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.
5 #include "base/base64.h"
6 #include "base/basictypes.h"
7 #include "base/strings/string_number_conversions.h"
8 #include "base/strings/string_tokenizer.h"
9 #include "base/strings/string_util.h"
10 #include "net/http/http_security_headers.h"
11 #include "net/http/http_util.h"
17 static_assert(kMaxHSTSAgeSecs
<= kuint32max
, "kMaxHSTSAgeSecs too large");
19 // MaxAgeToInt converts a string representation of a "whole number" of
20 // seconds into a uint32. The string may contain an arbitrarily large number,
21 // which will be clipped to kMaxHSTSAgeSecs and which is guaranteed to fit
22 // within a 32-bit unsigned integer. False is returned on any parse error.
23 bool MaxAgeToInt(std::string::const_iterator begin
,
24 std::string::const_iterator end
,
26 const std::string
s(begin
, end
);
29 // Return false on any StringToInt64 parse errors *except* for
30 // int64 overflow. StringToInt64 is used, rather than StringToUint64,
31 // in order to properly handle and reject negative numbers
32 // (StringToUint64 does not return false on negative numbers).
33 // For values too large to be stored in an int64, StringToInt64 will
34 // return false with i set to kint64max, so this case is detected
35 // by the immediately following if-statement and allowed to fall
36 // through so that i gets clipped to kMaxHSTSAgeSecs.
37 if (!base::StringToInt64(s
, &i
) && i
!= kint64max
)
41 if (i
> kMaxHSTSAgeSecs
)
47 // Returns true iff there is an item in |pins| which is not present in
48 // |from_cert_chain|. Such an SPKI hash is called a "backup pin".
49 bool IsBackupPinPresent(const HashValueVector
& pins
,
50 const HashValueVector
& from_cert_chain
) {
51 for (HashValueVector::const_iterator i
= pins
.begin(); i
!= pins
.end();
53 HashValueVector::const_iterator j
=
54 std::find_if(from_cert_chain
.begin(), from_cert_chain
.end(),
56 if (j
== from_cert_chain
.end())
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
));
76 // Returns true iff |pins| contains both a live and a backup pin. A live pin
77 // is a pin whose SPKI is present in the certificate chain in |ssl_info|. A
78 // backup pin is a pin intended for disaster recovery, not day-to-day use, and
79 // thus must be absent from the certificate chain. The Public-Key-Pins header
80 // specification requires both.
81 bool IsPinListValid(const HashValueVector
& pins
,
82 const HashValueVector
& from_cert_chain
) {
83 // Fast fail: 1 live + 1 backup = at least 2 pins. (Check for actual
84 // liveness and backupness below.)
88 if (from_cert_chain
.empty())
91 return IsBackupPinPresent(pins
, from_cert_chain
) &&
92 HashesIntersect(pins
, from_cert_chain
);
95 std::string
Strip(const std::string
& source
) {
99 std::string::const_iterator start
= source
.begin();
100 std::string::const_iterator end
= source
.end();
101 HttpUtil::TrimLWS(&start
, &end
);
102 return std::string(start
, end
);
105 typedef std::pair
<std::string
, std::string
> StringPair
;
107 StringPair
Split(const std::string
& source
, char delimiter
) {
109 size_t point
= source
.find(delimiter
);
111 pair
.first
= source
.substr(0, point
);
112 if (std::string::npos
!= point
)
113 pair
.second
= source
.substr(point
+ 1);
118 bool ParseAndAppendPin(const std::string
& value
,
120 HashValueVector
* hashes
) {
121 // Pins are always quoted.
122 if (value
.empty() || !HttpUtil::IsQuote(value
[0]))
125 std::string unquoted
= HttpUtil::Unquote(value
);
126 if (unquoted
.empty())
130 if (!base::Base64Decode(unquoted
, &decoded
))
134 if (decoded
.size() != hash
.size())
137 memcpy(hash
.data(), decoded
.data(), hash
.size());
138 hashes
->push_back(hash
);
144 // Parse the Strict-Transport-Security header, as currently defined in
145 // http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14:
147 // Strict-Transport-Security = "Strict-Transport-Security" ":"
148 // [ directive ] *( ";" [ directive ] )
150 // directive = directive-name [ "=" directive-value ]
151 // directive-name = token
152 // directive-value = token | quoted-string
154 // 1. The order of appearance of directives is not significant.
156 // 2. All directives MUST appear only once in an STS header field.
157 // Directives are either optional or required, as stipulated in
158 // their definitions.
160 // 3. Directive names are case-insensitive.
162 // 4. UAs MUST ignore any STS header fields containing directives, or
163 // other header field value data, that does not conform to the
164 // syntax defined in this specification.
166 // 5. If an STS header field contains directive(s) not recognized by
167 // the UA, the UA MUST ignore the unrecognized directives and if the
168 // STS header field otherwise satisfies the above requirements (1
169 // through 4), the UA MUST process the recognized directives.
170 bool ParseHSTSHeader(const std::string
& value
,
171 base::TimeDelta
* max_age
,
172 bool* include_subdomains
) {
173 uint32 max_age_candidate
= 0;
174 bool include_subdomains_candidate
= false;
176 // We must see max-age exactly once.
177 int max_age_observed
= 0;
178 // We must see includeSubdomains exactly 0 or 1 times.
179 int include_subdomains_observed
= 0;
184 AFTER_MAX_AGE_EQUALS
,
186 AFTER_INCLUDE_SUBDOMAINS
,
191 base::StringTokenizer
tokenizer(value
, " \t=;");
192 tokenizer
.set_options(base::StringTokenizer::RETURN_DELIMS
);
193 tokenizer
.set_quote_chars("\"");
194 std::string unquoted
;
195 while (tokenizer
.GetNext()) {
196 DCHECK(!tokenizer
.token_is_delim() || tokenizer
.token().length() == 1);
200 if (IsAsciiWhitespace(*tokenizer
.token_begin()))
202 if (LowerCaseEqualsASCII(tokenizer
.token(), "max-age")) {
203 state
= AFTER_MAX_AGE_LABEL
;
205 } else if (LowerCaseEqualsASCII(tokenizer
.token(),
206 "includesubdomains")) {
207 state
= AFTER_INCLUDE_SUBDOMAINS
;
208 include_subdomains_observed
++;
209 include_subdomains_candidate
= true;
211 state
= AFTER_UNKNOWN_LABEL
;
215 case AFTER_MAX_AGE_LABEL
:
216 if (IsAsciiWhitespace(*tokenizer
.token_begin()))
218 if (*tokenizer
.token_begin() != '=')
220 DCHECK_EQ(tokenizer
.token().length(), 1U);
221 state
= AFTER_MAX_AGE_EQUALS
;
224 case AFTER_MAX_AGE_EQUALS
:
225 if (IsAsciiWhitespace(*tokenizer
.token_begin()))
227 unquoted
= HttpUtil::Unquote(tokenizer
.token());
228 if (!MaxAgeToInt(unquoted
.begin(), unquoted
.end(), &max_age_candidate
))
230 state
= AFTER_MAX_AGE
;
234 case AFTER_INCLUDE_SUBDOMAINS
:
235 if (IsAsciiWhitespace(*tokenizer
.token_begin()))
237 else if (*tokenizer
.token_begin() == ';')
238 state
= DIRECTIVE_END
;
243 case AFTER_UNKNOWN_LABEL
:
244 // Consume and ignore the post-label contents (if any).
245 if (*tokenizer
.token_begin() != ';')
247 state
= DIRECTIVE_END
;
252 // We've consumed all the input. Let's see what state we ended up in.
253 if (max_age_observed
!= 1 ||
254 (include_subdomains_observed
!= 0 && include_subdomains_observed
!= 1)) {
261 case AFTER_INCLUDE_SUBDOMAINS
:
262 case AFTER_UNKNOWN_LABEL
:
263 *max_age
= base::TimeDelta::FromSeconds(max_age_candidate
);
264 *include_subdomains
= include_subdomains_candidate
;
267 case AFTER_MAX_AGE_LABEL
:
268 case AFTER_MAX_AGE_EQUALS
:
276 // "Public-Key-Pins" ":"
277 // "max-age" "=" delta-seconds ";"
278 // "pin-" algo "=" base64 [ ";" ... ]
279 bool ParseHPKPHeader(const std::string
& value
,
280 const HashValueVector
& chain_hashes
,
281 base::TimeDelta
* max_age
,
282 bool* include_subdomains
,
283 HashValueVector
* hashes
) {
284 bool parsed_max_age
= false;
285 bool include_subdomains_candidate
= false;
286 uint32 max_age_candidate
= 0;
287 HashValueVector pins
;
289 std::string source
= value
;
291 while (!source
.empty()) {
292 StringPair semicolon
= Split(source
, ';');
293 semicolon
.first
= Strip(semicolon
.first
);
294 semicolon
.second
= Strip(semicolon
.second
);
295 StringPair equals
= Split(semicolon
.first
, '=');
296 equals
.first
= Strip(equals
.first
);
297 equals
.second
= Strip(equals
.second
);
299 if (LowerCaseEqualsASCII(equals
.first
, "max-age")) {
300 if (equals
.second
.empty() ||
301 !MaxAgeToInt(equals
.second
.begin(), equals
.second
.end(),
302 &max_age_candidate
)) {
305 parsed_max_age
= true;
306 } else if (LowerCaseEqualsASCII(equals
.first
, "pin-sha1")) {
307 if (!ParseAndAppendPin(equals
.second
, HASH_VALUE_SHA1
, &pins
))
309 } else if (LowerCaseEqualsASCII(equals
.first
, "pin-sha256")) {
310 if (!ParseAndAppendPin(equals
.second
, HASH_VALUE_SHA256
, &pins
))
312 } else if (LowerCaseEqualsASCII(equals
.first
, "includesubdomains")) {
313 include_subdomains_candidate
= true;
315 // Silently ignore unknown directives for forward compatibility.
318 source
= semicolon
.second
;
324 if (!IsPinListValid(pins
, chain_hashes
))
327 *max_age
= base::TimeDelta::FromSeconds(max_age_candidate
);
328 *include_subdomains
= include_subdomains_candidate
;