1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/http/transport_security_state.h"
6
7 #include <stdint.h>
8
9 #include <algorithm>
10 #include <iterator>
11 #include <memory>
12 #include <string>
13 #include <vector>
14
15 #include "base/base64.h"
16 #include "base/files/file_path.h"
17 #include "base/functional/callback_helpers.h"
18 #include "base/json/json_reader.h"
19 #include "base/memory/raw_ptr.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/metrics/field_trial_param_associator.h"
22 #include "base/rand_util.h"
23 #include "base/stl_util.h"
24 #include "base/strings/string_piece.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/test/metrics/histogram_tester.h"
27 #include "base/test/mock_entropy_provider.h"
28 #include "base/test/scoped_feature_list.h"
29 #include "base/time/time.h"
30 #include "base/values.h"
31 #include "build/build_config.h"
32 #include "crypto/openssl_util.h"
33 #include "crypto/sha2.h"
34 #include "net/base/features.h"
35 #include "net/base/hash_value.h"
36 #include "net/base/host_port_pair.h"
37 #include "net/base/net_errors.h"
38 #include "net/base/network_anonymization_key.h"
39 #include "net/base/schemeful_site.h"
40 #include "net/base/test_completion_callback.h"
41 #include "net/cert/asn1_util.h"
42 #include "net/cert/cert_verifier.h"
43 #include "net/cert/cert_verify_result.h"
44 #include "net/cert/ct_policy_status.h"
45 #include "net/cert/test_root_certs.h"
46 #include "net/cert/x509_certificate.h"
47 #include "net/extras/preload_data/decoder.h"
48 #include "net/http/http_status_code.h"
49 #include "net/http/http_util.h"
50 #include "net/http/transport_security_state_source.h"
51 #include "net/net_buildflags.h"
52 #include "net/ssl/ssl_info.h"
53 #include "net/test/cert_test_util.h"
54 #include "net/test/test_data_directory.h"
55 #include "net/test/test_with_task_environment.h"
56 #include "net/tools/huffman_trie/bit_writer.h"
57 #include "net/tools/huffman_trie/trie/trie_bit_buffer.h"
58 #include "testing/gmock/include/gmock/gmock.h"
59 #include "testing/gtest/include/gtest/gtest.h"
60 #include "url/origin.h"
61
62 namespace net {
63
64 namespace {
65
66 namespace test_default {
67 #include "net/http/transport_security_state_static_unittest_default.h"
68 }
69 namespace test1 {
70 #include "net/http/transport_security_state_static_unittest1.h"
71 }
72 namespace test2 {
73 #include "net/http/transport_security_state_static_unittest2.h"
74 }
75 namespace test3 {
76 #include "net/http/transport_security_state_static_unittest3.h"
77 }
78
79 const char kHost[] = "example.test";
80 const uint16_t kPort = 443;
81 const char kReportUri[] = "http://report-example.test/test";
82
83 const char* const kGoodPath[] = {
84 "sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=",
85 "sha256/fzP+pVAbH0hRoUphJKenIP8+2tD/d2QH9J+kQNieM6Q=",
86 "sha256/9vRUVdjloCa4wXUKfDWotV5eUXYD7vu0v0z9SRzQdzg=",
87 "sha256/Nn8jk5By4Vkq6BeOVZ7R7AC6XUUBZsWmUbJR1f1Y5FY=",
88 nullptr,
89 };
90
91 const char* const kBadPath[] = {
92 "sha256/1111111111111111111111111111111111111111111=",
93 "sha256/2222222222222222222222222222222222222222222=",
94 "sha256/3333333333333333333333333333333333333333333=",
95 nullptr,
96 };
97
98 // A mock ReportSenderInterface that just remembers the latest report
99 // URI and report to be sent.
100 class MockCertificateReportSender
101 : public TransportSecurityState::ReportSenderInterface {
102 public:
103 MockCertificateReportSender() = default;
104 ~MockCertificateReportSender() override = default;
105
Send(const GURL & report_uri,base::StringPiece content_type,base::StringPiece report,const NetworkAnonymizationKey & network_anonymization_key,base::OnceCallback<void ()> success_callback,base::OnceCallback<void (const GURL &,int,int)> error_callback)106 void Send(
107 const GURL& report_uri,
108 base::StringPiece content_type,
109 base::StringPiece report,
110 const NetworkAnonymizationKey& network_anonymization_key,
111 base::OnceCallback<void()> success_callback,
112 base::OnceCallback<void(const GURL&, int, int)> error_callback) override {
113 latest_report_uri_ = report_uri;
114 latest_report_.assign(report.data(), report.size());
115 latest_content_type_.assign(content_type.data(), content_type.size());
116 latest_network_anonymization_key_ = network_anonymization_key;
117 }
118
Clear()119 void Clear() {
120 latest_report_uri_ = GURL();
121 latest_report_ = std::string();
122 latest_content_type_ = std::string();
123 latest_network_anonymization_key_ = NetworkAnonymizationKey();
124 }
125
latest_report_uri()126 const GURL& latest_report_uri() { return latest_report_uri_; }
latest_report()127 const std::string& latest_report() { return latest_report_; }
latest_content_type()128 const std::string& latest_content_type() { return latest_content_type_; }
latest_network_anonymization_key()129 const NetworkAnonymizationKey& latest_network_anonymization_key() {
130 return latest_network_anonymization_key_;
131 }
132
133 private:
134 GURL latest_report_uri_;
135 std::string latest_report_;
136 std::string latest_content_type_;
137 NetworkAnonymizationKey latest_network_anonymization_key_;
138 };
139
140 // A mock ReportSenderInterface that simulates a net error on every report sent.
141 class MockFailingCertificateReportSender
142 : public TransportSecurityState::ReportSenderInterface {
143 public:
144 MockFailingCertificateReportSender() = default;
145 ~MockFailingCertificateReportSender() override = default;
146
net_error()147 int net_error() { return net_error_; }
148
149 // TransportSecurityState::ReportSenderInterface:
Send(const GURL & report_uri,base::StringPiece content_type,base::StringPiece report,const NetworkAnonymizationKey & network_anonymization_key,base::OnceCallback<void ()> success_callback,base::OnceCallback<void (const GURL &,int,int)> error_callback)150 void Send(
151 const GURL& report_uri,
152 base::StringPiece content_type,
153 base::StringPiece report,
154 const NetworkAnonymizationKey& network_anonymization_key,
155 base::OnceCallback<void()> success_callback,
156 base::OnceCallback<void(const GURL&, int, int)> error_callback) override {
157 ASSERT_FALSE(error_callback.is_null());
158 std::move(error_callback).Run(report_uri, net_error_, 0);
159 }
160
161 private:
162 const int net_error_ = ERR_CONNECTION_FAILED;
163 };
164
165 class MockRequireCTDelegate : public TransportSecurityState::RequireCTDelegate {
166 public:
167 MOCK_METHOD3(IsCTRequiredForHost,
168 CTRequirementLevel(const std::string& hostname,
169 const X509Certificate* chain,
170 const HashValueVector& hashes));
171 };
172
CompareCertificateChainWithList(const scoped_refptr<X509Certificate> & cert_chain,const base::Value * cert_list)173 void CompareCertificateChainWithList(
174 const scoped_refptr<X509Certificate>& cert_chain,
175 const base::Value* cert_list) {
176 ASSERT_TRUE(cert_chain);
177 ASSERT_TRUE(cert_list->is_list());
178 std::vector<std::string> pem_encoded_chain;
179 cert_chain->GetPEMEncodedChain(&pem_encoded_chain);
180 ASSERT_EQ(pem_encoded_chain.size(), cert_list->GetList().size());
181
182 for (size_t i = 0; i < pem_encoded_chain.size(); i++) {
183 const std::string& list_cert = cert_list->GetList()[i].GetString();
184 EXPECT_EQ(pem_encoded_chain[i], list_cert);
185 }
186 }
187
CheckHPKPReport(const std::string & report,const HostPortPair & host_port_pair,bool include_subdomains,const std::string & noted_hostname,const scoped_refptr<X509Certificate> & served_certificate_chain,const scoped_refptr<X509Certificate> & validated_certificate_chain,const HashValueVector & known_pins)188 void CheckHPKPReport(
189 const std::string& report,
190 const HostPortPair& host_port_pair,
191 bool include_subdomains,
192 const std::string& noted_hostname,
193 const scoped_refptr<X509Certificate>& served_certificate_chain,
194 const scoped_refptr<X509Certificate>& validated_certificate_chain,
195 const HashValueVector& known_pins) {
196 absl::optional<base::Value> value = base::JSONReader::Read(report);
197 ASSERT_TRUE(value.has_value());
198 const base::Value::Dict* report_dict = value.value().GetIfDict();
199 ASSERT_TRUE(report_dict);
200
201 const std::string* report_hostname = report_dict->FindString("hostname");
202 ASSERT_TRUE(report_hostname);
203 EXPECT_EQ(host_port_pair.host(), *report_hostname);
204
205 absl::optional<int> report_port = report_dict->FindInt("port");
206 ASSERT_TRUE(report_port.has_value());
207 EXPECT_EQ(host_port_pair.port(), report_port.value());
208
209 absl::optional<bool> report_include_subdomains =
210 report_dict->FindBool("include-subdomains");
211 ASSERT_TRUE(report_include_subdomains.has_value());
212 EXPECT_EQ(include_subdomains, report_include_subdomains.value());
213
214 const std::string* report_noted_hostname =
215 report_dict->FindString("noted-hostname");
216 ASSERT_TRUE(report_noted_hostname);
217 EXPECT_EQ(noted_hostname, *report_noted_hostname);
218
219 // TODO(estark): check times in RFC3339 format.
220
221 const std::string* report_expiration =
222 report_dict->FindString("effective-expiration-date");
223 ASSERT_TRUE(report_expiration);
224 EXPECT_FALSE(report_expiration->empty());
225
226 const std::string* report_date = report_dict->FindString("date-time");
227 ASSERT_TRUE(report_date);
228 EXPECT_FALSE(report_date->empty());
229
230 const base::Value* report_served_certificate_chain =
231 report_dict->Find("served-certificate-chain");
232 ASSERT_TRUE(report_served_certificate_chain);
233 ASSERT_NO_FATAL_FAILURE(CompareCertificateChainWithList(
234 served_certificate_chain, report_served_certificate_chain));
235
236 const base::Value* report_validated_certificate_chain =
237 report_dict->Find("validated-certificate-chain");
238 ASSERT_TRUE(report_validated_certificate_chain);
239 ASSERT_NO_FATAL_FAILURE(CompareCertificateChainWithList(
240 validated_certificate_chain, report_validated_certificate_chain));
241 }
242
operator ==(const TransportSecurityState::STSState & lhs,const TransportSecurityState::STSState & rhs)243 bool operator==(const TransportSecurityState::STSState& lhs,
244 const TransportSecurityState::STSState& rhs) {
245 return lhs.last_observed == rhs.last_observed && lhs.expiry == rhs.expiry &&
246 lhs.upgrade_mode == rhs.upgrade_mode &&
247 lhs.include_subdomains == rhs.include_subdomains &&
248 lhs.domain == rhs.domain;
249 }
250
operator ==(const TransportSecurityState::PKPState & lhs,const TransportSecurityState::PKPState & rhs)251 bool operator==(const TransportSecurityState::PKPState& lhs,
252 const TransportSecurityState::PKPState& rhs) {
253 return lhs.last_observed == rhs.last_observed && lhs.expiry == rhs.expiry &&
254 lhs.spki_hashes == rhs.spki_hashes &&
255 lhs.bad_spki_hashes == rhs.bad_spki_hashes &&
256 lhs.include_subdomains == rhs.include_subdomains &&
257 lhs.domain == rhs.domain && lhs.report_uri == rhs.report_uri;
258 }
259
260 } // namespace
261
262 class TransportSecurityStateTest : public ::testing::Test,
263 public WithTaskEnvironment {
264 public:
TransportSecurityStateTest()265 TransportSecurityStateTest()
266 : WithTaskEnvironment(
267 base::test::TaskEnvironment::TimeSource::MOCK_TIME) {
268 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
269 // Need mocked out time for pruning tests. Don't start with a
270 // time of 0, as code doesn't generally expect it.
271 FastForwardBy(base::Days(1));
272 }
273
~TransportSecurityStateTest()274 ~TransportSecurityStateTest() override {
275 SetTransportSecurityStateSourceForTesting(nullptr);
276 }
277
SetUp()278 void SetUp() override { crypto::EnsureOpenSSLInit(); }
279
DisableStaticPins(TransportSecurityState * state)280 static void DisableStaticPins(TransportSecurityState* state) {
281 state->enable_static_pins_ = false;
282 }
283
EnableStaticPins(TransportSecurityState * state)284 static void EnableStaticPins(TransportSecurityState* state) {
285 state->enable_static_pins_ = true;
286 state->SetPinningListAlwaysTimelyForTesting(true);
287 }
288
GetSampleSPKIHashes()289 static HashValueVector GetSampleSPKIHashes() {
290 HashValueVector spki_hashes;
291 HashValue hash(HASH_VALUE_SHA256);
292 memset(hash.data(), 0, hash.size());
293 spki_hashes.push_back(hash);
294 return spki_hashes;
295 }
296
GetSampleSPKIHash(uint8_t value)297 static HashValue GetSampleSPKIHash(uint8_t value) {
298 HashValue hash(HASH_VALUE_SHA256);
299 memset(hash.data(), value, hash.size());
300 return hash;
301 }
302
303 protected:
GetStaticDomainState(TransportSecurityState * state,const std::string & host,TransportSecurityState::STSState * sts_result,TransportSecurityState::PKPState * pkp_result)304 bool GetStaticDomainState(TransportSecurityState* state,
305 const std::string& host,
306 TransportSecurityState::STSState* sts_result,
307 TransportSecurityState::PKPState* pkp_result) {
308 bool ret = state->GetStaticSTSState(host, sts_result);
309 if (state->GetStaticPKPState(host, pkp_result))
310 ret = true;
311 return ret;
312 }
313
314 private:
315 base::test::ScopedFeatureList scoped_feature_list_;
316 };
317
TEST_F(TransportSecurityStateTest,DomainNameOddities)318 TEST_F(TransportSecurityStateTest, DomainNameOddities) {
319 TransportSecurityState state;
320 const base::Time current_time(base::Time::Now());
321 const base::Time expiry = current_time + base::Seconds(1000);
322
323 // DNS suffix search tests. Some DNS resolvers allow a terminal "." to
324 // indicate not perform DNS suffix searching. Ensure that regardless
325 // of how this is treated at the resolver layer, or at the URL/origin
326 // layer (that is, whether they are treated as equivalent or distinct),
327 // ensure that for policy matching, something lacking a terminal "."
328 // is equivalent to something with a terminal "."
329 EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
330
331 state.AddHSTS("example.com", expiry, true /* include_subdomains */);
332 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
333 // Trailing '.' should be equivalent; it's just a resolver hint
334 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com."));
335 // Leading '.' should be invalid
336 EXPECT_FALSE(state.ShouldUpgradeToSSL(".example.com"));
337 // Subdomains should work regardless
338 EXPECT_TRUE(state.ShouldUpgradeToSSL("sub.example.com"));
339 EXPECT_TRUE(state.ShouldUpgradeToSSL("sub.example.com."));
340 // But invalid subdomains should be rejected
341 EXPECT_FALSE(state.ShouldUpgradeToSSL("sub..example.com"));
342 EXPECT_FALSE(state.ShouldUpgradeToSSL("sub..example.com."));
343
344 // Now try the inverse form
345 TransportSecurityState state2;
346 state2.AddHSTS("example.net.", expiry, true /* include_subdomains */);
347 EXPECT_TRUE(state2.ShouldUpgradeToSSL("example.net."));
348 EXPECT_TRUE(state2.ShouldUpgradeToSSL("example.net"));
349 EXPECT_TRUE(state2.ShouldUpgradeToSSL("sub.example.net."));
350 EXPECT_TRUE(state2.ShouldUpgradeToSSL("sub.example.net"));
351
352 // Finally, test weird things
353 TransportSecurityState state3;
354 state3.AddHSTS("", expiry, true /* include_subdomains */);
355 EXPECT_FALSE(state3.ShouldUpgradeToSSL(""));
356 EXPECT_FALSE(state3.ShouldUpgradeToSSL("."));
357 EXPECT_FALSE(state3.ShouldUpgradeToSSL("..."));
358 // Make sure it didn't somehow apply HSTS to the world
359 EXPECT_FALSE(state3.ShouldUpgradeToSSL("example.org"));
360
361 TransportSecurityState state4;
362 state4.AddHSTS(".", expiry, true /* include_subdomains */);
363 EXPECT_FALSE(state4.ShouldUpgradeToSSL(""));
364 EXPECT_FALSE(state4.ShouldUpgradeToSSL("."));
365 EXPECT_FALSE(state4.ShouldUpgradeToSSL("..."));
366 EXPECT_FALSE(state4.ShouldUpgradeToSSL("example.org"));
367
368 // Now do the same for preloaded entries
369 TransportSecurityState state5;
370 EXPECT_TRUE(state5.ShouldUpgradeToSSL("hsts-preloaded.test"));
371 EXPECT_TRUE(state5.ShouldUpgradeToSSL("hsts-preloaded.test."));
372 EXPECT_FALSE(state5.ShouldUpgradeToSSL("hsts-preloaded..test"));
373 EXPECT_FALSE(state5.ShouldUpgradeToSSL("hsts-preloaded..test."));
374 }
375
TEST_F(TransportSecurityStateTest,SimpleMatches)376 TEST_F(TransportSecurityStateTest, SimpleMatches) {
377 TransportSecurityState state;
378 const base::Time current_time(base::Time::Now());
379 const base::Time expiry = current_time + base::Seconds(1000);
380
381 EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
382 bool include_subdomains = false;
383 state.AddHSTS("example.com", expiry, include_subdomains);
384 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
385 EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example.com"));
386 EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example.com"));
387 EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("foo.example.com"));
388 }
389
TEST_F(TransportSecurityStateTest,MatchesCase1)390 TEST_F(TransportSecurityStateTest, MatchesCase1) {
391 TransportSecurityState state;
392 const base::Time current_time(base::Time::Now());
393 const base::Time expiry = current_time + base::Seconds(1000);
394
395 EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
396 bool include_subdomains = false;
397 state.AddHSTS("EXample.coM", expiry, include_subdomains);
398 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
399 }
400
TEST_F(TransportSecurityStateTest,MatchesCase2)401 TEST_F(TransportSecurityStateTest, MatchesCase2) {
402 TransportSecurityState state;
403 const base::Time current_time(base::Time::Now());
404 const base::Time expiry = current_time + base::Seconds(1000);
405
406 // Check dynamic entries
407 EXPECT_FALSE(state.ShouldUpgradeToSSL("EXample.coM"));
408 bool include_subdomains = false;
409 state.AddHSTS("example.com", expiry, include_subdomains);
410 EXPECT_TRUE(state.ShouldUpgradeToSSL("EXample.coM"));
411
412 // Check static entries
413 EXPECT_TRUE(state.ShouldUpgradeToSSL("hStS-prelOAded.tEsT"));
414 EXPECT_TRUE(
415 state.ShouldUpgradeToSSL("inClude-subDOmaIns-hsts-prEloaDed.TesT"));
416 }
417
TEST_F(TransportSecurityStateTest,SubdomainMatches)418 TEST_F(TransportSecurityStateTest, SubdomainMatches) {
419 TransportSecurityState state;
420 const base::Time current_time(base::Time::Now());
421 const base::Time expiry = current_time + base::Seconds(1000);
422
423 EXPECT_FALSE(state.ShouldUpgradeToSSL("example.test"));
424 bool include_subdomains = true;
425 state.AddHSTS("example.test", expiry, include_subdomains);
426 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.test"));
427 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example.test"));
428 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.bar.example.test"));
429 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.bar.baz.example.test"));
430 EXPECT_FALSE(state.ShouldUpgradeToSSL("test"));
431 EXPECT_FALSE(state.ShouldUpgradeToSSL("notexample.test"));
432 }
433
434 // Tests that a more-specific HSTS rule without the includeSubDomains bit does
435 // not override a less-specific rule with includeSubDomains. Applicability is
436 // checked before specificity. See https://crbug.com/821811.
TEST_F(TransportSecurityStateTest,STSSubdomainNoOverride)437 TEST_F(TransportSecurityStateTest, STSSubdomainNoOverride) {
438 const GURL report_uri(kReportUri);
439 TransportSecurityState state;
440 const base::Time current_time(base::Time::Now());
441 const base::Time expiry = current_time + base::Seconds(1000);
442 const base::Time older = current_time - base::Seconds(1000);
443
444 state.AddHSTS("example.test", expiry, true);
445 state.AddHSTS("foo.example.test", expiry, false);
446
447 // The example.test rule applies to the entire domain, including subdomains of
448 // foo.example.test.
449 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.test"));
450 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example.test"));
451 EXPECT_TRUE(state.ShouldUpgradeToSSL("bar.foo.example.test"));
452 EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example.test"));
453
454 // Expire the foo.example.test rule.
455 state.AddHSTS("foo.example.test", older, false);
456
457 // The example.test rule still applies.
458 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.test"));
459 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example.test"));
460 EXPECT_TRUE(state.ShouldUpgradeToSSL("bar.foo.example.test"));
461 EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example.test"));
462 }
463
464 // Tests that a more-specific HPKP rule overrides a less-specific rule
465 // with it, regardless of the includeSubDomains bit. Note this behavior does not
466 // match HSTS. See https://crbug.com/821811.
TEST_F(TransportSecurityStateTest,PKPSubdomainCarveout)467 TEST_F(TransportSecurityStateTest, PKPSubdomainCarveout) {
468 const GURL report_uri(kReportUri);
469 TransportSecurityState state;
470 const base::Time current_time(base::Time::Now());
471 const base::Time expiry = current_time + base::Seconds(1000);
472 const base::Time older = current_time - base::Seconds(1000);
473
474 state.AddHPKP("example.test", expiry, true, GetSampleSPKIHashes(),
475 report_uri);
476 state.AddHPKP("foo.example.test", expiry, false, GetSampleSPKIHashes(),
477 report_uri);
478 EXPECT_TRUE(state.HasPublicKeyPins("example.test"));
479 EXPECT_TRUE(state.HasPublicKeyPins("foo.example.test"));
480
481 // The foo.example.test rule overrides the example1.test rule, so
482 // bar.foo.example.test has no HPKP state.
483 EXPECT_FALSE(state.HasPublicKeyPins("bar.foo.example.test"));
484 EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("bar.foo.example.test"));
485
486 // Expire the foo.example.test rule.
487 state.AddHPKP("foo.example.test", older, false, GetSampleSPKIHashes(),
488 report_uri);
489
490 // Now the base example.test rule applies to bar.foo.example.test.
491 EXPECT_TRUE(state.HasPublicKeyPins("bar.foo.example.test"));
492 EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("bar.foo.example.test"));
493 }
494
TEST_F(TransportSecurityStateTest,FatalSSLErrors)495 TEST_F(TransportSecurityStateTest, FatalSSLErrors) {
496 const GURL report_uri(kReportUri);
497 TransportSecurityState state;
498 const base::Time current_time(base::Time::Now());
499 const base::Time expiry = current_time + base::Seconds(1000);
500
501 state.AddHSTS("example1.test", expiry, false);
502 state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
503 report_uri);
504
505 // The presense of either HSTS or HPKP is enough to make SSL errors fatal.
506 EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example1.test"));
507 EXPECT_TRUE(state.ShouldSSLErrorsBeFatal("example2.test"));
508 }
509
510 // Tests that HPKP and HSTS state both expire. Also tests that expired entries
511 // are pruned.
TEST_F(TransportSecurityStateTest,Expiration)512 TEST_F(TransportSecurityStateTest, Expiration) {
513 const GURL report_uri(kReportUri);
514 TransportSecurityState state;
515 const base::Time current_time(base::Time::Now());
516 const base::Time expiry = current_time + base::Seconds(1000);
517 const base::Time older = current_time - base::Seconds(1000);
518
519 // Note: this test assumes that inserting an entry with an expiration time in
520 // the past works and is pruned on query.
521 state.AddHSTS("example1.test", older, false);
522 EXPECT_TRUE(TransportSecurityState::STSStateIterator(state).HasNext());
523 EXPECT_FALSE(state.ShouldUpgradeToSSL("example1.test"));
524 // Querying |state| for a domain should flush out expired entries.
525 EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
526
527 state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
528 report_uri);
529 EXPECT_TRUE(state.has_dynamic_pkp_state());
530 EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
531 // Querying |state| for a domain should flush out expired entries.
532 EXPECT_FALSE(state.has_dynamic_pkp_state());
533
534 state.AddHSTS("example1.test", older, false);
535 state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
536 report_uri);
537 EXPECT_TRUE(TransportSecurityState::STSStateIterator(state).HasNext());
538 EXPECT_TRUE(state.has_dynamic_pkp_state());
539 EXPECT_FALSE(state.ShouldSSLErrorsBeFatal("example1.test"));
540 // Querying |state| for a domain should flush out expired entries.
541 EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
542 EXPECT_FALSE(state.has_dynamic_pkp_state());
543
544 // Test that HSTS can outlive HPKP.
545 state.AddHSTS("example1.test", expiry, false);
546 state.AddHPKP("example1.test", older, false, GetSampleSPKIHashes(),
547 report_uri);
548 EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
549 EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
550
551 // Test that HPKP can outlive HSTS.
552 state.AddHSTS("example2.test", older, false);
553 state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
554 report_uri);
555 EXPECT_FALSE(state.ShouldUpgradeToSSL("example2.test"));
556 EXPECT_TRUE(state.HasPublicKeyPins("example2.test"));
557 }
558
559 // Tests that HPKP and HSTS state are queried independently for subdomain
560 // matches.
TEST_F(TransportSecurityStateTest,IndependentSubdomain)561 TEST_F(TransportSecurityStateTest, IndependentSubdomain) {
562 const GURL report_uri(kReportUri);
563 TransportSecurityState state;
564 const base::Time current_time(base::Time::Now());
565 const base::Time expiry = current_time + base::Seconds(1000);
566
567 state.AddHSTS("example1.test", expiry, true);
568 state.AddHPKP("example1.test", expiry, false, GetSampleSPKIHashes(),
569 report_uri);
570
571 state.AddHSTS("example2.test", expiry, false);
572 state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes(),
573 report_uri);
574
575 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example1.test"));
576 EXPECT_FALSE(state.HasPublicKeyPins("foo.example1.test"));
577 EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example2.test"));
578 EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
579 }
580
581 // Tests that HPKP and HSTS state are inserted and overridden independently.
TEST_F(TransportSecurityStateTest,IndependentInsertion)582 TEST_F(TransportSecurityStateTest, IndependentInsertion) {
583 const GURL report_uri(kReportUri);
584 TransportSecurityState state;
585 const base::Time current_time(base::Time::Now());
586 const base::Time expiry = current_time + base::Seconds(1000);
587
588 // Place an includeSubdomains HSTS entry below a normal HPKP entry.
589 state.AddHSTS("example1.test", expiry, true);
590 state.AddHPKP("foo.example1.test", expiry, false, GetSampleSPKIHashes(),
591 report_uri);
592
593 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example1.test"));
594 EXPECT_TRUE(state.HasPublicKeyPins("foo.example1.test"));
595 EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
596 EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
597
598 // Drop the includeSubdomains from the HSTS entry.
599 state.AddHSTS("example1.test", expiry, false);
600
601 EXPECT_FALSE(state.ShouldUpgradeToSSL("foo.example1.test"));
602 EXPECT_TRUE(state.HasPublicKeyPins("foo.example1.test"));
603
604 // Place an includeSubdomains HPKP entry below a normal HSTS entry.
605 state.AddHSTS("foo.example2.test", expiry, false);
606 state.AddHPKP("example2.test", expiry, true, GetSampleSPKIHashes(),
607 report_uri);
608
609 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example2.test"));
610 EXPECT_TRUE(state.HasPublicKeyPins("foo.example2.test"));
611
612 // Drop the includeSubdomains from the HSTS entry.
613 state.AddHPKP("example2.test", expiry, false, GetSampleSPKIHashes(),
614 report_uri);
615
616 EXPECT_TRUE(state.ShouldUpgradeToSSL("foo.example2.test"));
617 EXPECT_FALSE(state.HasPublicKeyPins("foo.example2.test"));
618 }
619
620 // Tests that GetDynamic[PKP|STS]State returns the correct data and that the
621 // states are not mixed together.
TEST_F(TransportSecurityStateTest,DynamicDomainState)622 TEST_F(TransportSecurityStateTest, DynamicDomainState) {
623 const GURL report_uri(kReportUri);
624 TransportSecurityState state;
625 const base::Time current_time(base::Time::Now());
626 const base::Time expiry1 = current_time + base::Seconds(1000);
627 const base::Time expiry2 = current_time + base::Seconds(2000);
628
629 state.AddHSTS("example.com", expiry1, true);
630 state.AddHPKP("foo.example.com", expiry2, false, GetSampleSPKIHashes(),
631 report_uri);
632
633 TransportSecurityState::STSState sts_state;
634 TransportSecurityState::PKPState pkp_state;
635 ASSERT_TRUE(state.GetDynamicSTSState("foo.example.com", &sts_state));
636 ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
637 EXPECT_TRUE(sts_state.ShouldUpgradeToSSL());
638 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
639 EXPECT_TRUE(sts_state.include_subdomains);
640 EXPECT_FALSE(pkp_state.include_subdomains);
641 EXPECT_EQ(expiry1, sts_state.expiry);
642 EXPECT_EQ(expiry2, pkp_state.expiry);
643 EXPECT_EQ("example.com", sts_state.domain);
644 EXPECT_EQ("foo.example.com", pkp_state.domain);
645 }
646
647 // Tests that new pins always override previous pins. This should be true for
648 // both pins at the same domain or includeSubdomains pins at a parent domain.
TEST_F(TransportSecurityStateTest,NewPinsOverride)649 TEST_F(TransportSecurityStateTest, NewPinsOverride) {
650 const GURL report_uri(kReportUri);
651 TransportSecurityState state;
652 TransportSecurityState::PKPState pkp_state;
653 const base::Time current_time(base::Time::Now());
654 const base::Time expiry = current_time + base::Seconds(1000);
655 HashValue hash1(HASH_VALUE_SHA256);
656 memset(hash1.data(), 0x01, hash1.size());
657 HashValue hash2(HASH_VALUE_SHA256);
658 memset(hash2.data(), 0x02, hash1.size());
659 HashValue hash3(HASH_VALUE_SHA256);
660 memset(hash3.data(), 0x03, hash1.size());
661
662 state.AddHPKP("example.com", expiry, true, HashValueVector(1, hash1),
663 report_uri);
664
665 ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
666 ASSERT_EQ(1u, pkp_state.spki_hashes.size());
667 EXPECT_EQ(pkp_state.spki_hashes[0], hash1);
668
669 state.AddHPKP("foo.example.com", expiry, false, HashValueVector(1, hash2),
670 report_uri);
671
672 ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
673 ASSERT_EQ(1u, pkp_state.spki_hashes.size());
674 EXPECT_EQ(pkp_state.spki_hashes[0], hash2);
675
676 state.AddHPKP("foo.example.com", expiry, false, HashValueVector(1, hash3),
677 report_uri);
678
679 ASSERT_TRUE(state.GetDynamicPKPState("foo.example.com", &pkp_state));
680 ASSERT_EQ(1u, pkp_state.spki_hashes.size());
681 EXPECT_EQ(pkp_state.spki_hashes[0], hash3);
682 }
683
TEST_F(TransportSecurityStateTest,DeleteAllDynamicDataBetween)684 TEST_F(TransportSecurityStateTest, DeleteAllDynamicDataBetween) {
685 TransportSecurityState state;
686 const base::Time current_time(base::Time::Now());
687 const base::Time expiry = current_time + base::Seconds(1000);
688 const base::Time older = current_time - base::Seconds(1000);
689
690 EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
691 EXPECT_FALSE(state.HasPublicKeyPins("example.com"));
692 bool include_subdomains = false;
693 state.AddHSTS("example.com", expiry, include_subdomains);
694 state.AddHPKP("example.com", expiry, include_subdomains,
695 GetSampleSPKIHashes(), GURL());
696
697 state.DeleteAllDynamicDataBetween(expiry, base::Time::Max(),
698 base::DoNothing());
699 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
700 EXPECT_TRUE(state.HasPublicKeyPins("example.com"));
701
702 state.DeleteAllDynamicDataBetween(older, current_time, base::DoNothing());
703 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
704 EXPECT_TRUE(state.HasPublicKeyPins("example.com"));
705
706 state.DeleteAllDynamicDataBetween(base::Time(), current_time,
707 base::DoNothing());
708 EXPECT_TRUE(state.ShouldUpgradeToSSL("example.com"));
709 EXPECT_TRUE(state.HasPublicKeyPins("example.com"));
710
711 state.DeleteAllDynamicDataBetween(older, base::Time::Max(),
712 base::DoNothing());
713 EXPECT_FALSE(state.ShouldUpgradeToSSL("example.com"));
714 EXPECT_FALSE(state.HasPublicKeyPins("example.com"));
715
716 // Dynamic data in |state| should be empty now.
717 EXPECT_FALSE(TransportSecurityState::STSStateIterator(state).HasNext());
718 EXPECT_FALSE(state.has_dynamic_pkp_state());
719 }
720
TEST_F(TransportSecurityStateTest,DeleteDynamicDataForHost)721 TEST_F(TransportSecurityStateTest, DeleteDynamicDataForHost) {
722 TransportSecurityState state;
723 const base::Time current_time(base::Time::Now());
724 const base::Time expiry = current_time + base::Seconds(1000);
725 bool include_subdomains = false;
726
727 state.AddHSTS("example1.test", expiry, include_subdomains);
728 state.AddHPKP("example1.test", expiry, include_subdomains,
729 GetSampleSPKIHashes(), GURL());
730
731 EXPECT_TRUE(state.ShouldUpgradeToSSL("example1.test"));
732 EXPECT_FALSE(state.ShouldUpgradeToSSL("example2.test"));
733 EXPECT_TRUE(state.HasPublicKeyPins("example1.test"));
734 EXPECT_FALSE(state.HasPublicKeyPins("example2.test"));
735
736 EXPECT_TRUE(state.DeleteDynamicDataForHost("example1.test"));
737 EXPECT_FALSE(state.ShouldUpgradeToSSL("example1.test"));
738 EXPECT_FALSE(state.HasPublicKeyPins("example1.test"));
739 }
740
TEST_F(TransportSecurityStateTest,LongNames)741 TEST_F(TransportSecurityStateTest, LongNames) {
742 TransportSecurityState state;
743 state.SetPinningListAlwaysTimelyForTesting(true);
744 const char kLongName[] =
745 "lookupByWaveIdHashAndWaveIdIdAndWaveIdDomainAndWaveletIdIdAnd"
746 "WaveletIdDomainAndBlipBlipid";
747 TransportSecurityState::STSState sts_state;
748 TransportSecurityState::PKPState pkp_state;
749 // Just checks that we don't hit a NOTREACHED
750 EXPECT_FALSE(state.GetStaticSTSState(kLongName, &sts_state));
751 EXPECT_FALSE(state.GetStaticPKPState(kLongName, &pkp_state));
752 EXPECT_FALSE(state.GetDynamicSTSState(kLongName, &sts_state));
753 EXPECT_FALSE(state.GetDynamicPKPState(kLongName, &pkp_state));
754 }
755
AddHash(const std::string & type_and_base64,HashValueVector * out)756 static bool AddHash(const std::string& type_and_base64, HashValueVector* out) {
757 HashValue hash;
758 if (!hash.FromString(type_and_base64))
759 return false;
760
761 out->push_back(hash);
762 return true;
763 }
764
TEST_F(TransportSecurityStateTest,PinValidationWithoutRejectedCerts)765 TEST_F(TransportSecurityStateTest, PinValidationWithoutRejectedCerts) {
766 base::test::ScopedFeatureList scoped_feature_list_;
767 scoped_feature_list_.InitAndEnableFeature(
768 net::features::kStaticKeyPinningEnforcement);
769 HashValueVector good_hashes, bad_hashes;
770
771 for (size_t i = 0; kGoodPath[i]; i++) {
772 EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
773 }
774 for (size_t i = 0; kBadPath[i]; i++) {
775 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
776 }
777
778 TransportSecurityState state;
779 state.SetPinningListAlwaysTimelyForTesting(true);
780 EnableStaticPins(&state);
781
782 TransportSecurityState::PKPState pkp_state;
783 EXPECT_TRUE(state.GetStaticPKPState("no-rejected-pins-pkp.preloaded.test",
784 &pkp_state));
785 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
786
787 std::string failure_log;
788 EXPECT_TRUE(pkp_state.CheckPublicKeyPins(good_hashes, &failure_log));
789 EXPECT_FALSE(pkp_state.CheckPublicKeyPins(bad_hashes, &failure_log));
790 }
791
792 // Tests that pinning violations on preloaded pins trigger reports when
793 // the preloaded pin contains a report URI.
TEST_F(TransportSecurityStateTest,PreloadedPKPReportUri)794 TEST_F(TransportSecurityStateTest, PreloadedPKPReportUri) {
795 base::test::ScopedFeatureList scoped_feature_list_;
796 scoped_feature_list_.InitAndEnableFeature(
797 net::features::kStaticKeyPinningEnforcement);
798 const char kPreloadedPinDomain[] = "with-report-uri-pkp.preloaded.test";
799 HostPortPair host_port_pair(kPreloadedPinDomain, kPort);
800 net::NetworkAnonymizationKey network_anonymization_key =
801 NetworkAnonymizationKey::CreateTransient();
802
803 TransportSecurityState state;
804 state.SetPinningListAlwaysTimelyForTesting(true);
805 MockCertificateReportSender mock_report_sender;
806 state.SetReportSender(&mock_report_sender);
807
808 EnableStaticPins(&state);
809
810 TransportSecurityState::PKPState pkp_state;
811 ASSERT_TRUE(state.GetStaticPKPState(kPreloadedPinDomain, &pkp_state));
812 ASSERT_TRUE(pkp_state.HasPublicKeyPins());
813
814 GURL report_uri = pkp_state.report_uri;
815 ASSERT_TRUE(report_uri.is_valid());
816 ASSERT_FALSE(report_uri.is_empty());
817
818 // Two dummy certs to use as the server-sent and validated chains. The
819 // contents don't matter, as long as they are not the real google.com
820 // certs in the pins.
821 scoped_refptr<X509Certificate> cert1 =
822 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
823 ASSERT_TRUE(cert1);
824 scoped_refptr<X509Certificate> cert2 =
825 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
826 ASSERT_TRUE(cert2);
827
828 HashValueVector bad_hashes;
829 for (size_t i = 0; kBadPath[i]; i++)
830 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
831
832 // Trigger a violation and check that it sends a report.
833 std::string failure_log;
834 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
835 state.CheckPublicKeyPins(host_port_pair, true, bad_hashes,
836 cert1.get(), cert2.get(),
837 TransportSecurityState::ENABLE_PIN_REPORTS,
838 network_anonymization_key, &failure_log));
839
840 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
841
842 std::string report = mock_report_sender.latest_report();
843 ASSERT_FALSE(report.empty());
844 EXPECT_EQ("application/json; charset=utf-8",
845 mock_report_sender.latest_content_type());
846 ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(
847 report, host_port_pair, pkp_state.include_subdomains, pkp_state.domain,
848 cert1.get(), cert2.get(), pkp_state.spki_hashes));
849 EXPECT_EQ(network_anonymization_key,
850 mock_report_sender.latest_network_anonymization_key());
851
852 state.SetReportSender(nullptr);
853 }
854
855 // Tests that report URIs are thrown out if they point to the same host,
856 // over HTTPS, for which a pin was violated.
TEST_F(TransportSecurityStateTest,HPKPReportUriToSameHost)857 TEST_F(TransportSecurityStateTest, HPKPReportUriToSameHost) {
858 HostPortPair host_port_pair(kHost, kPort);
859 GURL https_report_uri("https://example.test/report");
860 GURL http_report_uri("http://example.test/report");
861 NetworkAnonymizationKey network_anonymization_key =
862 NetworkAnonymizationKey::CreateTransient();
863 TransportSecurityState state;
864 MockCertificateReportSender mock_report_sender;
865 state.SetReportSender(&mock_report_sender);
866
867 const base::Time current_time = base::Time::Now();
868 const base::Time expiry = current_time + base::Seconds(1000);
869 HashValueVector good_hashes;
870 for (size_t i = 0; kGoodPath[i]; i++)
871 EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
872
873 // Two dummy certs to use as the server-sent and validated chains. The
874 // contents don't matter, as long as they don't match the certs in the pins.
875 scoped_refptr<X509Certificate> cert1 =
876 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
877 ASSERT_TRUE(cert1);
878 scoped_refptr<X509Certificate> cert2 =
879 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
880 ASSERT_TRUE(cert2);
881
882 HashValueVector bad_hashes;
883 for (size_t i = 0; kBadPath[i]; i++)
884 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
885
886 state.AddHPKP(kHost, expiry, true, good_hashes, https_report_uri);
887
888 // Trigger a violation and check that it does not send a report
889 // because the report-uri is HTTPS and same-host as the pins.
890 std::string failure_log;
891 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
892 state.CheckPublicKeyPins(host_port_pair, true, bad_hashes,
893 cert1.get(), cert2.get(),
894 TransportSecurityState::ENABLE_PIN_REPORTS,
895 network_anonymization_key, &failure_log));
896
897 EXPECT_TRUE(mock_report_sender.latest_report_uri().is_empty());
898
899 // An HTTP report uri to the same host should be okay.
900 state.AddHPKP("example.test", expiry, true, good_hashes, http_report_uri);
901 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
902 state.CheckPublicKeyPins(host_port_pair, true, bad_hashes,
903 cert1.get(), cert2.get(),
904 TransportSecurityState::ENABLE_PIN_REPORTS,
905 network_anonymization_key, &failure_log));
906
907 EXPECT_EQ(http_report_uri, mock_report_sender.latest_report_uri());
908 EXPECT_EQ(network_anonymization_key,
909 mock_report_sender.latest_network_anonymization_key());
910
911 state.SetReportSender(nullptr);
912 }
913
914 // Simple test for the HSTS preload process. The trie (generated from
915 // transport_security_state_static_unittest1.json) contains 1 entry. Test that
916 // the lookup methods can find the entry and correctly decode the different
917 // preloaded states (HSTS and HPKP).
TEST_F(TransportSecurityStateTest,DecodePreloadedSingle)918 TEST_F(TransportSecurityStateTest, DecodePreloadedSingle) {
919 base::test::ScopedFeatureList scoped_feature_list_;
920 scoped_feature_list_.InitAndEnableFeature(
921 net::features::kStaticKeyPinningEnforcement);
922 SetTransportSecurityStateSourceForTesting(&test1::kHSTSSource);
923
924 TransportSecurityState state;
925 TransportSecurityStateTest::EnableStaticPins(&state);
926
927 TransportSecurityState::STSState sts_state;
928 TransportSecurityState::PKPState pkp_state;
929 EXPECT_TRUE(
930 GetStaticDomainState(&state, "hsts.example.com", &sts_state, &pkp_state));
931 EXPECT_TRUE(sts_state.include_subdomains);
932 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
933 sts_state.upgrade_mode);
934 EXPECT_TRUE(pkp_state.include_subdomains);
935 EXPECT_EQ(GURL(), pkp_state.report_uri);
936 ASSERT_EQ(1u, pkp_state.spki_hashes.size());
937 EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
938 ASSERT_EQ(1u, pkp_state.bad_spki_hashes.size());
939 EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x2));
940 }
941
942 // More advanced test for the HSTS preload process where the trie (generated
943 // from transport_security_state_static_unittest2.json) contains multiple
944 // entries with a common prefix. Test that the lookup methods can find all
945 // entries and correctly decode the different preloaded states (HSTS and HPKP)
946 // for each entry.
TEST_F(TransportSecurityStateTest,DecodePreloadedMultiplePrefix)947 TEST_F(TransportSecurityStateTest, DecodePreloadedMultiplePrefix) {
948 base::test::ScopedFeatureList scoped_feature_list_;
949 scoped_feature_list_.InitAndEnableFeature(
950 net::features::kStaticKeyPinningEnforcement);
951 SetTransportSecurityStateSourceForTesting(&test2::kHSTSSource);
952
953 TransportSecurityState state;
954 TransportSecurityStateTest::EnableStaticPins(&state);
955
956 TransportSecurityState::STSState sts_state;
957 TransportSecurityState::PKPState pkp_state;
958
959 EXPECT_TRUE(
960 GetStaticDomainState(&state, "hsts.example.com", &sts_state, &pkp_state));
961 EXPECT_FALSE(sts_state.include_subdomains);
962 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
963 sts_state.upgrade_mode);
964 EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
965
966 sts_state = TransportSecurityState::STSState();
967 pkp_state = TransportSecurityState::PKPState();
968 EXPECT_TRUE(
969 GetStaticDomainState(&state, "hpkp.example.com", &sts_state, &pkp_state));
970 EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
971 EXPECT_TRUE(pkp_state.include_subdomains);
972 EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
973 pkp_state.report_uri);
974 EXPECT_EQ(1U, pkp_state.spki_hashes.size());
975 EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
976 EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
977
978 sts_state = TransportSecurityState::STSState();
979 pkp_state = TransportSecurityState::PKPState();
980 EXPECT_TRUE(
981 GetStaticDomainState(&state, "mix.example.com", &sts_state, &pkp_state));
982 EXPECT_FALSE(sts_state.include_subdomains);
983 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
984 sts_state.upgrade_mode);
985 EXPECT_TRUE(pkp_state.include_subdomains);
986 EXPECT_EQ(GURL(), pkp_state.report_uri);
987 EXPECT_EQ(1U, pkp_state.spki_hashes.size());
988 EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x2));
989 EXPECT_EQ(1U, pkp_state.bad_spki_hashes.size());
990 EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x1));
991 }
992
993 // More advanced test for the HSTS preload process where the trie (generated
994 // from transport_security_state_static_unittest3.json) contains a mix of
995 // entries. Some entries share a prefix with the prefix also having its own
996 // preloaded state while others share no prefix. This results in a trie with
997 // several different internal structures. Test that the lookup methods can find
998 // all entries and correctly decode the different preloaded states (HSTS and
999 // HPKP) for each entry.
TEST_F(TransportSecurityStateTest,DecodePreloadedMultipleMix)1000 TEST_F(TransportSecurityStateTest, DecodePreloadedMultipleMix) {
1001 base::test::ScopedFeatureList scoped_feature_list_;
1002 scoped_feature_list_.InitAndEnableFeature(
1003 net::features::kStaticKeyPinningEnforcement);
1004 SetTransportSecurityStateSourceForTesting(&test3::kHSTSSource);
1005
1006 TransportSecurityState state;
1007 TransportSecurityStateTest::EnableStaticPins(&state);
1008
1009 TransportSecurityState::STSState sts_state;
1010 TransportSecurityState::PKPState pkp_state;
1011
1012 EXPECT_TRUE(
1013 GetStaticDomainState(&state, "example.com", &sts_state, &pkp_state));
1014 EXPECT_TRUE(sts_state.include_subdomains);
1015 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
1016 sts_state.upgrade_mode);
1017 EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
1018
1019 sts_state = TransportSecurityState::STSState();
1020 pkp_state = TransportSecurityState::PKPState();
1021 EXPECT_TRUE(
1022 GetStaticDomainState(&state, "hpkp.example.com", &sts_state, &pkp_state));
1023 EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
1024 EXPECT_TRUE(pkp_state.include_subdomains);
1025 EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
1026 pkp_state.report_uri);
1027 EXPECT_EQ(1U, pkp_state.spki_hashes.size());
1028 EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
1029 EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
1030
1031 sts_state = TransportSecurityState::STSState();
1032 pkp_state = TransportSecurityState::PKPState();
1033 EXPECT_TRUE(
1034 GetStaticDomainState(&state, "example.org", &sts_state, &pkp_state));
1035 EXPECT_FALSE(sts_state.include_subdomains);
1036 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
1037 sts_state.upgrade_mode);
1038 EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
1039
1040 sts_state = TransportSecurityState::STSState();
1041 pkp_state = TransportSecurityState::PKPState();
1042 EXPECT_TRUE(
1043 GetStaticDomainState(&state, "badssl.com", &sts_state, &pkp_state));
1044 EXPECT_TRUE(sts_state == TransportSecurityState::STSState());
1045 EXPECT_TRUE(pkp_state.include_subdomains);
1046 EXPECT_EQ(GURL("https://report.example.com/hpkp-upload"),
1047 pkp_state.report_uri);
1048 EXPECT_EQ(1U, pkp_state.spki_hashes.size());
1049 EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x1));
1050 EXPECT_EQ(0U, pkp_state.bad_spki_hashes.size());
1051
1052 sts_state = TransportSecurityState::STSState();
1053 pkp_state = TransportSecurityState::PKPState();
1054 EXPECT_TRUE(
1055 GetStaticDomainState(&state, "mix.badssl.com", &sts_state, &pkp_state));
1056 EXPECT_FALSE(sts_state.include_subdomains);
1057 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
1058 sts_state.upgrade_mode);
1059 EXPECT_TRUE(pkp_state.include_subdomains);
1060 EXPECT_EQ(GURL(), pkp_state.report_uri);
1061 EXPECT_EQ(1U, pkp_state.spki_hashes.size());
1062 EXPECT_EQ(pkp_state.spki_hashes[0], GetSampleSPKIHash(0x2));
1063 EXPECT_EQ(1U, pkp_state.bad_spki_hashes.size());
1064 EXPECT_EQ(pkp_state.bad_spki_hashes[0], GetSampleSPKIHash(0x1));
1065
1066 sts_state = TransportSecurityState::STSState();
1067 pkp_state = TransportSecurityState::PKPState();
1068
1069 // This should be a simple entry in the context of
1070 // TrieWriter::IsSimpleEntry().
1071 EXPECT_TRUE(GetStaticDomainState(&state, "simple-entry.example.com",
1072 &sts_state, &pkp_state));
1073 EXPECT_TRUE(sts_state.include_subdomains);
1074 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
1075 sts_state.upgrade_mode);
1076 EXPECT_TRUE(pkp_state == TransportSecurityState::PKPState());
1077 }
1078
TEST_F(TransportSecurityStateTest,HstsHostBypassList)1079 TEST_F(TransportSecurityStateTest, HstsHostBypassList) {
1080 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
1081
1082 TransportSecurityState::STSState sts_state;
1083 TransportSecurityState::PKPState pkp_state;
1084
1085 std::string preloaded_tld = "example";
1086 std::string subdomain = "sub.example";
1087
1088 {
1089 TransportSecurityState state;
1090 // Check that "example" is preloaded with subdomains.
1091 EXPECT_TRUE(state.ShouldUpgradeToSSL(preloaded_tld));
1092 EXPECT_TRUE(state.ShouldUpgradeToSSL(subdomain));
1093 }
1094
1095 {
1096 // Add "example" to the bypass list.
1097 TransportSecurityState state({preloaded_tld});
1098 EXPECT_FALSE(state.ShouldUpgradeToSSL(preloaded_tld));
1099 // The preloaded entry should still apply to the subdomain.
1100 EXPECT_TRUE(state.ShouldUpgradeToSSL(subdomain));
1101 }
1102 }
1103
1104 // Tests that TransportSecurityState always consults the RequireCTDelegate,
1105 // if supplied.
TEST_F(TransportSecurityStateTest,RequireCTConsultsDelegate)1106 TEST_F(TransportSecurityStateTest, RequireCTConsultsDelegate) {
1107 using ::testing::_;
1108 using ::testing::Return;
1109 using CTRequirementLevel =
1110 TransportSecurityState::RequireCTDelegate::CTRequirementLevel;
1111
1112 // Dummy cert to use as the validation chain. The contents do not matter.
1113 scoped_refptr<X509Certificate> cert =
1114 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
1115 ASSERT_TRUE(cert);
1116
1117 HashValueVector hashes;
1118 hashes.push_back(
1119 HashValue(X509Certificate::CalculateFingerprint256(cert->cert_buffer())));
1120
1121 // If CT is required, then the requirements are not met if the CT policy
1122 // wasn't met, but are met if the policy was met or the build was out of
1123 // date.
1124 {
1125 TransportSecurityState state;
1126 const TransportSecurityState::CTRequirementsStatus original_status =
1127 state.CheckCTRequirements(
1128 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1129 cert.get(), SignedCertificateTimestampAndStatusList(),
1130 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
1131
1132 MockRequireCTDelegate always_require_delegate;
1133 EXPECT_CALL(always_require_delegate, IsCTRequiredForHost(_, _, _))
1134 .WillRepeatedly(Return(CTRequirementLevel::REQUIRED));
1135 state.SetRequireCTDelegate(&always_require_delegate);
1136 EXPECT_EQ(
1137 TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
1138 state.CheckCTRequirements(
1139 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1140 cert.get(), SignedCertificateTimestampAndStatusList(),
1141 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
1142 EXPECT_EQ(
1143 TransportSecurityState::CT_REQUIREMENTS_NOT_MET,
1144 state.CheckCTRequirements(
1145 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1146 cert.get(), SignedCertificateTimestampAndStatusList(),
1147 ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
1148 EXPECT_EQ(
1149 TransportSecurityState::CT_REQUIREMENTS_MET,
1150 state.CheckCTRequirements(
1151 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1152 cert.get(), SignedCertificateTimestampAndStatusList(),
1153 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
1154 EXPECT_EQ(
1155 TransportSecurityState::CT_REQUIREMENTS_MET,
1156 state.CheckCTRequirements(
1157 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1158 cert.get(), SignedCertificateTimestampAndStatusList(),
1159 ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
1160
1161 state.SetRequireCTDelegate(nullptr);
1162 EXPECT_EQ(
1163 original_status,
1164 state.CheckCTRequirements(
1165 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1166 cert.get(), SignedCertificateTimestampAndStatusList(),
1167 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
1168 }
1169
1170 // If CT is not required, then regardless of the CT state for the host,
1171 // it should indicate CT is not required.
1172 {
1173 TransportSecurityState state;
1174 const TransportSecurityState::CTRequirementsStatus original_status =
1175 state.CheckCTRequirements(
1176 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1177 cert.get(), SignedCertificateTimestampAndStatusList(),
1178 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
1179
1180 MockRequireCTDelegate never_require_delegate;
1181 EXPECT_CALL(never_require_delegate, IsCTRequiredForHost(_, _, _))
1182 .WillRepeatedly(Return(CTRequirementLevel::NOT_REQUIRED));
1183 state.SetRequireCTDelegate(&never_require_delegate);
1184 EXPECT_EQ(
1185 TransportSecurityState::CT_NOT_REQUIRED,
1186 state.CheckCTRequirements(
1187 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1188 cert.get(), SignedCertificateTimestampAndStatusList(),
1189 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
1190 EXPECT_EQ(
1191 TransportSecurityState::CT_NOT_REQUIRED,
1192 state.CheckCTRequirements(
1193 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1194 cert.get(), SignedCertificateTimestampAndStatusList(),
1195 ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
1196
1197 state.SetRequireCTDelegate(nullptr);
1198 EXPECT_EQ(
1199 original_status,
1200 state.CheckCTRequirements(
1201 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1202 cert.get(), SignedCertificateTimestampAndStatusList(),
1203 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
1204 }
1205 }
1206
1207 enum class CTEmergencyDisableSwitchKind {
1208 kFinchDrivenFeature,
1209 kComponentUpdaterDrivenSwitch,
1210 };
1211
1212 class CTEmergencyDisableTest
1213 : public TransportSecurityStateTest,
1214 public testing::WithParamInterface<CTEmergencyDisableSwitchKind> {
1215 public:
CTEmergencyDisableTest()1216 CTEmergencyDisableTest() {
1217 if (GetParam() ==
1218 CTEmergencyDisableSwitchKind::kComponentUpdaterDrivenSwitch) {
1219 scoped_feature_list_.Init();
1220 } else {
1221 scoped_feature_list_.InitAndDisableFeature(
1222 kCertificateTransparencyEnforcement);
1223 }
1224 }
SetUp()1225 void SetUp() override {
1226 if (GetParam() ==
1227 CTEmergencyDisableSwitchKind::kComponentUpdaterDrivenSwitch) {
1228 state_.SetCTEmergencyDisabled(true);
1229 } else {
1230 ASSERT_EQ(GetParam(), CTEmergencyDisableSwitchKind::kFinchDrivenFeature);
1231 }
1232 }
1233
1234 protected:
1235 base::test::ScopedFeatureList scoped_feature_list_;
1236 TransportSecurityState state_;
1237 };
1238
1239 // Tests that the emergency disable flags cause CT to stop being required
1240 // regardless of host or delegate status.
TEST_P(CTEmergencyDisableTest,CTEmergencyDisable)1241 TEST_P(CTEmergencyDisableTest, CTEmergencyDisable) {
1242 using ::testing::_;
1243 using ::testing::Return;
1244 using CTRequirementLevel =
1245 TransportSecurityState::RequireCTDelegate::CTRequirementLevel;
1246
1247 // Dummy cert to use as the validation chain. The contents do not matter.
1248 scoped_refptr<X509Certificate> cert =
1249 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
1250 ASSERT_TRUE(cert);
1251
1252 HashValueVector hashes;
1253 hashes.push_back(
1254 HashValue(X509Certificate::CalculateFingerprint256(cert->cert_buffer())));
1255
1256 MockRequireCTDelegate always_require_delegate;
1257 EXPECT_CALL(always_require_delegate, IsCTRequiredForHost(_, _, _))
1258 .WillRepeatedly(Return(CTRequirementLevel::REQUIRED));
1259 state_.SetRequireCTDelegate(&always_require_delegate);
1260 EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
1261 state_.CheckCTRequirements(
1262 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1263 cert.get(), SignedCertificateTimestampAndStatusList(),
1264 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
1265 EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
1266 state_.CheckCTRequirements(
1267 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1268 cert.get(), SignedCertificateTimestampAndStatusList(),
1269 ct::CTPolicyCompliance::CT_POLICY_NOT_DIVERSE_SCTS));
1270 EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
1271 state_.CheckCTRequirements(
1272 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1273 cert.get(), SignedCertificateTimestampAndStatusList(),
1274 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS));
1275 EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
1276 state_.CheckCTRequirements(
1277 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1278 cert.get(), SignedCertificateTimestampAndStatusList(),
1279 ct::CTPolicyCompliance::CT_POLICY_BUILD_NOT_TIMELY));
1280
1281 state_.SetRequireCTDelegate(nullptr);
1282 EXPECT_EQ(TransportSecurityState::CT_NOT_REQUIRED,
1283 state_.CheckCTRequirements(
1284 HostPortPair("www.example.com", 443), true, hashes, cert.get(),
1285 cert.get(), SignedCertificateTimestampAndStatusList(),
1286 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS));
1287 }
1288
1289 INSTANTIATE_TEST_SUITE_P(
1290 CTEmergencyDisable,
1291 CTEmergencyDisableTest,
1292 testing::Values(CTEmergencyDisableSwitchKind::kComponentUpdaterDrivenSwitch,
1293 CTEmergencyDisableSwitchKind::kFinchDrivenFeature));
1294
1295 #if BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
1296 const char kSubdomain[] = "foo.example.test";
1297
1298 class TransportSecurityStateStaticTest : public TransportSecurityStateTest {
1299 public:
TransportSecurityStateStaticTest()1300 TransportSecurityStateStaticTest() {
1301 SetTransportSecurityStateSourceForTesting(nullptr);
1302 }
1303 };
1304
StaticShouldRedirect(const char * hostname)1305 static bool StaticShouldRedirect(const char* hostname) {
1306 TransportSecurityState state;
1307 TransportSecurityState::STSState sts_state;
1308 return state.GetStaticSTSState(hostname, &sts_state) &&
1309 sts_state.ShouldUpgradeToSSL();
1310 }
1311
HasStaticState(const char * hostname)1312 static bool HasStaticState(const char* hostname) {
1313 TransportSecurityState state;
1314 state.SetPinningListAlwaysTimelyForTesting(true);
1315 TransportSecurityState::STSState sts_state;
1316 TransportSecurityState::PKPState pkp_state;
1317 return state.GetStaticSTSState(hostname, &sts_state) ||
1318 state.GetStaticPKPState(hostname, &pkp_state);
1319 }
1320
HasStaticPublicKeyPins(const char * hostname)1321 static bool HasStaticPublicKeyPins(const char* hostname) {
1322 TransportSecurityState state;
1323 state.SetPinningListAlwaysTimelyForTesting(true);
1324 TransportSecurityStateTest::EnableStaticPins(&state);
1325 TransportSecurityState::PKPState pkp_state;
1326 if (!state.GetStaticPKPState(hostname, &pkp_state))
1327 return false;
1328
1329 return pkp_state.HasPublicKeyPins();
1330 }
1331
OnlyPinningInStaticState(const char * hostname)1332 static bool OnlyPinningInStaticState(const char* hostname) {
1333 TransportSecurityState state;
1334 TransportSecurityStateTest::EnableStaticPins(&state);
1335 TransportSecurityState::STSState sts_state;
1336 TransportSecurityState::PKPState pkp_state;
1337 return HasStaticPublicKeyPins(hostname) && !StaticShouldRedirect(hostname);
1338 }
1339
TEST_F(TransportSecurityStateStaticTest,EnableStaticPins)1340 TEST_F(TransportSecurityStateStaticTest, EnableStaticPins) {
1341 base::test::ScopedFeatureList scoped_feature_list_;
1342 scoped_feature_list_.InitAndEnableFeature(
1343 net::features::kStaticKeyPinningEnforcement);
1344 TransportSecurityState state;
1345 state.SetPinningListAlwaysTimelyForTesting(true);
1346 TransportSecurityState::PKPState pkp_state;
1347
1348 EnableStaticPins(&state);
1349
1350 EXPECT_TRUE(state.GetStaticPKPState("chrome.google.com", &pkp_state));
1351 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1352 }
1353
TEST_F(TransportSecurityStateStaticTest,DisableStaticPins)1354 TEST_F(TransportSecurityStateStaticTest, DisableStaticPins) {
1355 TransportSecurityState state;
1356 state.SetPinningListAlwaysTimelyForTesting(true);
1357 TransportSecurityState::PKPState pkp_state;
1358
1359 DisableStaticPins(&state);
1360 EXPECT_FALSE(state.GetStaticPKPState("chrome.google.com", &pkp_state));
1361 EXPECT_TRUE(pkp_state.spki_hashes.empty());
1362 }
1363
TEST_F(TransportSecurityStateStaticTest,IsPreloaded)1364 TEST_F(TransportSecurityStateStaticTest, IsPreloaded) {
1365 const std::string paypal = "paypal.com";
1366 const std::string www_paypal = "www.paypal.com";
1367 const std::string foo_paypal = "foo.paypal.com";
1368 const std::string a_www_paypal = "a.www.paypal.com";
1369 const std::string abc_paypal = "a.b.c.paypal.com";
1370 const std::string example = "example.com";
1371 const std::string aypal = "aypal.com";
1372 const std::string google = "google";
1373 const std::string www_google = "www.google";
1374 const std::string foo = "foo";
1375 const std::string bank = "example.bank";
1376 const std::string insurance = "sub.example.insurance";
1377
1378 TransportSecurityState state;
1379 TransportSecurityState::STSState sts_state;
1380 TransportSecurityState::PKPState pkp_state;
1381
1382 EXPECT_TRUE(GetStaticDomainState(&state, paypal, &sts_state, &pkp_state));
1383 EXPECT_TRUE(GetStaticDomainState(&state, www_paypal, &sts_state, &pkp_state));
1384 EXPECT_FALSE(sts_state.include_subdomains);
1385 EXPECT_TRUE(GetStaticDomainState(&state, google, &sts_state, &pkp_state));
1386 EXPECT_TRUE(GetStaticDomainState(&state, www_google, &sts_state, &pkp_state));
1387 EXPECT_TRUE(GetStaticDomainState(&state, foo, &sts_state, &pkp_state));
1388 EXPECT_TRUE(GetStaticDomainState(&state, bank, &sts_state, &pkp_state));
1389 EXPECT_TRUE(sts_state.include_subdomains);
1390 EXPECT_TRUE(GetStaticDomainState(&state, insurance, &sts_state, &pkp_state));
1391 EXPECT_TRUE(sts_state.include_subdomains);
1392 EXPECT_FALSE(
1393 GetStaticDomainState(&state, a_www_paypal, &sts_state, &pkp_state));
1394 EXPECT_FALSE(
1395 GetStaticDomainState(&state, abc_paypal, &sts_state, &pkp_state));
1396 EXPECT_FALSE(GetStaticDomainState(&state, example, &sts_state, &pkp_state));
1397 EXPECT_FALSE(GetStaticDomainState(&state, aypal, &sts_state, &pkp_state));
1398 }
1399
TEST_F(TransportSecurityStateStaticTest,PreloadedDomainSet)1400 TEST_F(TransportSecurityStateStaticTest, PreloadedDomainSet) {
1401 base::test::ScopedFeatureList scoped_feature_list_;
1402 scoped_feature_list_.InitAndEnableFeature(
1403 net::features::kStaticKeyPinningEnforcement);
1404 TransportSecurityState state;
1405 EnableStaticPins(&state);
1406 TransportSecurityState::STSState sts_state;
1407 TransportSecurityState::PKPState pkp_state;
1408
1409 // The domain wasn't being set, leading to a blank string in the
1410 // chrome://net-internals/#hsts UI. So test that.
1411 EXPECT_TRUE(state.GetStaticPKPState("market.android.com", &pkp_state));
1412 EXPECT_TRUE(state.GetStaticSTSState("market.android.com", &sts_state));
1413 EXPECT_EQ(sts_state.domain, "market.android.com");
1414 EXPECT_EQ(pkp_state.domain, "market.android.com");
1415 EXPECT_TRUE(state.GetStaticPKPState("sub.market.android.com", &pkp_state));
1416 EXPECT_TRUE(state.GetStaticSTSState("sub.market.android.com", &sts_state));
1417 EXPECT_EQ(sts_state.domain, "market.android.com");
1418 EXPECT_EQ(pkp_state.domain, "market.android.com");
1419 }
1420
TEST_F(TransportSecurityStateStaticTest,Preloaded)1421 TEST_F(TransportSecurityStateStaticTest, Preloaded) {
1422 base::test::ScopedFeatureList scoped_feature_list_;
1423 scoped_feature_list_.InitAndEnableFeature(
1424 net::features::kStaticKeyPinningEnforcement);
1425 TransportSecurityState state;
1426 EnableStaticPins(&state);
1427 TransportSecurityState::STSState sts_state;
1428 TransportSecurityState::PKPState pkp_state;
1429
1430 // We do more extensive checks for the first domain.
1431 EXPECT_TRUE(state.GetStaticSTSState("www.paypal.com", &sts_state));
1432 EXPECT_FALSE(state.GetStaticPKPState("www.paypal.com", &pkp_state));
1433 EXPECT_EQ(sts_state.upgrade_mode,
1434 TransportSecurityState::STSState::MODE_FORCE_HTTPS);
1435 EXPECT_FALSE(sts_state.include_subdomains);
1436 EXPECT_FALSE(pkp_state.include_subdomains);
1437
1438 EXPECT_TRUE(HasStaticState("paypal.com"));
1439 EXPECT_FALSE(HasStaticState("www2.paypal.com"));
1440
1441 // Google hosts:
1442
1443 EXPECT_TRUE(StaticShouldRedirect("chrome.google.com"));
1444 EXPECT_TRUE(StaticShouldRedirect("checkout.google.com"));
1445 EXPECT_TRUE(StaticShouldRedirect("wallet.google.com"));
1446 EXPECT_TRUE(StaticShouldRedirect("docs.google.com"));
1447 EXPECT_TRUE(StaticShouldRedirect("sites.google.com"));
1448 EXPECT_TRUE(StaticShouldRedirect("drive.google.com"));
1449 EXPECT_TRUE(StaticShouldRedirect("spreadsheets.google.com"));
1450 EXPECT_TRUE(StaticShouldRedirect("appengine.google.com"));
1451 EXPECT_TRUE(StaticShouldRedirect("market.android.com"));
1452 EXPECT_TRUE(StaticShouldRedirect("encrypted.google.com"));
1453 EXPECT_TRUE(StaticShouldRedirect("accounts.google.com"));
1454 EXPECT_TRUE(StaticShouldRedirect("profiles.google.com"));
1455 EXPECT_TRUE(StaticShouldRedirect("mail.google.com"));
1456 EXPECT_TRUE(StaticShouldRedirect("chatenabled.mail.google.com"));
1457 EXPECT_TRUE(StaticShouldRedirect("talkgadget.google.com"));
1458 EXPECT_TRUE(StaticShouldRedirect("hostedtalkgadget.google.com"));
1459 EXPECT_TRUE(StaticShouldRedirect("talk.google.com"));
1460 EXPECT_TRUE(StaticShouldRedirect("plus.google.com"));
1461 EXPECT_TRUE(StaticShouldRedirect("groups.google.com"));
1462 EXPECT_TRUE(StaticShouldRedirect("apis.google.com"));
1463 EXPECT_TRUE(StaticShouldRedirect("oauthaccountmanager.googleapis.com"));
1464 EXPECT_TRUE(StaticShouldRedirect("passwordsleakcheck-pa.googleapis.com"));
1465 EXPECT_TRUE(StaticShouldRedirect("ssl.google-analytics.com"));
1466 EXPECT_TRUE(StaticShouldRedirect("google"));
1467 EXPECT_TRUE(StaticShouldRedirect("foo.google"));
1468 EXPECT_TRUE(StaticShouldRedirect("foo"));
1469 EXPECT_TRUE(StaticShouldRedirect("domaintest.foo"));
1470 EXPECT_TRUE(StaticShouldRedirect("gmail.com"));
1471 EXPECT_TRUE(StaticShouldRedirect("www.gmail.com"));
1472 EXPECT_TRUE(StaticShouldRedirect("googlemail.com"));
1473 EXPECT_TRUE(StaticShouldRedirect("www.googlemail.com"));
1474 EXPECT_TRUE(StaticShouldRedirect("googleplex.com"));
1475 EXPECT_TRUE(StaticShouldRedirect("www.googleplex.com"));
1476 EXPECT_TRUE(StaticShouldRedirect("www.google-analytics.com"));
1477 EXPECT_TRUE(StaticShouldRedirect("www.youtube.com"));
1478 EXPECT_TRUE(StaticShouldRedirect("youtube.com"));
1479
1480 // These domains used to be only HSTS when SNI was available.
1481 EXPECT_TRUE(state.GetStaticSTSState("gmail.com", &sts_state));
1482 EXPECT_TRUE(state.GetStaticPKPState("gmail.com", &pkp_state));
1483 EXPECT_TRUE(state.GetStaticSTSState("www.gmail.com", &sts_state));
1484 EXPECT_TRUE(state.GetStaticPKPState("www.gmail.com", &pkp_state));
1485 EXPECT_TRUE(state.GetStaticSTSState("googlemail.com", &sts_state));
1486 EXPECT_TRUE(state.GetStaticPKPState("googlemail.com", &pkp_state));
1487 EXPECT_TRUE(state.GetStaticSTSState("www.googlemail.com", &sts_state));
1488 EXPECT_TRUE(state.GetStaticPKPState("www.googlemail.com", &pkp_state));
1489
1490 // fi.g.co should not force HTTPS because there are still HTTP-only services
1491 // on it.
1492 EXPECT_FALSE(StaticShouldRedirect("fi.g.co"));
1493
1494 // Other hosts:
1495
1496 EXPECT_TRUE(StaticShouldRedirect("aladdinschools.appspot.com"));
1497
1498 EXPECT_TRUE(StaticShouldRedirect("ottospora.nl"));
1499 EXPECT_TRUE(StaticShouldRedirect("www.ottospora.nl"));
1500
1501 EXPECT_TRUE(StaticShouldRedirect("www.paycheckrecords.com"));
1502
1503 EXPECT_TRUE(StaticShouldRedirect("lastpass.com"));
1504 EXPECT_TRUE(StaticShouldRedirect("www.lastpass.com"));
1505 EXPECT_FALSE(HasStaticState("blog.lastpass.com"));
1506
1507 EXPECT_TRUE(StaticShouldRedirect("keyerror.com"));
1508 EXPECT_TRUE(StaticShouldRedirect("www.keyerror.com"));
1509
1510 EXPECT_TRUE(StaticShouldRedirect("entropia.de"));
1511 EXPECT_TRUE(StaticShouldRedirect("www.entropia.de"));
1512 EXPECT_FALSE(HasStaticState("foo.entropia.de"));
1513
1514 EXPECT_TRUE(StaticShouldRedirect("www.elanex.biz"));
1515 EXPECT_FALSE(HasStaticState("elanex.biz"));
1516 EXPECT_FALSE(HasStaticState("foo.elanex.biz"));
1517
1518 EXPECT_TRUE(StaticShouldRedirect("sunshinepress.org"));
1519 EXPECT_TRUE(StaticShouldRedirect("www.sunshinepress.org"));
1520 EXPECT_TRUE(StaticShouldRedirect("a.b.sunshinepress.org"));
1521
1522 EXPECT_TRUE(StaticShouldRedirect("www.noisebridge.net"));
1523 EXPECT_FALSE(HasStaticState("noisebridge.net"));
1524 EXPECT_FALSE(HasStaticState("foo.noisebridge.net"));
1525
1526 EXPECT_TRUE(StaticShouldRedirect("neg9.org"));
1527 EXPECT_FALSE(HasStaticState("www.neg9.org"));
1528
1529 EXPECT_TRUE(StaticShouldRedirect("riseup.net"));
1530 EXPECT_TRUE(StaticShouldRedirect("foo.riseup.net"));
1531
1532 EXPECT_TRUE(StaticShouldRedirect("factor.cc"));
1533 EXPECT_FALSE(HasStaticState("www.factor.cc"));
1534
1535 EXPECT_TRUE(StaticShouldRedirect("members.mayfirst.org"));
1536 EXPECT_TRUE(StaticShouldRedirect("support.mayfirst.org"));
1537 EXPECT_TRUE(StaticShouldRedirect("id.mayfirst.org"));
1538 EXPECT_TRUE(StaticShouldRedirect("lists.mayfirst.org"));
1539 EXPECT_FALSE(HasStaticState("www.mayfirst.org"));
1540
1541 EXPECT_TRUE(StaticShouldRedirect("romab.com"));
1542 EXPECT_TRUE(StaticShouldRedirect("www.romab.com"));
1543 EXPECT_TRUE(StaticShouldRedirect("foo.romab.com"));
1544
1545 EXPECT_TRUE(StaticShouldRedirect("logentries.com"));
1546 EXPECT_TRUE(StaticShouldRedirect("www.logentries.com"));
1547 EXPECT_FALSE(HasStaticState("foo.logentries.com"));
1548
1549 EXPECT_TRUE(StaticShouldRedirect("stripe.com"));
1550 EXPECT_TRUE(StaticShouldRedirect("foo.stripe.com"));
1551
1552 EXPECT_TRUE(StaticShouldRedirect("cloudsecurityalliance.org"));
1553 EXPECT_TRUE(StaticShouldRedirect("foo.cloudsecurityalliance.org"));
1554
1555 EXPECT_TRUE(StaticShouldRedirect("login.sapo.pt"));
1556 EXPECT_TRUE(StaticShouldRedirect("foo.login.sapo.pt"));
1557
1558 EXPECT_TRUE(StaticShouldRedirect("mattmccutchen.net"));
1559 EXPECT_TRUE(StaticShouldRedirect("foo.mattmccutchen.net"));
1560
1561 EXPECT_TRUE(StaticShouldRedirect("betnet.fr"));
1562 EXPECT_TRUE(StaticShouldRedirect("foo.betnet.fr"));
1563
1564 EXPECT_TRUE(StaticShouldRedirect("uprotect.it"));
1565 EXPECT_TRUE(StaticShouldRedirect("foo.uprotect.it"));
1566
1567 EXPECT_TRUE(StaticShouldRedirect("cert.se"));
1568 EXPECT_TRUE(StaticShouldRedirect("foo.cert.se"));
1569
1570 EXPECT_TRUE(StaticShouldRedirect("crypto.is"));
1571 EXPECT_TRUE(StaticShouldRedirect("foo.crypto.is"));
1572
1573 EXPECT_TRUE(StaticShouldRedirect("simon.butcher.name"));
1574 EXPECT_TRUE(StaticShouldRedirect("foo.simon.butcher.name"));
1575
1576 EXPECT_TRUE(StaticShouldRedirect("linx.net"));
1577 EXPECT_TRUE(StaticShouldRedirect("foo.linx.net"));
1578
1579 EXPECT_TRUE(StaticShouldRedirect("dropcam.com"));
1580 EXPECT_TRUE(StaticShouldRedirect("www.dropcam.com"));
1581 EXPECT_FALSE(HasStaticState("foo.dropcam.com"));
1582
1583 EXPECT_TRUE(StaticShouldRedirect("ebanking.indovinabank.com.vn"));
1584 EXPECT_TRUE(StaticShouldRedirect("foo.ebanking.indovinabank.com.vn"));
1585
1586 EXPECT_TRUE(StaticShouldRedirect("epoxate.com"));
1587 EXPECT_FALSE(HasStaticState("foo.epoxate.com"));
1588
1589 EXPECT_FALSE(HasStaticState("foo.torproject.org"));
1590
1591 EXPECT_TRUE(StaticShouldRedirect("www.moneybookers.com"));
1592 EXPECT_FALSE(HasStaticState("moneybookers.com"));
1593
1594 EXPECT_TRUE(StaticShouldRedirect("ledgerscope.net"));
1595 EXPECT_TRUE(StaticShouldRedirect("www.ledgerscope.net"));
1596 EXPECT_FALSE(HasStaticState("status.ledgerscope.net"));
1597
1598 EXPECT_TRUE(StaticShouldRedirect("foo.app.recurly.com"));
1599 EXPECT_TRUE(StaticShouldRedirect("foo.api.recurly.com"));
1600
1601 EXPECT_TRUE(StaticShouldRedirect("greplin.com"));
1602 EXPECT_TRUE(StaticShouldRedirect("www.greplin.com"));
1603 EXPECT_FALSE(HasStaticState("foo.greplin.com"));
1604
1605 EXPECT_TRUE(StaticShouldRedirect("luneta.nearbuysystems.com"));
1606 EXPECT_TRUE(StaticShouldRedirect("foo.luneta.nearbuysystems.com"));
1607
1608 EXPECT_TRUE(StaticShouldRedirect("ubertt.org"));
1609 EXPECT_TRUE(StaticShouldRedirect("foo.ubertt.org"));
1610
1611 EXPECT_TRUE(StaticShouldRedirect("pixi.me"));
1612 EXPECT_TRUE(StaticShouldRedirect("www.pixi.me"));
1613
1614 EXPECT_TRUE(StaticShouldRedirect("grepular.com"));
1615 EXPECT_TRUE(StaticShouldRedirect("www.grepular.com"));
1616
1617 EXPECT_TRUE(StaticShouldRedirect("mydigipass.com"));
1618 EXPECT_FALSE(StaticShouldRedirect("foo.mydigipass.com"));
1619 EXPECT_TRUE(StaticShouldRedirect("www.mydigipass.com"));
1620 EXPECT_FALSE(StaticShouldRedirect("foo.www.mydigipass.com"));
1621 EXPECT_TRUE(StaticShouldRedirect("developer.mydigipass.com"));
1622 EXPECT_FALSE(StaticShouldRedirect("foo.developer.mydigipass.com"));
1623 EXPECT_TRUE(StaticShouldRedirect("www.developer.mydigipass.com"));
1624 EXPECT_FALSE(StaticShouldRedirect("foo.www.developer.mydigipass.com"));
1625 EXPECT_TRUE(StaticShouldRedirect("sandbox.mydigipass.com"));
1626 EXPECT_FALSE(StaticShouldRedirect("foo.sandbox.mydigipass.com"));
1627 EXPECT_TRUE(StaticShouldRedirect("www.sandbox.mydigipass.com"));
1628 EXPECT_FALSE(StaticShouldRedirect("foo.www.sandbox.mydigipass.com"));
1629
1630 EXPECT_TRUE(StaticShouldRedirect("bigshinylock.minazo.net"));
1631 EXPECT_TRUE(StaticShouldRedirect("foo.bigshinylock.minazo.net"));
1632
1633 EXPECT_TRUE(StaticShouldRedirect("crate.io"));
1634 EXPECT_TRUE(StaticShouldRedirect("foo.crate.io"));
1635
1636 EXPECT_TRUE(StaticShouldRedirect("sub.bank"));
1637 EXPECT_TRUE(StaticShouldRedirect("sub.insurance"));
1638 }
1639
TEST_F(TransportSecurityStateStaticTest,PreloadedPins)1640 TEST_F(TransportSecurityStateStaticTest, PreloadedPins) {
1641 base::test::ScopedFeatureList scoped_feature_list_;
1642 scoped_feature_list_.InitAndEnableFeature(
1643 net::features::kStaticKeyPinningEnforcement);
1644 TransportSecurityState state;
1645 EnableStaticPins(&state);
1646 TransportSecurityState::STSState sts_state;
1647 TransportSecurityState::PKPState pkp_state;
1648
1649 // We do more extensive checks for the first domain.
1650 EXPECT_TRUE(state.GetStaticSTSState("www.paypal.com", &sts_state));
1651 EXPECT_FALSE(state.GetStaticPKPState("www.paypal.com", &pkp_state));
1652 EXPECT_EQ(sts_state.upgrade_mode,
1653 TransportSecurityState::STSState::MODE_FORCE_HTTPS);
1654 EXPECT_FALSE(sts_state.include_subdomains);
1655 EXPECT_FALSE(pkp_state.include_subdomains);
1656
1657 EXPECT_TRUE(OnlyPinningInStaticState("www.google.com"));
1658 EXPECT_TRUE(OnlyPinningInStaticState("foo.google.com"));
1659 EXPECT_TRUE(OnlyPinningInStaticState("google.com"));
1660 EXPECT_TRUE(OnlyPinningInStaticState("i.ytimg.com"));
1661 EXPECT_TRUE(OnlyPinningInStaticState("ytimg.com"));
1662 EXPECT_TRUE(OnlyPinningInStaticState("googleusercontent.com"));
1663 EXPECT_TRUE(OnlyPinningInStaticState("www.googleusercontent.com"));
1664 EXPECT_TRUE(OnlyPinningInStaticState("googleapis.com"));
1665 EXPECT_TRUE(OnlyPinningInStaticState("googleadservices.com"));
1666 EXPECT_TRUE(OnlyPinningInStaticState("googlecode.com"));
1667 EXPECT_TRUE(OnlyPinningInStaticState("appspot.com"));
1668 EXPECT_TRUE(OnlyPinningInStaticState("googlesyndication.com"));
1669 EXPECT_TRUE(OnlyPinningInStaticState("doubleclick.net"));
1670 EXPECT_TRUE(OnlyPinningInStaticState("googlegroups.com"));
1671
1672 EXPECT_TRUE(HasStaticPublicKeyPins("torproject.org"));
1673 EXPECT_TRUE(HasStaticPublicKeyPins("www.torproject.org"));
1674 EXPECT_TRUE(HasStaticPublicKeyPins("check.torproject.org"));
1675 EXPECT_TRUE(HasStaticPublicKeyPins("blog.torproject.org"));
1676 EXPECT_FALSE(HasStaticState("foo.torproject.org"));
1677
1678 EXPECT_TRUE(state.GetStaticPKPState("torproject.org", &pkp_state));
1679 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1680 EXPECT_TRUE(state.GetStaticPKPState("www.torproject.org", &pkp_state));
1681 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1682 EXPECT_TRUE(state.GetStaticPKPState("check.torproject.org", &pkp_state));
1683 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1684 EXPECT_TRUE(state.GetStaticPKPState("blog.torproject.org", &pkp_state));
1685 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1686
1687 // Facebook has pinning and hsts on facebook.com, but only pinning on
1688 // subdomains.
1689 EXPECT_TRUE(state.GetStaticPKPState("facebook.com", &pkp_state));
1690 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1691 EXPECT_TRUE(StaticShouldRedirect("facebook.com"));
1692
1693 EXPECT_TRUE(state.GetStaticPKPState("foo.facebook.com", &pkp_state));
1694 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1695 EXPECT_FALSE(StaticShouldRedirect("foo.facebook.com"));
1696
1697 // www.facebook.com and subdomains have both pinning and hsts.
1698 EXPECT_TRUE(state.GetStaticPKPState("www.facebook.com", &pkp_state));
1699 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1700 EXPECT_TRUE(StaticShouldRedirect("www.facebook.com"));
1701
1702 EXPECT_TRUE(state.GetStaticPKPState("foo.www.facebook.com", &pkp_state));
1703 EXPECT_FALSE(pkp_state.spki_hashes.empty());
1704 EXPECT_TRUE(StaticShouldRedirect("foo.www.facebook.com"));
1705 }
1706
TEST_F(TransportSecurityStateStaticTest,BuiltinCertPins)1707 TEST_F(TransportSecurityStateStaticTest, BuiltinCertPins) {
1708 base::test::ScopedFeatureList scoped_feature_list_;
1709 scoped_feature_list_.InitAndEnableFeature(
1710 net::features::kStaticKeyPinningEnforcement);
1711 TransportSecurityState state;
1712 EnableStaticPins(&state);
1713 TransportSecurityState::PKPState pkp_state;
1714
1715 EXPECT_TRUE(state.GetStaticPKPState("chrome.google.com", &pkp_state));
1716 EXPECT_TRUE(HasStaticPublicKeyPins("chrome.google.com"));
1717
1718 HashValueVector hashes;
1719 std::string failure_log;
1720 // Checks that a built-in list does exist.
1721 EXPECT_FALSE(pkp_state.CheckPublicKeyPins(hashes, &failure_log));
1722 EXPECT_FALSE(HasStaticPublicKeyPins("www.paypal.com"));
1723
1724 EXPECT_TRUE(HasStaticPublicKeyPins("docs.google.com"));
1725 EXPECT_TRUE(HasStaticPublicKeyPins("1.docs.google.com"));
1726 EXPECT_TRUE(HasStaticPublicKeyPins("sites.google.com"));
1727 EXPECT_TRUE(HasStaticPublicKeyPins("drive.google.com"));
1728 EXPECT_TRUE(HasStaticPublicKeyPins("spreadsheets.google.com"));
1729 EXPECT_TRUE(HasStaticPublicKeyPins("wallet.google.com"));
1730 EXPECT_TRUE(HasStaticPublicKeyPins("checkout.google.com"));
1731 EXPECT_TRUE(HasStaticPublicKeyPins("appengine.google.com"));
1732 EXPECT_TRUE(HasStaticPublicKeyPins("market.android.com"));
1733 EXPECT_TRUE(HasStaticPublicKeyPins("encrypted.google.com"));
1734 EXPECT_TRUE(HasStaticPublicKeyPins("accounts.google.com"));
1735 EXPECT_TRUE(HasStaticPublicKeyPins("profiles.google.com"));
1736 EXPECT_TRUE(HasStaticPublicKeyPins("mail.google.com"));
1737 EXPECT_TRUE(HasStaticPublicKeyPins("chatenabled.mail.google.com"));
1738 EXPECT_TRUE(HasStaticPublicKeyPins("talkgadget.google.com"));
1739 EXPECT_TRUE(HasStaticPublicKeyPins("hostedtalkgadget.google.com"));
1740 EXPECT_TRUE(HasStaticPublicKeyPins("talk.google.com"));
1741 EXPECT_TRUE(HasStaticPublicKeyPins("plus.google.com"));
1742 EXPECT_TRUE(HasStaticPublicKeyPins("groups.google.com"));
1743 EXPECT_TRUE(HasStaticPublicKeyPins("apis.google.com"));
1744 EXPECT_TRUE(HasStaticPublicKeyPins("www.google-analytics.com"));
1745 EXPECT_TRUE(HasStaticPublicKeyPins("www.youtube.com"));
1746 EXPECT_TRUE(HasStaticPublicKeyPins("youtube.com"));
1747
1748 EXPECT_TRUE(HasStaticPublicKeyPins("ssl.gstatic.com"));
1749 EXPECT_TRUE(HasStaticPublicKeyPins("gstatic.com"));
1750 EXPECT_TRUE(HasStaticPublicKeyPins("www.gstatic.com"));
1751 EXPECT_TRUE(HasStaticPublicKeyPins("ssl.google-analytics.com"));
1752 EXPECT_TRUE(HasStaticPublicKeyPins("www.googleplex.com"));
1753 }
1754
TEST_F(TransportSecurityStateStaticTest,OptionalHSTSCertPins)1755 TEST_F(TransportSecurityStateStaticTest, OptionalHSTSCertPins) {
1756 base::test::ScopedFeatureList scoped_feature_list_;
1757 scoped_feature_list_.InitAndEnableFeature(
1758 net::features::kStaticKeyPinningEnforcement);
1759 TransportSecurityState state;
1760 EnableStaticPins(&state);
1761
1762 EXPECT_TRUE(HasStaticPublicKeyPins("google.com"));
1763 EXPECT_TRUE(HasStaticPublicKeyPins("www.google.com"));
1764 EXPECT_TRUE(HasStaticPublicKeyPins("mail-attachment.googleusercontent.com"));
1765 EXPECT_TRUE(HasStaticPublicKeyPins("www.youtube.com"));
1766 EXPECT_TRUE(HasStaticPublicKeyPins("i.ytimg.com"));
1767 EXPECT_TRUE(HasStaticPublicKeyPins("googleapis.com"));
1768 EXPECT_TRUE(HasStaticPublicKeyPins("ajax.googleapis.com"));
1769 EXPECT_TRUE(HasStaticPublicKeyPins("googleadservices.com"));
1770 EXPECT_TRUE(HasStaticPublicKeyPins("pagead2.googleadservices.com"));
1771 EXPECT_TRUE(HasStaticPublicKeyPins("googlecode.com"));
1772 EXPECT_TRUE(HasStaticPublicKeyPins("kibbles.googlecode.com"));
1773 EXPECT_TRUE(HasStaticPublicKeyPins("appspot.com"));
1774 EXPECT_TRUE(HasStaticPublicKeyPins("googlesyndication.com"));
1775 EXPECT_TRUE(HasStaticPublicKeyPins("doubleclick.net"));
1776 EXPECT_TRUE(HasStaticPublicKeyPins("ad.doubleclick.net"));
1777 EXPECT_TRUE(HasStaticPublicKeyPins("redirector.gvt1.com"));
1778 EXPECT_TRUE(HasStaticPublicKeyPins("a.googlegroups.com"));
1779 }
1780
TEST_F(TransportSecurityStateStaticTest,OverrideBuiltins)1781 TEST_F(TransportSecurityStateStaticTest, OverrideBuiltins) {
1782 base::test::ScopedFeatureList scoped_feature_list_;
1783 scoped_feature_list_.InitAndEnableFeature(
1784 net::features::kStaticKeyPinningEnforcement);
1785 EXPECT_TRUE(HasStaticPublicKeyPins("google.com"));
1786 EXPECT_FALSE(StaticShouldRedirect("google.com"));
1787 EXPECT_FALSE(StaticShouldRedirect("www.google.com"));
1788
1789 TransportSecurityState state;
1790 state.SetPinningListAlwaysTimelyForTesting(true);
1791
1792 const base::Time current_time(base::Time::Now());
1793 const base::Time expiry = current_time + base::Seconds(1000);
1794 state.AddHSTS("www.google.com", expiry, true);
1795
1796 EXPECT_TRUE(state.ShouldUpgradeToSSL("www.google.com"));
1797 }
1798
1799 // Tests that redundant reports are rate-limited.
TEST_F(TransportSecurityStateStaticTest,HPKPReportRateLimiting)1800 TEST_F(TransportSecurityStateStaticTest, HPKPReportRateLimiting) {
1801 base::test::ScopedFeatureList scoped_feature_list_;
1802 scoped_feature_list_.InitAndEnableFeature(
1803 net::features::kStaticKeyPinningEnforcement);
1804 HostPortPair host_port_pair(kHost, kPort);
1805 HostPortPair subdomain_host_port_pair(kSubdomain, kPort);
1806 GURL report_uri(kReportUri);
1807 NetworkAnonymizationKey network_anonymization_key =
1808 NetworkAnonymizationKey::CreateTransient();
1809 // Two dummy certs to use as the server-sent and validated chains. The
1810 // contents don't matter.
1811 scoped_refptr<X509Certificate> cert1 =
1812 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
1813 ASSERT_TRUE(cert1);
1814 scoped_refptr<X509Certificate> cert2 =
1815 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
1816 ASSERT_TRUE(cert2);
1817
1818 HashValueVector good_hashes, bad_hashes;
1819
1820 for (size_t i = 0; kGoodPath[i]; i++)
1821 EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
1822 for (size_t i = 0; kBadPath[i]; i++)
1823 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
1824
1825 TransportSecurityState state;
1826 EnableStaticPins(&state);
1827 MockCertificateReportSender mock_report_sender;
1828 state.SetReportSender(&mock_report_sender);
1829
1830 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
1831 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
1832
1833 std::string failure_log;
1834 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
1835 state.CheckPublicKeyPins(host_port_pair, true, bad_hashes,
1836 cert1.get(), cert2.get(),
1837 TransportSecurityState::ENABLE_PIN_REPORTS,
1838 network_anonymization_key, &failure_log));
1839
1840 // A report should have been sent. Check that it contains the
1841 // right information.
1842 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
1843 std::string report = mock_report_sender.latest_report();
1844 ASSERT_FALSE(report.empty());
1845 ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, host_port_pair, true, kHost,
1846 cert1.get(), cert2.get(),
1847 good_hashes));
1848 EXPECT_EQ(network_anonymization_key,
1849 mock_report_sender.latest_network_anonymization_key());
1850 mock_report_sender.Clear();
1851
1852 // Now trigger the same violation; a duplicative report should not be
1853 // sent.
1854 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
1855 state.CheckPublicKeyPins(host_port_pair, true, bad_hashes,
1856 cert1.get(), cert2.get(),
1857 TransportSecurityState::ENABLE_PIN_REPORTS,
1858 network_anonymization_key, &failure_log));
1859 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
1860 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
1861 EXPECT_EQ(NetworkAnonymizationKey(),
1862 mock_report_sender.latest_network_anonymization_key());
1863
1864 state.SetReportSender(nullptr);
1865 }
1866
TEST_F(TransportSecurityStateStaticTest,HPKPReporting)1867 TEST_F(TransportSecurityStateStaticTest, HPKPReporting) {
1868 base::test::ScopedFeatureList scoped_feature_list_;
1869 scoped_feature_list_.InitAndEnableFeature(
1870 net::features::kStaticKeyPinningEnforcement);
1871 HostPortPair host_port_pair(kHost, kPort);
1872 HostPortPair subdomain_host_port_pair(kSubdomain, kPort);
1873 GURL report_uri(kReportUri);
1874 NetworkAnonymizationKey network_anonymization_key =
1875 NetworkAnonymizationKey::CreateTransient();
1876 // Two dummy certs to use as the server-sent and validated chains. The
1877 // contents don't matter.
1878 scoped_refptr<X509Certificate> cert1 =
1879 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
1880 ASSERT_TRUE(cert1);
1881 scoped_refptr<X509Certificate> cert2 =
1882 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
1883 ASSERT_TRUE(cert2);
1884
1885 HashValueVector good_hashes, bad_hashes;
1886
1887 for (size_t i = 0; kGoodPath[i]; i++)
1888 EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
1889 for (size_t i = 0; kBadPath[i]; i++)
1890 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
1891
1892 TransportSecurityState state;
1893 EnableStaticPins(&state);
1894 MockCertificateReportSender mock_report_sender;
1895 state.SetReportSender(&mock_report_sender);
1896
1897 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
1898 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
1899
1900 std::string failure_log;
1901 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
1902 state.CheckPublicKeyPins(
1903 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
1904 TransportSecurityState::DISABLE_PIN_REPORTS,
1905 network_anonymization_key, &failure_log));
1906
1907 // No report should have been sent because of the DISABLE_PIN_REPORTS
1908 // argument.
1909 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
1910 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
1911
1912 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
1913 state.CheckPublicKeyPins(host_port_pair, true, good_hashes,
1914 cert1.get(), cert2.get(),
1915 TransportSecurityState::ENABLE_PIN_REPORTS,
1916 network_anonymization_key, &failure_log));
1917
1918 // No report should have been sent because there was no violation.
1919 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
1920 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
1921
1922 EXPECT_EQ(TransportSecurityState::PKPStatus::BYPASSED,
1923 state.CheckPublicKeyPins(host_port_pair, false, bad_hashes,
1924 cert1.get(), cert2.get(),
1925 TransportSecurityState::ENABLE_PIN_REPORTS,
1926 network_anonymization_key, &failure_log));
1927
1928 // No report should have been sent because the certificate chained to a
1929 // non-public root.
1930 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
1931 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
1932
1933 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
1934 state.CheckPublicKeyPins(host_port_pair, false, good_hashes,
1935 cert1.get(), cert2.get(),
1936 TransportSecurityState::ENABLE_PIN_REPORTS,
1937 network_anonymization_key, &failure_log));
1938
1939 // No report should have been sent because there was no violation, even though
1940 // the certificate chained to a local trust anchor.
1941 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
1942 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
1943
1944 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
1945 state.CheckPublicKeyPins(host_port_pair, true, bad_hashes,
1946 cert1.get(), cert2.get(),
1947 TransportSecurityState::ENABLE_PIN_REPORTS,
1948 network_anonymization_key, &failure_log));
1949
1950 // Now a report should have been sent. Check that it contains the
1951 // right information.
1952 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
1953 std::string report = mock_report_sender.latest_report();
1954 ASSERT_FALSE(report.empty());
1955 EXPECT_EQ("application/json; charset=utf-8",
1956 mock_report_sender.latest_content_type());
1957 ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, host_port_pair, true, kHost,
1958 cert1.get(), cert2.get(),
1959 good_hashes));
1960 mock_report_sender.Clear();
1961 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
1962 state.CheckPublicKeyPins(subdomain_host_port_pair, true, bad_hashes,
1963 cert1.get(), cert2.get(),
1964 TransportSecurityState::ENABLE_PIN_REPORTS,
1965 network_anonymization_key, &failure_log));
1966
1967 // Now a report should have been sent for the subdomain. Check that it
1968 // contains the right information.
1969 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
1970 report = mock_report_sender.latest_report();
1971 ASSERT_FALSE(report.empty());
1972 EXPECT_EQ("application/json; charset=utf-8",
1973 mock_report_sender.latest_content_type());
1974 ASSERT_NO_FATAL_FAILURE(CheckHPKPReport(report, subdomain_host_port_pair,
1975 true, kHost, cert1.get(), cert2.get(),
1976 good_hashes));
1977 EXPECT_EQ(network_anonymization_key,
1978 mock_report_sender.latest_network_anonymization_key());
1979
1980 state.SetReportSender(nullptr);
1981 }
1982
TEST_F(TransportSecurityStateTest,WriteSizeDecodeSize)1983 TEST_F(TransportSecurityStateTest, WriteSizeDecodeSize) {
1984 for (size_t i = 0; i < 300; ++i) {
1985 SCOPED_TRACE(i);
1986 huffman_trie::TrieBitBuffer buffer;
1987 buffer.WriteSize(i);
1988 huffman_trie::BitWriter writer;
1989 buffer.WriteToBitWriter(&writer);
1990 size_t position = writer.position();
1991 writer.Flush();
1992 ASSERT_NE(writer.bytes().data(), nullptr);
1993 extras::PreloadDecoder::BitReader reader(writer.bytes().data(), position);
1994 size_t decoded_size;
1995 EXPECT_TRUE(reader.DecodeSize(&decoded_size));
1996 EXPECT_EQ(i, decoded_size);
1997 }
1998 }
1999
TEST_F(TransportSecurityStateTest,DecodeSizeFour)2000 TEST_F(TransportSecurityStateTest, DecodeSizeFour) {
2001 // Test that BitReader::DecodeSize properly handles the number 4, including
2002 // not over-reading input bytes. BitReader::Next only fails if there's not
2003 // another byte to read from; if it reads past the number of bits in the
2004 // buffer but is still in the last byte it will still succeed. For this
2005 // reason, this test puts the encoding of 4 at the end of the byte to check
2006 // that DecodeSize doesn't over-read.
2007 //
2008 // 4 is encoded as 0b010. Shifted right to fill one byte, it is 0x02, with 5
2009 // bits of padding.
2010 uint8_t encoded = 0x02;
2011 extras::PreloadDecoder::BitReader reader(&encoded, 8);
2012 for (size_t i = 0; i < 5; ++i) {
2013 bool unused;
2014 ASSERT_TRUE(reader.Next(&unused));
2015 }
2016 size_t decoded_size;
2017 EXPECT_TRUE(reader.DecodeSize(&decoded_size));
2018 EXPECT_EQ(4u, decoded_size);
2019 }
2020
2021 #endif // BUILDFLAG(INCLUDE_TRANSPORT_SECURITY_STATE_PRELOAD_LIST)
2022
TEST_F(TransportSecurityStateTest,UpdateKeyPinsListValidPin)2023 TEST_F(TransportSecurityStateTest, UpdateKeyPinsListValidPin) {
2024 base::test::ScopedFeatureList scoped_feature_list_;
2025 scoped_feature_list_.InitAndEnableFeature(
2026 net::features::kStaticKeyPinningEnforcement);
2027 HostPortPair host_port_pair(kHost, kPort);
2028 GURL report_uri(kReportUri);
2029 NetworkAnonymizationKey network_anonymization_key =
2030 NetworkAnonymizationKey::CreateTransient();
2031 // Two dummy certs to use as the server-sent and validated chains. The
2032 // contents don't matter.
2033 scoped_refptr<X509Certificate> cert1 =
2034 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
2035 ASSERT_TRUE(cert1);
2036 scoped_refptr<X509Certificate> cert2 =
2037 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
2038 ASSERT_TRUE(cert2);
2039
2040 HashValueVector bad_hashes;
2041
2042 for (size_t i = 0; kBadPath[i]; i++)
2043 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
2044
2045 TransportSecurityState state;
2046 EnableStaticPins(&state);
2047 std::string unused_failure_log;
2048
2049 // Prior to updating the list, bad_hashes should be rejected.
2050 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2051 state.CheckPublicKeyPins(
2052 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
2053 TransportSecurityState::ENABLE_PIN_REPORTS,
2054 network_anonymization_key, &unused_failure_log));
2055
2056 // Update the pins list, adding bad_hashes to the accepted hashes for this
2057 // host.
2058 std::vector<std::vector<uint8_t>> accepted_hashes;
2059 for (size_t i = 0; kBadPath[i]; i++) {
2060 HashValue hash;
2061 ASSERT_TRUE(hash.FromString(kBadPath[i]));
2062 accepted_hashes.emplace_back(hash.data(), hash.data() + hash.size());
2063 }
2064 TransportSecurityState::PinSet test_pinset(
2065 /*name=*/"test",
2066 /*static_spki_hashes=*/accepted_hashes,
2067 /*bad_static_spki_hashes=*/{},
2068 /*report_uri=*/kReportUri);
2069 TransportSecurityState::PinSetInfo test_pinsetinfo(
2070 /*hostname=*/kHost, /*pinset_name=*/"test",
2071 /*include_subdomains=*/false);
2072 state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());
2073
2074 // Hashes should now be accepted.
2075 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2076 state.CheckPublicKeyPins(
2077 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
2078 TransportSecurityState::ENABLE_PIN_REPORTS,
2079 network_anonymization_key, &unused_failure_log));
2080 }
2081
TEST_F(TransportSecurityStateTest,UpdateKeyPinsListNotValidPin)2082 TEST_F(TransportSecurityStateTest, UpdateKeyPinsListNotValidPin) {
2083 base::test::ScopedFeatureList scoped_feature_list_;
2084 scoped_feature_list_.InitAndEnableFeature(
2085 net::features::kStaticKeyPinningEnforcement);
2086 HostPortPair host_port_pair(kHost, kPort);
2087 GURL report_uri(kReportUri);
2088 NetworkAnonymizationKey network_anonymization_key =
2089 NetworkAnonymizationKey::CreateTransient();
2090 // Two dummy certs to use as the server-sent and validated chains. The
2091 // contents don't matter.
2092 scoped_refptr<X509Certificate> cert1 =
2093 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
2094 ASSERT_TRUE(cert1);
2095 scoped_refptr<X509Certificate> cert2 =
2096 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
2097 ASSERT_TRUE(cert2);
2098
2099 HashValueVector good_hashes;
2100
2101 for (size_t i = 0; kGoodPath[i]; i++)
2102 EXPECT_TRUE(AddHash(kGoodPath[i], &good_hashes));
2103
2104 TransportSecurityState state;
2105 EnableStaticPins(&state);
2106 std::string unused_failure_log;
2107
2108 // Prior to updating the list, good_hashes should be accepted
2109 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2110 state.CheckPublicKeyPins(
2111 host_port_pair, true, good_hashes, cert1.get(), cert2.get(),
2112 TransportSecurityState::ENABLE_PIN_REPORTS,
2113 network_anonymization_key, &unused_failure_log));
2114
2115 // Update the pins list, adding good_hashes to the rejected hashes for this
2116 // host.
2117 std::vector<std::vector<uint8_t>> rejected_hashes;
2118 for (size_t i = 0; kGoodPath[i]; i++) {
2119 HashValue hash;
2120 ASSERT_TRUE(hash.FromString(kGoodPath[i]));
2121 rejected_hashes.emplace_back(hash.data(), hash.data() + hash.size());
2122 }
2123 TransportSecurityState::PinSet test_pinset(
2124 /*name=*/"test",
2125 /*static_spki_hashes=*/{},
2126 /*bad_static_spki_hashes=*/rejected_hashes,
2127 /*report_uri=*/kReportUri);
2128 TransportSecurityState::PinSetInfo test_pinsetinfo(
2129 /*hostname=*/kHost, /* pinset_name=*/"test",
2130 /*include_subdomains=*/false);
2131 state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());
2132
2133 // Hashes should now be rejected.
2134 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2135 state.CheckPublicKeyPins(
2136 host_port_pair, true, good_hashes, cert1.get(), cert2.get(),
2137 TransportSecurityState::ENABLE_PIN_REPORTS,
2138 network_anonymization_key, &unused_failure_log));
2139
2140 // Hashes should also be rejected if the hostname has a trailing dot.
2141 host_port_pair = HostPortPair("example.test.", kPort);
2142 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2143 state.CheckPublicKeyPins(
2144 host_port_pair, true, good_hashes, cert1.get(), cert2.get(),
2145 TransportSecurityState::ENABLE_PIN_REPORTS,
2146 network_anonymization_key, &unused_failure_log));
2147
2148 // Hashes should also be rejected if the hostname has different
2149 // capitalization.
2150 host_port_pair = HostPortPair("ExAmpLe.tEsT", kPort);
2151 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2152 state.CheckPublicKeyPins(
2153 host_port_pair, true, good_hashes, cert1.get(), cert2.get(),
2154 TransportSecurityState::ENABLE_PIN_REPORTS,
2155 network_anonymization_key, &unused_failure_log));
2156 }
2157
TEST_F(TransportSecurityStateTest,UpdateKeyPinsEmptyList)2158 TEST_F(TransportSecurityStateTest, UpdateKeyPinsEmptyList) {
2159 base::test::ScopedFeatureList scoped_feature_list_;
2160 scoped_feature_list_.InitAndEnableFeature(
2161 net::features::kStaticKeyPinningEnforcement);
2162 HostPortPair host_port_pair(kHost, kPort);
2163 GURL report_uri(kReportUri);
2164 NetworkAnonymizationKey network_anonymization_key =
2165 NetworkAnonymizationKey::CreateTransient();
2166 // Two dummy certs to use as the server-sent and validated chains. The
2167 // contents don't matter.
2168 scoped_refptr<X509Certificate> cert1 =
2169 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
2170 ASSERT_TRUE(cert1);
2171 scoped_refptr<X509Certificate> cert2 =
2172 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
2173 ASSERT_TRUE(cert2);
2174
2175 HashValueVector bad_hashes;
2176
2177 for (size_t i = 0; kBadPath[i]; i++)
2178 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
2179
2180 TransportSecurityState state;
2181 EnableStaticPins(&state);
2182 std::string unused_failure_log;
2183
2184 // Prior to updating the list, bad_hashes should be rejected.
2185 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2186 state.CheckPublicKeyPins(
2187 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
2188 TransportSecurityState::ENABLE_PIN_REPORTS,
2189 network_anonymization_key, &unused_failure_log));
2190
2191 // Update the pins list with an empty list.
2192 state.UpdatePinList({}, {}, base::Time::Now());
2193
2194 // Hashes should now be accepted.
2195 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2196 state.CheckPublicKeyPins(
2197 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
2198 TransportSecurityState::ENABLE_PIN_REPORTS,
2199 network_anonymization_key, &unused_failure_log));
2200 }
2201
TEST_F(TransportSecurityStateTest,UpdateKeyPinsIncludeSubdomains)2202 TEST_F(TransportSecurityStateTest, UpdateKeyPinsIncludeSubdomains) {
2203 base::test::ScopedFeatureList scoped_feature_list_;
2204 scoped_feature_list_.InitAndEnableFeature(
2205 net::features::kStaticKeyPinningEnforcement);
2206 HostPortPair host_port_pair("example.sub.test", kPort);
2207 GURL report_uri(kReportUri);
2208 NetworkAnonymizationKey network_anonymization_key =
2209 NetworkAnonymizationKey::CreateTransient();
2210 // Two dummy certs to use as the server-sent and validated chains. The
2211 // contents don't matter.
2212 scoped_refptr<X509Certificate> cert1 =
2213 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
2214 ASSERT_TRUE(cert1);
2215 scoped_refptr<X509Certificate> cert2 =
2216 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
2217 ASSERT_TRUE(cert2);
2218
2219 // unpinned_hashes is a set of hashes that (after the update) won't match the
2220 // expected hashes for the tld of this domain. kGoodPath is used here because
2221 // it's a path that is accepted prior to any updates, and this test will
2222 // validate it is rejected afterwards.
2223 HashValueVector unpinned_hashes;
2224 for (size_t i = 0; kGoodPath[i]; i++) {
2225 EXPECT_TRUE(AddHash(kGoodPath[i], &unpinned_hashes));
2226 }
2227
2228 TransportSecurityState state;
2229 EnableStaticPins(&state);
2230 std::string unused_failure_log;
2231
2232 // Prior to updating the list, unpinned_hashes should be accepted
2233 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2234 state.CheckPublicKeyPins(
2235 host_port_pair, true, unpinned_hashes, cert1.get(), cert2.get(),
2236 TransportSecurityState::ENABLE_PIN_REPORTS,
2237 network_anonymization_key, &unused_failure_log));
2238
2239 // Update the pins list, adding kBadPath to the accepted hashes for this
2240 // host, relying on include_subdomains for enforcement. The contents of the
2241 // hashes don't matter as long as they are different from unpinned_hashes,
2242 // kBadPath is used for convenience.
2243 std::vector<std::vector<uint8_t>> accepted_hashes;
2244 for (size_t i = 0; kBadPath[i]; i++) {
2245 HashValue hash;
2246 ASSERT_TRUE(hash.FromString(kBadPath[i]));
2247 accepted_hashes.emplace_back(hash.data(), hash.data() + hash.size());
2248 }
2249 TransportSecurityState::PinSet test_pinset(
2250 /*name=*/"test",
2251 /*static_spki_hashes=*/{accepted_hashes},
2252 /*bad_static_spki_hashes=*/{},
2253 /*report_uri=*/kReportUri);
2254 // The host used in the test is "example.sub.test", so this pinset will only
2255 // match due to include subdomains.
2256 TransportSecurityState::PinSetInfo test_pinsetinfo(
2257 /*hostname=*/"sub.test", /* pinset_name=*/"test",
2258 /*include_subdomains=*/true);
2259 state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());
2260
2261 // The path that was accepted before updating the pins should now be rejected.
2262 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2263 state.CheckPublicKeyPins(
2264 host_port_pair, true, unpinned_hashes, cert1.get(), cert2.get(),
2265 TransportSecurityState::ENABLE_PIN_REPORTS,
2266 network_anonymization_key, &unused_failure_log));
2267 }
2268
TEST_F(TransportSecurityStateTest,UpdateKeyPinsIncludeSubdomainsTLD)2269 TEST_F(TransportSecurityStateTest, UpdateKeyPinsIncludeSubdomainsTLD) {
2270 base::test::ScopedFeatureList scoped_feature_list_;
2271 scoped_feature_list_.InitAndEnableFeature(
2272 net::features::kStaticKeyPinningEnforcement);
2273 HostPortPair host_port_pair(kHost, kPort);
2274 GURL report_uri(kReportUri);
2275 NetworkAnonymizationKey network_anonymization_key =
2276 NetworkAnonymizationKey::CreateTransient();
2277 // Two dummy certs to use as the server-sent and validated chains. The
2278 // contents don't matter.
2279 scoped_refptr<X509Certificate> cert1 =
2280 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
2281 ASSERT_TRUE(cert1);
2282 scoped_refptr<X509Certificate> cert2 =
2283 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
2284 ASSERT_TRUE(cert2);
2285
2286 // unpinned_hashes is a set of hashes that (after the update) won't match the
2287 // expected hashes for the tld of this domain. kGoodPath is used here because
2288 // it's a path that is accepted prior to any updates, and this test will
2289 // validate it is rejected afterwards.
2290 HashValueVector unpinned_hashes;
2291 for (size_t i = 0; kGoodPath[i]; i++) {
2292 EXPECT_TRUE(AddHash(kGoodPath[i], &unpinned_hashes));
2293 }
2294
2295 TransportSecurityState state;
2296 EnableStaticPins(&state);
2297 std::string unused_failure_log;
2298
2299 // Prior to updating the list, unpinned_hashes should be accepted
2300 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2301 state.CheckPublicKeyPins(
2302 host_port_pair, true, unpinned_hashes, cert1.get(), cert2.get(),
2303 TransportSecurityState::ENABLE_PIN_REPORTS,
2304 network_anonymization_key, &unused_failure_log));
2305
2306 // Update the pins list, adding kBadPath to the accepted hashes for this
2307 // host, relying on include_subdomains for enforcement. The contents of the
2308 // hashes don't matter as long as they are different from unpinned_hashes,
2309 // kBadPath is used for convenience.
2310 std::vector<std::vector<uint8_t>> accepted_hashes;
2311 for (size_t i = 0; kBadPath[i]; i++) {
2312 HashValue hash;
2313 ASSERT_TRUE(hash.FromString(kBadPath[i]));
2314 accepted_hashes.emplace_back(hash.data(), hash.data() + hash.size());
2315 }
2316 TransportSecurityState::PinSet test_pinset(
2317 /*name=*/"test",
2318 /*static_spki_hashes=*/{accepted_hashes},
2319 /*bad_static_spki_hashes=*/{},
2320 /*report_uri=*/kReportUri);
2321 // The host used in the test is "example.test", so this pinset will only match
2322 // due to include subdomains.
2323 TransportSecurityState::PinSetInfo test_pinsetinfo(
2324 /*hostname=*/"test", /* pinset_name=*/"test",
2325 /*include_subdomains=*/true);
2326 state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());
2327
2328 // The path that was accepted before updating the pins should now be rejected.
2329 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2330 state.CheckPublicKeyPins(
2331 host_port_pair, true, unpinned_hashes, cert1.get(), cert2.get(),
2332 TransportSecurityState::ENABLE_PIN_REPORTS,
2333 network_anonymization_key, &unused_failure_log));
2334 }
2335
TEST_F(TransportSecurityStateTest,UpdateKeyPinsDontIncludeSubdomains)2336 TEST_F(TransportSecurityStateTest, UpdateKeyPinsDontIncludeSubdomains) {
2337 base::test::ScopedFeatureList scoped_feature_list_;
2338 scoped_feature_list_.InitAndEnableFeature(
2339 net::features::kStaticKeyPinningEnforcement);
2340 HostPortPair host_port_pair(kHost, kPort);
2341 GURL report_uri(kReportUri);
2342 NetworkAnonymizationKey network_anonymization_key =
2343 NetworkAnonymizationKey::CreateTransient();
2344 // Two dummy certs to use as the server-sent and validated chains. The
2345 // contents don't matter.
2346 scoped_refptr<X509Certificate> cert1 =
2347 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
2348 ASSERT_TRUE(cert1);
2349 scoped_refptr<X509Certificate> cert2 =
2350 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
2351 ASSERT_TRUE(cert2);
2352
2353 // unpinned_hashes is a set of hashes that (after the update) won't match the
2354 // expected hashes for the tld of this domain. kGoodPath is used here because
2355 // it's a path that is accepted prior to any updates, and this test will
2356 // validate it is accepted or rejected afterwards depending on whether the
2357 // domain is an exact match.
2358 HashValueVector unpinned_hashes;
2359 for (size_t i = 0; kGoodPath[i]; i++) {
2360 EXPECT_TRUE(AddHash(kGoodPath[i], &unpinned_hashes));
2361 }
2362
2363 TransportSecurityState state;
2364 EnableStaticPins(&state);
2365 std::string unused_failure_log;
2366
2367 // Prior to updating the list, unpinned_hashes should be accepted
2368 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2369 state.CheckPublicKeyPins(
2370 host_port_pair, true, unpinned_hashes, cert1.get(), cert2.get(),
2371 TransportSecurityState::ENABLE_PIN_REPORTS,
2372 network_anonymization_key, &unused_failure_log));
2373
2374 // Update the pins list, adding kBadPath to the accepted hashes for the
2375 // tld of this host, but without include_subdomains set. The contents of the
2376 // hashes don't matter as long as they are different from unpinned_hashes,
2377 // kBadPath is used for convenience.
2378 std::vector<std::vector<uint8_t>> accepted_hashes;
2379 for (size_t i = 0; kBadPath[i]; i++) {
2380 HashValue hash;
2381 ASSERT_TRUE(hash.FromString(kBadPath[i]));
2382 accepted_hashes.emplace_back(hash.data(), hash.data() + hash.size());
2383 }
2384 TransportSecurityState::PinSet test_pinset(
2385 /*name=*/"test",
2386 /*static_spki_hashes=*/{accepted_hashes},
2387 /*bad_static_spki_hashes=*/{},
2388 /*report_uri=*/kReportUri);
2389 // The host used in the test is "example.test", so this pinset will not match
2390 // due to include subdomains not being set.
2391 TransportSecurityState::PinSetInfo test_pinsetinfo(
2392 /*hostname=*/"test", /* pinset_name=*/"test",
2393 /*include_subdomains=*/false);
2394 state.UpdatePinList({test_pinset}, {test_pinsetinfo}, base::Time::Now());
2395
2396 // Hashes that were accepted before the update should still be accepted since
2397 // include subdomains is not set for the pinset, and this is not an exact
2398 // match.
2399 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2400 state.CheckPublicKeyPins(
2401 host_port_pair, true, unpinned_hashes, cert1.get(), cert2.get(),
2402 TransportSecurityState::ENABLE_PIN_REPORTS,
2403 network_anonymization_key, &unused_failure_log));
2404
2405 // Hashes should be rejected for an exact match of the hostname.
2406 HostPortPair exact_match_host("test", kPort);
2407 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2408 state.CheckPublicKeyPins(
2409 exact_match_host, true, unpinned_hashes, cert1.get(),
2410 cert2.get(), TransportSecurityState::ENABLE_PIN_REPORTS,
2411 network_anonymization_key, &unused_failure_log));
2412 }
2413
TEST_F(TransportSecurityStateTest,UpdateKeyPinsListTimestamp)2414 TEST_F(TransportSecurityStateTest, UpdateKeyPinsListTimestamp) {
2415 base::test::ScopedFeatureList scoped_feature_list_;
2416 scoped_feature_list_.InitAndEnableFeature(
2417 net::features::kStaticKeyPinningEnforcement);
2418 HostPortPair host_port_pair(kHost, kPort);
2419 GURL report_uri(kReportUri);
2420 NetworkAnonymizationKey network_anonymization_key =
2421 NetworkAnonymizationKey::CreateTransient();
2422 // Two dummy certs to use as the server-sent and validated chains. The
2423 // contents don't matter.
2424 scoped_refptr<X509Certificate> cert1 =
2425 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
2426 ASSERT_TRUE(cert1);
2427 scoped_refptr<X509Certificate> cert2 =
2428 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
2429 ASSERT_TRUE(cert2);
2430
2431 HashValueVector bad_hashes;
2432
2433 for (size_t i = 0; kBadPath[i]; i++)
2434 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
2435
2436 TransportSecurityState state;
2437 EnableStaticPins(&state);
2438 std::string unused_failure_log;
2439
2440 // Prior to updating the list, bad_hashes should be rejected.
2441 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2442 state.CheckPublicKeyPins(
2443 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
2444 TransportSecurityState::ENABLE_PIN_REPORTS,
2445 network_anonymization_key, &unused_failure_log));
2446
2447 // TransportSecurityStateTest sets a flag when EnableStaticPins is called that
2448 // results in TransportSecurityState considering the pins list as always
2449 // timely. We need to disable it so we can test that the timestamp has the
2450 // required effect.
2451 state.SetPinningListAlwaysTimelyForTesting(false);
2452
2453 // Update the pins list, with bad hashes as rejected, but a timestamp >70 days
2454 // old.
2455 std::vector<std::vector<uint8_t>> rejected_hashes;
2456 for (size_t i = 0; kBadPath[i]; i++) {
2457 HashValue hash;
2458 ASSERT_TRUE(hash.FromString(kBadPath[i]));
2459 rejected_hashes.emplace_back(hash.data(), hash.data() + hash.size());
2460 }
2461 TransportSecurityState::PinSet test_pinset(
2462 /*name=*/"test",
2463 /*static_spki_hashes=*/{},
2464 /*bad_static_spki_hashes=*/rejected_hashes,
2465 /*report_uri=*/kReportUri);
2466 TransportSecurityState::PinSetInfo test_pinsetinfo(
2467 /*hostname=*/kHost, /* pinset_name=*/"test",
2468 /*include_subdomains=*/false);
2469 state.UpdatePinList({test_pinset}, {test_pinsetinfo},
2470 base::Time::Now() - base::Days(70));
2471
2472 // Hashes should now be accepted.
2473 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2474 state.CheckPublicKeyPins(
2475 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
2476 TransportSecurityState::ENABLE_PIN_REPORTS,
2477 network_anonymization_key, &unused_failure_log));
2478
2479 // Update the pins list again, with a timestamp <70 days old.
2480 state.UpdatePinList({test_pinset}, {test_pinsetinfo},
2481 base::Time::Now() - base::Days(69));
2482
2483 // Hashes should now be rejected.
2484 EXPECT_EQ(TransportSecurityState::PKPStatus::VIOLATED,
2485 state.CheckPublicKeyPins(
2486 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
2487 TransportSecurityState::ENABLE_PIN_REPORTS,
2488 network_anonymization_key, &unused_failure_log));
2489 }
2490
2491 class TransportSecurityStatePinningKillswitchTest
2492 : public TransportSecurityStateTest {
2493 public:
TransportSecurityStatePinningKillswitchTest()2494 TransportSecurityStatePinningKillswitchTest() {
2495 scoped_feature_list_.InitAndDisableFeature(
2496 features::kStaticKeyPinningEnforcement);
2497 }
2498
2499 protected:
2500 base::test::ScopedFeatureList scoped_feature_list_;
2501 };
2502
TEST_F(TransportSecurityStatePinningKillswitchTest,PinningKillswitchSet)2503 TEST_F(TransportSecurityStatePinningKillswitchTest, PinningKillswitchSet) {
2504 HostPortPair host_port_pair(kHost, kPort);
2505 GURL report_uri(kReportUri);
2506 NetworkAnonymizationKey network_anonymization_key =
2507 NetworkAnonymizationKey::CreateTransient();
2508 // Two dummy certs to use as the server-sent and validated chains. The
2509 // contents don't matter.
2510 scoped_refptr<X509Certificate> cert1 =
2511 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
2512 ASSERT_TRUE(cert1);
2513 scoped_refptr<X509Certificate> cert2 =
2514 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
2515 ASSERT_TRUE(cert2);
2516
2517 HashValueVector bad_hashes;
2518
2519 for (size_t i = 0; kBadPath[i]; i++)
2520 EXPECT_TRUE(AddHash(kBadPath[i], &bad_hashes));
2521
2522 TransportSecurityState state;
2523 EnableStaticPins(&state);
2524 std::string unused_failure_log;
2525
2526 // Hashes should be accepted since pinning enforcement is disabled.
2527 EXPECT_EQ(TransportSecurityState::PKPStatus::OK,
2528 state.CheckPublicKeyPins(
2529 host_port_pair, true, bad_hashes, cert1.get(), cert2.get(),
2530 TransportSecurityState::ENABLE_PIN_REPORTS,
2531 network_anonymization_key, &unused_failure_log));
2532 }
2533
2534 } // namespace net
2535