- add sources.
[platform/framework/web/crosswalk.git] / src / net / http / transport_security_state.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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 #if defined(USE_OPENSSL)
8 #include <openssl/ecdsa.h>
9 #include <openssl/ssl.h>
10 #else  // !defined(USE_OPENSSL)
11 #include <cryptohi.h>
12 #include <hasht.h>
13 #include <keyhi.h>
14 #include <nspr.h>
15 #include <pk11pub.h>
16 #endif
17
18 #include <algorithm>
19
20 #include "base/base64.h"
21 #include "base/build_time.h"
22 #include "base/logging.h"
23 #include "base/memory/scoped_ptr.h"
24 #include "base/metrics/histogram.h"
25 #include "base/sha1.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/time/time.h"
30 #include "base/values.h"
31 #include "crypto/sha2.h"
32 #include "net/base/dns_util.h"
33 #include "net/cert/x509_cert_types.h"
34 #include "net/cert/x509_certificate.h"
35 #include "net/http/http_security_headers.h"
36 #include "net/ssl/ssl_info.h"
37 #include "url/gurl.h"
38
39 #if defined(USE_OPENSSL)
40 #include "crypto/openssl_util.h"
41 #endif
42
43 namespace net {
44
45 namespace {
46
47 std::string HashesToBase64String(const HashValueVector& hashes) {
48   std::string str;
49   for (size_t i = 0; i != hashes.size(); ++i) {
50     if (i != 0)
51       str += ",";
52     str += hashes[i].ToString();
53   }
54   return str;
55 }
56
57 std::string HashHost(const std::string& canonicalized_host) {
58   char hashed[crypto::kSHA256Length];
59   crypto::SHA256HashString(canonicalized_host, hashed, sizeof(hashed));
60   return std::string(hashed, sizeof(hashed));
61 }
62
63 // Returns true if the intersection of |a| and |b| is not empty. If either
64 // |a| or |b| is empty, returns false.
65 bool HashesIntersect(const HashValueVector& a,
66                      const HashValueVector& b) {
67   for (HashValueVector::const_iterator i = a.begin(); i != a.end(); ++i) {
68     HashValueVector::const_iterator j =
69         std::find_if(b.begin(), b.end(), HashValuesEqual(*i));
70     if (j != b.end())
71       return true;
72   }
73   return false;
74 }
75
76 bool AddHash(const char* sha1_hash,
77              HashValueVector* out) {
78   HashValue hash(HASH_VALUE_SHA1);
79   memcpy(hash.data(), sha1_hash, hash.size());
80   out->push_back(hash);
81   return true;
82 }
83
84 }  // namespace
85
86 TransportSecurityState::TransportSecurityState()
87   : delegate_(NULL) {
88   DCHECK(CalledOnValidThread());
89 }
90
91 TransportSecurityState::Iterator::Iterator(const TransportSecurityState& state)
92     : iterator_(state.enabled_hosts_.begin()),
93       end_(state.enabled_hosts_.end()) {
94 }
95
96 TransportSecurityState::Iterator::~Iterator() {}
97
98 void TransportSecurityState::SetDelegate(
99     TransportSecurityState::Delegate* delegate) {
100   DCHECK(CalledOnValidThread());
101   delegate_ = delegate;
102 }
103
104 void TransportSecurityState::EnableHost(const std::string& host,
105                                         const DomainState& state) {
106   DCHECK(CalledOnValidThread());
107
108   const std::string canonicalized_host = CanonicalizeHost(host);
109   if (canonicalized_host.empty())
110     return;
111
112   DomainState state_copy(state);
113   // No need to store this value since it is redundant. (|canonicalized_host|
114   // is the map key.)
115   state_copy.domain.clear();
116
117   enabled_hosts_[HashHost(canonicalized_host)] = state_copy;
118   DirtyNotify();
119 }
120
121 bool TransportSecurityState::DeleteDynamicDataForHost(const std::string& host) {
122   DCHECK(CalledOnValidThread());
123
124   const std::string canonicalized_host = CanonicalizeHost(host);
125   if (canonicalized_host.empty())
126     return false;
127
128   DomainStateMap::iterator i = enabled_hosts_.find(
129       HashHost(canonicalized_host));
130   if (i != enabled_hosts_.end()) {
131     enabled_hosts_.erase(i);
132     DirtyNotify();
133     return true;
134   }
135   return false;
136 }
137
138 bool TransportSecurityState::GetDomainState(const std::string& host,
139                                             bool sni_enabled,
140                                             DomainState* result) {
141   DCHECK(CalledOnValidThread());
142
143   DomainState state;
144   const std::string canonicalized_host = CanonicalizeHost(host);
145   if (canonicalized_host.empty())
146     return false;
147
148   bool has_preload = GetStaticDomainState(canonicalized_host, sni_enabled,
149                                           &state);
150   std::string canonicalized_preload = CanonicalizeHost(state.domain);
151   GetDynamicDomainState(host, &state);
152
153   base::Time current_time(base::Time::Now());
154
155   for (size_t i = 0; canonicalized_host[i]; i += canonicalized_host[i] + 1) {
156     std::string host_sub_chunk(&canonicalized_host[i],
157                                canonicalized_host.size() - i);
158     // Exact match of a preload always wins.
159     if (has_preload && host_sub_chunk == canonicalized_preload) {
160       *result = state;
161       return true;
162     }
163
164     DomainStateMap::iterator j =
165         enabled_hosts_.find(HashHost(host_sub_chunk));
166     if (j == enabled_hosts_.end())
167       continue;
168
169     if (current_time > j->second.upgrade_expiry &&
170         current_time > j->second.dynamic_spki_hashes_expiry) {
171       enabled_hosts_.erase(j);
172       DirtyNotify();
173       continue;
174     }
175
176     state = j->second;
177     state.domain = DNSDomainToString(host_sub_chunk);
178
179     // Succeed if we matched the domain exactly or if subdomain matches are
180     // allowed.
181     if (i == 0 || j->second.sts_include_subdomains ||
182         j->second.pkp_include_subdomains) {
183       *result = state;
184       return true;
185     }
186
187     return false;
188   }
189
190   return false;
191 }
192
193 void TransportSecurityState::ClearDynamicData() {
194   DCHECK(CalledOnValidThread());
195   enabled_hosts_.clear();
196 }
197
198 void TransportSecurityState::DeleteAllDynamicDataSince(const base::Time& time) {
199   DCHECK(CalledOnValidThread());
200
201   bool dirtied = false;
202
203   DomainStateMap::iterator i = enabled_hosts_.begin();
204   while (i != enabled_hosts_.end()) {
205     if (i->second.created >= time) {
206       dirtied = true;
207       enabled_hosts_.erase(i++);
208     } else {
209       i++;
210     }
211   }
212
213   if (dirtied)
214     DirtyNotify();
215 }
216
217 TransportSecurityState::~TransportSecurityState() {
218   DCHECK(CalledOnValidThread());
219 }
220
221 void TransportSecurityState::DirtyNotify() {
222   DCHECK(CalledOnValidThread());
223
224   if (delegate_)
225     delegate_->StateIsDirty(this);
226 }
227
228 // static
229 std::string TransportSecurityState::CanonicalizeHost(const std::string& host) {
230   // We cannot perform the operations as detailed in the spec here as |host|
231   // has already undergone IDN processing before it reached us. Thus, we check
232   // that there are no invalid characters in the host and lowercase the result.
233
234   std::string new_host;
235   if (!DNSDomainFromDot(host, &new_host)) {
236     // DNSDomainFromDot can fail if any label is > 63 bytes or if the whole
237     // name is >255 bytes. However, search terms can have those properties.
238     return std::string();
239   }
240
241   for (size_t i = 0; new_host[i]; i += new_host[i] + 1) {
242     const unsigned label_length = static_cast<unsigned>(new_host[i]);
243     if (!label_length)
244       break;
245
246     for (size_t j = 0; j < label_length; ++j) {
247       new_host[i + 1 + j] = tolower(new_host[i + 1 + j]);
248     }
249   }
250
251   return new_host;
252 }
253
254 // |ReportUMAOnPinFailure| uses these to report which domain was associated
255 // with the public key pinning failure.
256 //
257 // DO NOT CHANGE THE ORDERING OF THESE NAMES OR REMOVE ANY OF THEM. Add new
258 // domains at the END of the listing (but before DOMAIN_NUM_EVENTS).
259 enum SecondLevelDomainName {
260   DOMAIN_NOT_PINNED,
261
262   DOMAIN_GOOGLE_COM,
263   DOMAIN_ANDROID_COM,
264   DOMAIN_GOOGLE_ANALYTICS_COM,
265   DOMAIN_GOOGLEPLEX_COM,
266   DOMAIN_YTIMG_COM,
267   DOMAIN_GOOGLEUSERCONTENT_COM,
268   DOMAIN_YOUTUBE_COM,
269   DOMAIN_GOOGLEAPIS_COM,
270   DOMAIN_GOOGLEADSERVICES_COM,
271   DOMAIN_GOOGLECODE_COM,
272   DOMAIN_APPSPOT_COM,
273   DOMAIN_GOOGLESYNDICATION_COM,
274   DOMAIN_DOUBLECLICK_NET,
275   DOMAIN_GSTATIC_COM,
276   DOMAIN_GMAIL_COM,
277   DOMAIN_GOOGLEMAIL_COM,
278   DOMAIN_GOOGLEGROUPS_COM,
279
280   DOMAIN_TORPROJECT_ORG,
281
282   DOMAIN_TWITTER_COM,
283   DOMAIN_TWIMG_COM,
284
285   DOMAIN_AKAMAIHD_NET,
286
287   DOMAIN_TOR2WEB_ORG,
288
289   DOMAIN_YOUTU_BE,
290   DOMAIN_GOOGLECOMMERCE_COM,
291   DOMAIN_URCHIN_COM,
292   DOMAIN_GOO_GL,
293   DOMAIN_G_CO,
294   DOMAIN_GOOGLE_AC,
295   DOMAIN_GOOGLE_AD,
296   DOMAIN_GOOGLE_AE,
297   DOMAIN_GOOGLE_AF,
298   DOMAIN_GOOGLE_AG,
299   DOMAIN_GOOGLE_AM,
300   DOMAIN_GOOGLE_AS,
301   DOMAIN_GOOGLE_AT,
302   DOMAIN_GOOGLE_AZ,
303   DOMAIN_GOOGLE_BA,
304   DOMAIN_GOOGLE_BE,
305   DOMAIN_GOOGLE_BF,
306   DOMAIN_GOOGLE_BG,
307   DOMAIN_GOOGLE_BI,
308   DOMAIN_GOOGLE_BJ,
309   DOMAIN_GOOGLE_BS,
310   DOMAIN_GOOGLE_BY,
311   DOMAIN_GOOGLE_CA,
312   DOMAIN_GOOGLE_CAT,
313   DOMAIN_GOOGLE_CC,
314   DOMAIN_GOOGLE_CD,
315   DOMAIN_GOOGLE_CF,
316   DOMAIN_GOOGLE_CG,
317   DOMAIN_GOOGLE_CH,
318   DOMAIN_GOOGLE_CI,
319   DOMAIN_GOOGLE_CL,
320   DOMAIN_GOOGLE_CM,
321   DOMAIN_GOOGLE_CN,
322   DOMAIN_CO_AO,
323   DOMAIN_CO_BW,
324   DOMAIN_CO_CK,
325   DOMAIN_CO_CR,
326   DOMAIN_CO_HU,
327   DOMAIN_CO_ID,
328   DOMAIN_CO_IL,
329   DOMAIN_CO_IM,
330   DOMAIN_CO_IN,
331   DOMAIN_CO_JE,
332   DOMAIN_CO_JP,
333   DOMAIN_CO_KE,
334   DOMAIN_CO_KR,
335   DOMAIN_CO_LS,
336   DOMAIN_CO_MA,
337   DOMAIN_CO_MZ,
338   DOMAIN_CO_NZ,
339   DOMAIN_CO_TH,
340   DOMAIN_CO_TZ,
341   DOMAIN_CO_UG,
342   DOMAIN_CO_UK,
343   DOMAIN_CO_UZ,
344   DOMAIN_CO_VE,
345   DOMAIN_CO_VI,
346   DOMAIN_CO_ZA,
347   DOMAIN_CO_ZM,
348   DOMAIN_CO_ZW,
349   DOMAIN_COM_AF,
350   DOMAIN_COM_AG,
351   DOMAIN_COM_AI,
352   DOMAIN_COM_AR,
353   DOMAIN_COM_AU,
354   DOMAIN_COM_BD,
355   DOMAIN_COM_BH,
356   DOMAIN_COM_BN,
357   DOMAIN_COM_BO,
358   DOMAIN_COM_BR,
359   DOMAIN_COM_BY,
360   DOMAIN_COM_BZ,
361   DOMAIN_COM_CN,
362   DOMAIN_COM_CO,
363   DOMAIN_COM_CU,
364   DOMAIN_COM_CY,
365   DOMAIN_COM_DO,
366   DOMAIN_COM_EC,
367   DOMAIN_COM_EG,
368   DOMAIN_COM_ET,
369   DOMAIN_COM_FJ,
370   DOMAIN_COM_GE,
371   DOMAIN_COM_GH,
372   DOMAIN_COM_GI,
373   DOMAIN_COM_GR,
374   DOMAIN_COM_GT,
375   DOMAIN_COM_HK,
376   DOMAIN_COM_IQ,
377   DOMAIN_COM_JM,
378   DOMAIN_COM_JO,
379   DOMAIN_COM_KH,
380   DOMAIN_COM_KW,
381   DOMAIN_COM_LB,
382   DOMAIN_COM_LY,
383   DOMAIN_COM_MT,
384   DOMAIN_COM_MX,
385   DOMAIN_COM_MY,
386   DOMAIN_COM_NA,
387   DOMAIN_COM_NF,
388   DOMAIN_COM_NG,
389   DOMAIN_COM_NI,
390   DOMAIN_COM_NP,
391   DOMAIN_COM_NR,
392   DOMAIN_COM_OM,
393   DOMAIN_COM_PA,
394   DOMAIN_COM_PE,
395   DOMAIN_COM_PH,
396   DOMAIN_COM_PK,
397   DOMAIN_COM_PL,
398   DOMAIN_COM_PR,
399   DOMAIN_COM_PY,
400   DOMAIN_COM_QA,
401   DOMAIN_COM_RU,
402   DOMAIN_COM_SA,
403   DOMAIN_COM_SB,
404   DOMAIN_COM_SG,
405   DOMAIN_COM_SL,
406   DOMAIN_COM_SV,
407   DOMAIN_COM_TJ,
408   DOMAIN_COM_TN,
409   DOMAIN_COM_TR,
410   DOMAIN_COM_TW,
411   DOMAIN_COM_UA,
412   DOMAIN_COM_UY,
413   DOMAIN_COM_VC,
414   DOMAIN_COM_VE,
415   DOMAIN_COM_VN,
416   DOMAIN_GOOGLE_CV,
417   DOMAIN_GOOGLE_CZ,
418   DOMAIN_GOOGLE_DE,
419   DOMAIN_GOOGLE_DJ,
420   DOMAIN_GOOGLE_DK,
421   DOMAIN_GOOGLE_DM,
422   DOMAIN_GOOGLE_DZ,
423   DOMAIN_GOOGLE_EE,
424   DOMAIN_GOOGLE_ES,
425   DOMAIN_GOOGLE_FI,
426   DOMAIN_GOOGLE_FM,
427   DOMAIN_GOOGLE_FR,
428   DOMAIN_GOOGLE_GA,
429   DOMAIN_GOOGLE_GE,
430   DOMAIN_GOOGLE_GG,
431   DOMAIN_GOOGLE_GL,
432   DOMAIN_GOOGLE_GM,
433   DOMAIN_GOOGLE_GP,
434   DOMAIN_GOOGLE_GR,
435   DOMAIN_GOOGLE_GY,
436   DOMAIN_GOOGLE_HK,
437   DOMAIN_GOOGLE_HN,
438   DOMAIN_GOOGLE_HR,
439   DOMAIN_GOOGLE_HT,
440   DOMAIN_GOOGLE_HU,
441   DOMAIN_GOOGLE_IE,
442   DOMAIN_GOOGLE_IM,
443   DOMAIN_GOOGLE_INFO,
444   DOMAIN_GOOGLE_IQ,
445   DOMAIN_GOOGLE_IS,
446   DOMAIN_GOOGLE_IT,
447   DOMAIN_IT_AO,
448   DOMAIN_GOOGLE_JE,
449   DOMAIN_GOOGLE_JO,
450   DOMAIN_GOOGLE_JOBS,
451   DOMAIN_GOOGLE_JP,
452   DOMAIN_GOOGLE_KG,
453   DOMAIN_GOOGLE_KI,
454   DOMAIN_GOOGLE_KZ,
455   DOMAIN_GOOGLE_LA,
456   DOMAIN_GOOGLE_LI,
457   DOMAIN_GOOGLE_LK,
458   DOMAIN_GOOGLE_LT,
459   DOMAIN_GOOGLE_LU,
460   DOMAIN_GOOGLE_LV,
461   DOMAIN_GOOGLE_MD,
462   DOMAIN_GOOGLE_ME,
463   DOMAIN_GOOGLE_MG,
464   DOMAIN_GOOGLE_MK,
465   DOMAIN_GOOGLE_ML,
466   DOMAIN_GOOGLE_MN,
467   DOMAIN_GOOGLE_MS,
468   DOMAIN_GOOGLE_MU,
469   DOMAIN_GOOGLE_MV,
470   DOMAIN_GOOGLE_MW,
471   DOMAIN_GOOGLE_NE,
472   DOMAIN_NE_JP,
473   DOMAIN_GOOGLE_NET,
474   DOMAIN_GOOGLE_NL,
475   DOMAIN_GOOGLE_NO,
476   DOMAIN_GOOGLE_NR,
477   DOMAIN_GOOGLE_NU,
478   DOMAIN_OFF_AI,
479   DOMAIN_GOOGLE_PK,
480   DOMAIN_GOOGLE_PL,
481   DOMAIN_GOOGLE_PN,
482   DOMAIN_GOOGLE_PS,
483   DOMAIN_GOOGLE_PT,
484   DOMAIN_GOOGLE_RO,
485   DOMAIN_GOOGLE_RS,
486   DOMAIN_GOOGLE_RU,
487   DOMAIN_GOOGLE_RW,
488   DOMAIN_GOOGLE_SC,
489   DOMAIN_GOOGLE_SE,
490   DOMAIN_GOOGLE_SH,
491   DOMAIN_GOOGLE_SI,
492   DOMAIN_GOOGLE_SK,
493   DOMAIN_GOOGLE_SM,
494   DOMAIN_GOOGLE_SN,
495   DOMAIN_GOOGLE_SO,
496   DOMAIN_GOOGLE_ST,
497   DOMAIN_GOOGLE_TD,
498   DOMAIN_GOOGLE_TG,
499   DOMAIN_GOOGLE_TK,
500   DOMAIN_GOOGLE_TL,
501   DOMAIN_GOOGLE_TM,
502   DOMAIN_GOOGLE_TN,
503   DOMAIN_GOOGLE_TO,
504   DOMAIN_GOOGLE_TP,
505   DOMAIN_GOOGLE_TT,
506   DOMAIN_GOOGLE_US,
507   DOMAIN_GOOGLE_UZ,
508   DOMAIN_GOOGLE_VG,
509   DOMAIN_GOOGLE_VU,
510   DOMAIN_GOOGLE_WS,
511
512   DOMAIN_CHROMIUM_ORG,
513
514   DOMAIN_CRYPTO_CAT,
515   DOMAIN_LAVABIT_COM,
516
517   // Boundary value for UMA_HISTOGRAM_ENUMERATION:
518   DOMAIN_NUM_EVENTS
519 };
520
521 // PublicKeyPins contains a number of SubjectPublicKeyInfo hashes for a site.
522 // The validated certificate chain for the site must not include any of
523 // |excluded_hashes| and must include one or more of |required_hashes|.
524 struct PublicKeyPins {
525   const char* const* required_hashes;
526   const char* const* excluded_hashes;
527 };
528
529 struct HSTSPreload {
530   uint8 length;
531   bool include_subdomains;
532   char dns_name[38];
533   bool https_required;
534   PublicKeyPins pins;
535   SecondLevelDomainName second_level_domain_name;
536 };
537
538 static bool HasPreload(const struct HSTSPreload* entries, size_t num_entries,
539                        const std::string& canonicalized_host, size_t i,
540                        TransportSecurityState::DomainState* out, bool* ret) {
541   for (size_t j = 0; j < num_entries; j++) {
542     if (entries[j].length == canonicalized_host.size() - i &&
543         memcmp(entries[j].dns_name, &canonicalized_host[i],
544                entries[j].length) == 0) {
545       if (!entries[j].include_subdomains && i != 0) {
546         *ret = false;
547       } else {
548         out->sts_include_subdomains = entries[j].include_subdomains;
549         out->pkp_include_subdomains = entries[j].include_subdomains;
550         *ret = true;
551         if (!entries[j].https_required)
552           out->upgrade_mode = TransportSecurityState::DomainState::MODE_DEFAULT;
553         if (entries[j].pins.required_hashes) {
554           const char* const* sha1_hash = entries[j].pins.required_hashes;
555           while (*sha1_hash) {
556             AddHash(*sha1_hash, &out->static_spki_hashes);
557             sha1_hash++;
558           }
559         }
560         if (entries[j].pins.excluded_hashes) {
561           const char* const* sha1_hash = entries[j].pins.excluded_hashes;
562           while (*sha1_hash) {
563             AddHash(*sha1_hash, &out->bad_static_spki_hashes);
564             sha1_hash++;
565           }
566         }
567       }
568       return true;
569     }
570   }
571   return false;
572 }
573
574 #include "net/http/transport_security_state_static.h"
575
576 // Returns the HSTSPreload entry for the |canonicalized_host| in |entries|,
577 // or NULL if there is none. Prefers exact hostname matches to those that
578 // match only because HSTSPreload.include_subdomains is true.
579 //
580 // |canonicalized_host| should be the hostname as canonicalized by
581 // CanonicalizeHost.
582 static const struct HSTSPreload* GetHSTSPreload(
583     const std::string& canonicalized_host,
584     const struct HSTSPreload* entries,
585     size_t num_entries) {
586   for (size_t i = 0; canonicalized_host[i]; i += canonicalized_host[i] + 1) {
587     for (size_t j = 0; j < num_entries; j++) {
588       const struct HSTSPreload* entry = entries + j;
589
590       if (i != 0 && !entry->include_subdomains)
591         continue;
592
593       if (entry->length == canonicalized_host.size() - i &&
594           memcmp(entry->dns_name, &canonicalized_host[i], entry->length) == 0) {
595         return entry;
596       }
597     }
598   }
599
600   return NULL;
601 }
602
603 bool TransportSecurityState::AddHSTSHeader(const std::string& host,
604                                            const std::string& value) {
605   DCHECK(CalledOnValidThread());
606
607   base::Time now = base::Time::Now();
608   base::TimeDelta max_age;
609   TransportSecurityState::DomainState domain_state;
610   GetDynamicDomainState(host, &domain_state);
611   if (ParseHSTSHeader(value, &max_age, &domain_state.sts_include_subdomains)) {
612     // Handle max-age == 0
613     if (max_age.InSeconds() == 0)
614       domain_state.upgrade_mode = DomainState::MODE_DEFAULT;
615     else
616       domain_state.upgrade_mode = DomainState::MODE_FORCE_HTTPS;
617     domain_state.created = now;
618     domain_state.upgrade_expiry = now + max_age;
619     EnableHost(host, domain_state);
620     return true;
621   }
622   return false;
623 }
624
625 bool TransportSecurityState::AddHPKPHeader(const std::string& host,
626                                            const std::string& value,
627                                            const SSLInfo& ssl_info) {
628   DCHECK(CalledOnValidThread());
629
630   base::Time now = base::Time::Now();
631   base::TimeDelta max_age;
632   TransportSecurityState::DomainState domain_state;
633   GetDynamicDomainState(host, &domain_state);
634   if (ParseHPKPHeader(value, ssl_info.public_key_hashes,
635                       &max_age, &domain_state.pkp_include_subdomains,
636                       &domain_state.dynamic_spki_hashes)) {
637     // TODO(palmer): http://crbug.com/243865 handle max-age == 0.
638     domain_state.created = now;
639     domain_state.dynamic_spki_hashes_expiry = now + max_age;
640     EnableHost(host, domain_state);
641     return true;
642   }
643   return false;
644 }
645
646 bool TransportSecurityState::AddHSTS(const std::string& host,
647                                      const base::Time& expiry,
648                                      bool include_subdomains) {
649   DCHECK(CalledOnValidThread());
650
651   // Copy-and-modify the existing DomainState for this host (if any).
652   TransportSecurityState::DomainState domain_state;
653   const std::string canonicalized_host = CanonicalizeHost(host);
654   const std::string hashed_host = HashHost(canonicalized_host);
655   DomainStateMap::const_iterator i = enabled_hosts_.find(
656       hashed_host);
657   if (i != enabled_hosts_.end())
658     domain_state = i->second;
659
660   domain_state.created = base::Time::Now();
661   domain_state.sts_include_subdomains = include_subdomains;
662   domain_state.upgrade_expiry = expiry;
663   domain_state.upgrade_mode = DomainState::MODE_FORCE_HTTPS;
664   EnableHost(host, domain_state);
665   return true;
666 }
667
668 bool TransportSecurityState::AddHPKP(const std::string& host,
669                                      const base::Time& expiry,
670                                      bool include_subdomains,
671                                      const HashValueVector& hashes) {
672   DCHECK(CalledOnValidThread());
673
674   // Copy-and-modify the existing DomainState for this host (if any).
675   TransportSecurityState::DomainState domain_state;
676   const std::string canonicalized_host = CanonicalizeHost(host);
677   const std::string hashed_host = HashHost(canonicalized_host);
678   DomainStateMap::const_iterator i = enabled_hosts_.find(
679       hashed_host);
680   if (i != enabled_hosts_.end())
681     domain_state = i->second;
682
683   domain_state.created = base::Time::Now();
684   domain_state.pkp_include_subdomains = include_subdomains;
685   domain_state.dynamic_spki_hashes_expiry = expiry;
686   domain_state.dynamic_spki_hashes = hashes;
687   EnableHost(host, domain_state);
688   return true;
689 }
690
691 // static
692 bool TransportSecurityState::IsGooglePinnedProperty(const std::string& host,
693                                                     bool sni_enabled) {
694   std::string canonicalized_host = CanonicalizeHost(host);
695   const struct HSTSPreload* entry =
696       GetHSTSPreload(canonicalized_host, kPreloadedSTS, kNumPreloadedSTS);
697
698   if (entry && entry->pins.required_hashes == kGoogleAcceptableCerts)
699     return true;
700
701   if (sni_enabled) {
702     entry = GetHSTSPreload(canonicalized_host, kPreloadedSNISTS,
703                            kNumPreloadedSNISTS);
704     if (entry && entry->pins.required_hashes == kGoogleAcceptableCerts)
705       return true;
706   }
707
708   return false;
709 }
710
711 // static
712 void TransportSecurityState::ReportUMAOnPinFailure(const std::string& host) {
713   std::string canonicalized_host = CanonicalizeHost(host);
714
715   const struct HSTSPreload* entry =
716       GetHSTSPreload(canonicalized_host, kPreloadedSTS, kNumPreloadedSTS);
717
718   if (!entry) {
719     entry = GetHSTSPreload(canonicalized_host, kPreloadedSNISTS,
720                            kNumPreloadedSNISTS);
721   }
722
723   if (!entry) {
724     // We don't care to report pin failures for dynamic pins.
725     return;
726   }
727
728   DCHECK(entry);
729   DCHECK(entry->pins.required_hashes);
730   DCHECK(entry->second_level_domain_name != DOMAIN_NOT_PINNED);
731
732   UMA_HISTOGRAM_ENUMERATION("Net.PublicKeyPinFailureDomain",
733                             entry->second_level_domain_name, DOMAIN_NUM_EVENTS);
734 }
735
736 // static
737 bool TransportSecurityState::IsBuildTimely() {
738   const base::Time build_time = base::GetBuildTime();
739   // We consider built-in information to be timely for 10 weeks.
740   return (base::Time::Now() - build_time).InDays() < 70 /* 10 weeks */;
741 }
742
743 bool TransportSecurityState::GetStaticDomainState(
744     const std::string& canonicalized_host,
745     bool sni_enabled,
746     DomainState* out) {
747   DCHECK(CalledOnValidThread());
748
749   out->upgrade_mode = DomainState::MODE_FORCE_HTTPS;
750   out->sts_include_subdomains = false;
751   out->pkp_include_subdomains = false;
752
753   const bool is_build_timely = IsBuildTimely();
754
755   for (size_t i = 0; canonicalized_host[i]; i += canonicalized_host[i] + 1) {
756     std::string host_sub_chunk(&canonicalized_host[i],
757                                canonicalized_host.size() - i);
758     out->domain = DNSDomainToString(host_sub_chunk);
759     bool ret;
760     if (is_build_timely &&
761         HasPreload(kPreloadedSTS, kNumPreloadedSTS, canonicalized_host, i, out,
762                    &ret)) {
763       return ret;
764     }
765     if (sni_enabled &&
766         is_build_timely &&
767         HasPreload(kPreloadedSNISTS, kNumPreloadedSNISTS, canonicalized_host, i,
768                    out, &ret)) {
769       return ret;
770     }
771   }
772
773   return false;
774 }
775
776 bool TransportSecurityState::GetDynamicDomainState(const std::string& host,
777                                                    DomainState* result) {
778   DCHECK(CalledOnValidThread());
779
780   DomainState state;
781   const std::string canonicalized_host = CanonicalizeHost(host);
782   if (canonicalized_host.empty())
783     return false;
784
785   base::Time current_time(base::Time::Now());
786
787   for (size_t i = 0; canonicalized_host[i]; i += canonicalized_host[i] + 1) {
788     std::string host_sub_chunk(&canonicalized_host[i],
789                                canonicalized_host.size() - i);
790     DomainStateMap::iterator j =
791         enabled_hosts_.find(HashHost(host_sub_chunk));
792     if (j == enabled_hosts_.end())
793       continue;
794
795     if (current_time > j->second.upgrade_expiry &&
796         current_time > j->second.dynamic_spki_hashes_expiry) {
797       enabled_hosts_.erase(j);
798       DirtyNotify();
799       continue;
800     }
801
802     state = j->second;
803     state.domain = DNSDomainToString(host_sub_chunk);
804
805     // Succeed if we matched the domain exactly or if subdomain matches are
806     // allowed.
807     if (i == 0 || j->second.sts_include_subdomains ||
808         j->second.pkp_include_subdomains) {
809       *result = state;
810       return true;
811     }
812
813     return false;
814   }
815
816   return false;
817 }
818
819
820 void TransportSecurityState::AddOrUpdateEnabledHosts(
821     const std::string& hashed_host, const DomainState& state) {
822   DCHECK(CalledOnValidThread());
823   enabled_hosts_[hashed_host] = state;
824 }
825
826 TransportSecurityState::DomainState::DomainState()
827     : upgrade_mode(MODE_DEFAULT),
828       created(base::Time::Now()),
829       sts_include_subdomains(false),
830       pkp_include_subdomains(false) {
831 }
832
833 TransportSecurityState::DomainState::~DomainState() {
834 }
835
836 bool TransportSecurityState::DomainState::CheckPublicKeyPins(
837     const HashValueVector& hashes) const {
838   // Validate that hashes is not empty. By the time this code is called (in
839   // production), that should never happen, but it's good to be defensive.
840   // And, hashes *can* be empty in some test scenarios.
841   if (hashes.empty()) {
842     LOG(ERROR) << "Rejecting empty public key chain for public-key-pinned "
843                   "domain " << domain;
844     return false;
845   }
846
847   if (HashesIntersect(bad_static_spki_hashes, hashes)) {
848     LOG(ERROR) << "Rejecting public key chain for domain " << domain
849                << ". Validated chain: " << HashesToBase64String(hashes)
850                << ", matches one or more bad hashes: "
851                << HashesToBase64String(bad_static_spki_hashes);
852     return false;
853   }
854
855   // If there are no pins, then any valid chain is acceptable.
856   if (dynamic_spki_hashes.empty() && static_spki_hashes.empty())
857     return true;
858
859   if (HashesIntersect(dynamic_spki_hashes, hashes) ||
860       HashesIntersect(static_spki_hashes, hashes)) {
861     return true;
862   }
863
864   LOG(ERROR) << "Rejecting public key chain for domain " << domain
865              << ". Validated chain: " << HashesToBase64String(hashes)
866              << ", expected: " << HashesToBase64String(dynamic_spki_hashes)
867              << " or: " << HashesToBase64String(static_spki_hashes);
868   return false;
869 }
870
871 bool TransportSecurityState::DomainState::ShouldUpgradeToSSL() const {
872   return upgrade_mode == MODE_FORCE_HTTPS;
873 }
874
875 bool TransportSecurityState::DomainState::ShouldSSLErrorsBeFatal() const {
876   return true;
877 }
878
879 bool TransportSecurityState::DomainState::HasPublicKeyPins() const {
880   return static_spki_hashes.size() > 0 ||
881          bad_static_spki_hashes.size() > 0 ||
882          dynamic_spki_hashes.size() > 0;
883 }
884
885 }  // namespace