transport_security_state.h revision a1401311d1ab56c4ed0a474bd38c108f75cb0cd9
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#ifndef NET_HTTP_TRANSPORT_SECURITY_STATE_H_
6#define NET_HTTP_TRANSPORT_SECURITY_STATE_H_
7
8#include <map>
9#include <string>
10#include <utility>
11#include <vector>
12
13#include "base/basictypes.h"
14#include "base/gtest_prod_util.h"
15#include "base/threading/non_thread_safe.h"
16#include "base/time/time.h"
17#include "net/base/net_export.h"
18#include "net/cert/x509_cert_types.h"
19#include "net/cert/x509_certificate.h"
20
21namespace net {
22
23class SSLInfo;
24
25// Tracks which hosts have enabled strict transport security and/or public
26// key pins.
27//
28// This object manages the in-memory store. Register a Delegate with
29// |SetDelegate| to persist the state to disk.
30//
31// HTTP strict transport security (HSTS) is defined in
32// http://tools.ietf.org/html/ietf-websec-strict-transport-sec, and
33// HTTP-based dynamic public key pinning (HPKP) is defined in
34// http://tools.ietf.org/html/ietf-websec-key-pinning.
35class NET_EXPORT TransportSecurityState
36    : NON_EXPORTED_BASE(public base::NonThreadSafe) {
37 public:
38  class NET_EXPORT Delegate {
39   public:
40    // This function may not block and may be called with internal locks held.
41    // Thus it must not reenter the TransportSecurityState object.
42    virtual void StateIsDirty(TransportSecurityState* state) = 0;
43
44   protected:
45    virtual ~Delegate() {}
46  };
47
48  TransportSecurityState();
49  ~TransportSecurityState();
50
51  // A DomainState describes the transport security state (required upgrade
52  // to HTTPS, and/or any public key pins).
53  class NET_EXPORT DomainState {
54   public:
55    enum UpgradeMode {
56      // These numbers must match those in hsts_view.js, function modeToString.
57      MODE_FORCE_HTTPS = 0,
58      MODE_DEFAULT = 1,
59    };
60
61    DomainState();
62    ~DomainState();
63
64    // Takes a set of SubjectPublicKeyInfo |hashes| and returns true if:
65    //   1) |bad_static_spki_hashes| does not intersect |hashes|; AND
66    //   2) Both |static_spki_hashes| and |dynamic_spki_hashes| are empty
67    //      or at least one of them intersects |hashes|.
68    //
69    // |{dynamic,static}_spki_hashes| contain trustworthy public key hashes,
70    // any one of which is sufficient to validate the certificate chain in
71    // question. The public keys could be of a root CA, intermediate CA, or
72    // leaf certificate, depending on the security vs. disaster recovery
73    // tradeoff selected. (Pinning only to leaf certifiates increases
74    // security because you no longer trust any CAs, but it hampers disaster
75    // recovery because you can't just get a new certificate signed by the
76    // CA.)
77    //
78    // |bad_static_spki_hashes| contains public keys that we don't want to
79    // trust.
80    bool CheckPublicKeyPins(const HashValueVector& hashes) const;
81
82    // Returns true if any of the HashValueVectors |static_spki_hashes|,
83    // |bad_static_spki_hashes|, or |dynamic_spki_hashes| contains any
84    // items.
85    bool HasPublicKeyPins() const;
86
87    // ShouldUpgradeToSSL returns true iff, given the |mode| of this
88    // DomainState, HTTP requests should be internally redirected to HTTPS
89    // (also if the "ws" WebSocket request should be upgraded to "wss")
90    bool ShouldUpgradeToSSL() const;
91
92    // ShouldSSLErrorsBeFatal returns true iff HTTPS errors should cause
93    // hard-fail behavior (e.g. if HSTS is set for the domain)
94    bool ShouldSSLErrorsBeFatal() const;
95
96    UpgradeMode upgrade_mode;
97
98    // The absolute time (UTC) when the |upgrade_mode| was observed.
99    //
100    // TODO(palmer): Perhaps static entries should have an "observed" time.
101    base::Time sts_observed;
102
103    // The absolute time (UTC) when the |dynamic_spki_hashes| (and other
104    // |dynamic_*| state) were observed.
105    //
106    // TODO(palmer): Perhaps static entries should have an "observed" time.
107    base::Time pkp_observed;
108
109    // The absolute time (UTC) when the |upgrade_mode|, if set to
110    // UPGRADE_ALWAYS, downgrades to UPGRADE_NEVER.
111    base::Time upgrade_expiry;
112
113    // Are subdomains subject to this DomainState, for the purposes of
114    // upgrading to HTTPS?
115    bool sts_include_subdomains;
116
117    // Are subdomains subject to this DomainState, for the purposes of
118    // Pin Validation?
119    bool pkp_include_subdomains;
120
121    // Optional; hashes of static pinned SubjectPublicKeyInfos. Unless both
122    // are empty, at least one of |static_spki_hashes| and
123    // |dynamic_spki_hashes| MUST intersect with the set of SPKIs in the TLS
124    // server's certificate chain.
125    //
126    // |dynamic_spki_hashes| take precedence over |static_spki_hashes|.
127    // That is, |IsChainOfPublicKeysPermitted| first checks dynamic pins and
128    // then checks static pins.
129    HashValueVector static_spki_hashes;
130
131    // Optional; hashes of dynamically pinned SubjectPublicKeyInfos.
132    HashValueVector dynamic_spki_hashes;
133
134    // The absolute time (UTC) when the |dynamic_spki_hashes| expire.
135    base::Time dynamic_spki_hashes_expiry;
136
137    // Optional; hashes of static known-bad SubjectPublicKeyInfos which
138    // MUST NOT intersect with the set of SPKIs in the TLS server's
139    // certificate chain.
140    HashValueVector bad_static_spki_hashes;
141
142    // The following members are not valid when stored in |enabled_hosts_|:
143
144    // The domain which matched during a search for this DomainState entry.
145    // Updated by |GetDomainState|, |GetDynamicDomainState|, and
146    // |GetStaticDomainState|.
147    std::string domain;
148  };
149
150  class NET_EXPORT Iterator {
151   public:
152    explicit Iterator(const TransportSecurityState& state);
153    ~Iterator();
154
155    bool HasNext() const { return iterator_ != end_; }
156    void Advance() { ++iterator_; }
157    const std::string& hostname() const { return iterator_->first; }
158    const DomainState& domain_state() const { return iterator_->second; }
159
160   private:
161    std::map<std::string, DomainState>::const_iterator iterator_;
162    std::map<std::string, DomainState>::const_iterator end_;
163  };
164
165  // Assign a |Delegate| for persisting the transport security state. If
166  // |NULL|, state will not be persisted. The caller retains
167  // ownership of |delegate|.
168  // Note: This is only used for serializing/deserializing the
169  // TransportSecurityState.
170  void SetDelegate(Delegate* delegate);
171
172  // Clears all dynamic data (e.g. HSTS and HPKP data).
173  //
174  // Does NOT persist changes using the Delegate, as this function is only
175  // used to clear any dynamic data prior to re-loading it from a file.
176  // Note: This is only used for serializing/deserializing the
177  // TransportSecurityState.
178  void ClearDynamicData();
179
180  // Inserts |state| into |enabled_hosts_| under the key |hashed_host|.
181  // |hashed_host| is already in the internal representation
182  // HashHost(CanonicalizeHost(host)).
183  // Note: This is only used for serializing/deserializing the
184  // TransportSecurityState.
185  void AddOrUpdateEnabledHosts(const std::string& hashed_host,
186                               const DomainState& state);
187
188  // Deletes all dynamic data (e.g. HSTS or HPKP data) created since a given
189  // time.
190  //
191  // If any entries are deleted, the new state will be persisted through
192  // the Delegate (if any).
193  void DeleteAllDynamicDataSince(const base::Time& time);
194
195  // Deletes any dynamic data stored for |host| (e.g. HSTS or HPKP data).
196  // If |host| doesn't have an exact entry then no action is taken. Does
197  // not delete static (i.e. preloaded) data.  Returns true iff an entry
198  // was deleted.
199  //
200  // If an entry is deleted, the new state will be persisted through
201  // the Delegate (if any).
202  bool DeleteDynamicDataForHost(const std::string& host);
203
204  // Returns true and updates |*result| iff there is a DomainState for
205  // |host|.
206  //
207  // If |sni_enabled| is true, searches the static pins defined for
208  // SNI-using hosts as well as the rest of the pins.
209  //
210  // If |host| matches both an exact entry and is a subdomain of another
211  // entry, the exact match determines the return value.
212  //
213  // Note that this method is not const because it opportunistically removes
214  // entries that have expired.
215  bool GetDomainState(const std::string& host,
216                      bool sni_enabled,
217                      DomainState* result);
218
219  // Processes an HSTS header value from the host, adding entries to
220  // dynamic state if necessary.
221  bool AddHSTSHeader(const std::string& host, const std::string& value);
222
223  // Processes an HPKP header value from the host, adding entries to
224  // dynamic state if necessary.  ssl_info is used to check that
225  // the specified pins overlap with the certificate chain.
226  bool AddHPKPHeader(const std::string& host, const std::string& value,
227                     const SSLInfo& ssl_info);
228
229  // Adds explicitly-specified data as if it was processed from an
230  // HSTS header (used for net-internals and unit tests).
231  bool AddHSTS(const std::string& host, const base::Time& expiry,
232               bool include_subdomains);
233
234  // Adds explicitly-specified data as if it was processed from an
235  // HPKP header (used for net-internals and unit tests).
236  bool AddHPKP(const std::string& host, const base::Time& expiry,
237               bool include_subdomains, const HashValueVector& hashes);
238
239  // Returns true iff we have any static public key pins for the |host| and
240  // iff its set of required pins is the set we expect for Google
241  // properties.
242  //
243  // If |sni_enabled| is true, searches the static pins defined for
244  // SNI-using hosts as well as the rest of the pins.
245  //
246  // If |host| matches both an exact entry and is a subdomain of another
247  // entry, the exact match determines the return value.
248  static bool IsGooglePinnedProperty(const std::string& host,
249                                     bool sni_enabled);
250
251  // GooglePinsForDebugging returns an array of SHA-1 pins for Google
252  // properties - each 20 bytes long - with a NULL pointer signalling the end
253  // of the array. This is a temporary debugging measure to check for binary
254  // alteration / corruption.
255  static const char* const* GooglePinsForDebugging();
256
257  // The maximum number of seconds for which we'll cache an HSTS request.
258  static const long int kMaxHSTSAgeSecs;
259
260  // Send an UMA report on pin validation failure, if the host is in a
261  // statically-defined list of domains.
262  //
263  // TODO(palmer): This doesn't really belong here, and should be moved into
264  // the exactly one call site. This requires unifying |struct HSTSPreload|
265  // (an implementation detail of this class) with a more generic
266  // representation of first-class DomainStates, and exposing the preloads
267  // to the caller with |GetStaticDomainState|.
268  static void ReportUMAOnPinFailure(const std::string& host);
269
270  // IsBuildTimely returns true if the current build is new enough ensure that
271  // built in security information (i.e. HSTS preloading and pinning
272  // information) is timely.
273  static bool IsBuildTimely();
274
275 private:
276  friend class TransportSecurityStateTest;
277  FRIEND_TEST_ALL_PREFIXES(HttpSecurityHeadersTest,
278                           UpdateDynamicPKPOnly);
279
280  typedef std::map<std::string, DomainState> DomainStateMap;
281
282  // If a Delegate is present, notify it that the internal state has
283  // changed.
284  void DirtyNotify();
285
286  // Enable TransportSecurity for |host|. |state| supercedes any previous
287  // state for the |host|, including static entries.
288  //
289  // The new state for |host| is persisted using the Delegate (if any).
290  void EnableHost(const std::string& host, const DomainState& state);
291
292  // Converts |hostname| from dotted form ("www.google.com") to the form
293  // used in DNS: "\x03www\x06google\x03com", lowercases that, and returns
294  // the result.
295  static std::string CanonicalizeHost(const std::string& hostname);
296
297  // Returns true and updates |*result| iff there is a static DomainState for
298  // |host|.
299  //
300  // |GetStaticDomainState| is identical to |GetDomainState| except that it
301  // searches only the statically-defined transport security state, ignoring
302  // all dynamically-added DomainStates.
303  //
304  // If |sni_enabled| is true, searches the static pins defined for
305  // SNI-using hosts as well as the rest of the pins.
306  //
307  // If |host| matches both an exact entry and is a subdomain of another
308  // entry, the exact match determines the return value.
309  //
310  // Note that this method is not const because it opportunistically removes
311  // entries that have expired.
312  bool GetStaticDomainState(const std::string& host,
313                            bool sni_enabled,
314                            DomainState* result);
315
316  // Returns true and updates |*result| iff there is a dynamic DomainState for
317  // |host|.
318  //
319  // |GetDynamicDomainState| is identical to |GetDomainState| except that it
320  // searches only the dynamically-added transport security state, ignoring
321  // all statically-defined DomainStates.
322  //
323  // If |host| matches both an exact entry and is a subdomain of another
324  // entry, the exact match determines the return value.
325  //
326  // Note that this method is not const because it opportunistically removes
327  // entries that have expired.
328  bool GetDynamicDomainState(const std::string& host, DomainState* result);
329
330  // The set of hosts that have enabled TransportSecurity.
331  DomainStateMap enabled_hosts_;
332
333  Delegate* delegate_;
334
335  DISALLOW_COPY_AND_ASSIGN(TransportSecurityState);
336};
337
338}  // namespace net
339
340#endif  // NET_HTTP_TRANSPORT_SECURITY_STATE_H_
341