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_piece.h"
9 #include "base/strings/string_tokenizer.h"
10 #include "base/strings/string_util.h"
11 #include "net/http/http_security_headers.h"
12 #include "net/http/http_util.h"
19 enum MaxAgeParsing
{ REQUIRE_MAX_AGE
, DO_NOT_REQUIRE_MAX_AGE
};
21 static_assert(kMaxHSTSAgeSecs
<= kuint32max
, "kMaxHSTSAgeSecs too large");
23 // MaxAgeToInt converts a string representation of a "whole number" of
24 // seconds into a uint32. The string may contain an arbitrarily large number,
25 // which will be clipped to kMaxHSTSAgeSecs and which is guaranteed to fit
26 // within a 32-bit unsigned integer. False is returned on any parse error.
27 bool MaxAgeToInt(std::string::const_iterator begin
,
28 std::string::const_iterator end
,
30 const base::StringPiece
s(begin
, end
);
36 // Return false on any StringToInt64 parse errors *except* for
37 // int64 overflow. StringToInt64 is used, rather than StringToUint64,
38 // in order to properly handle and reject negative numbers
39 // (StringToUint64 does not return false on negative numbers).
40 // For values too large to be stored in an int64, StringToInt64 will
41 // return false with i set to kint64max, so this case is detected
42 // by the immediately following if-statement and allowed to fall
43 // through so that i gets clipped to kMaxHSTSAgeSecs.
44 if (!base::StringToInt64(s
, &i
) && i
!= kint64max
)
48 if (i
> kMaxHSTSAgeSecs
)
54 // Returns true iff there is an item in |pins| which is not present in
55 // |from_cert_chain|. Such an SPKI hash is called a "backup pin".
56 bool IsBackupPinPresent(const HashValueVector
& pins
,
57 const HashValueVector
& from_cert_chain
) {
58 for (HashValueVector::const_iterator i
= pins
.begin(); i
!= pins
.end();
60 HashValueVector::const_iterator j
=
61 std::find_if(from_cert_chain
.begin(), from_cert_chain
.end(),
63 if (j
== from_cert_chain
.end())
70 // Returns true if the intersection of |a| and |b| is not empty. If either
71 // |a| or |b| is empty, returns false.
72 bool HashesIntersect(const HashValueVector
& a
,
73 const HashValueVector
& b
) {
74 for (HashValueVector::const_iterator i
= a
.begin(); i
!= a
.end(); ++i
) {
75 HashValueVector::const_iterator j
=
76 std::find_if(b
.begin(), b
.end(), HashValuesEqual(*i
));
83 // Returns true iff |pins| contains both a live and a backup pin. A live pin
84 // is a pin whose SPKI is present in the certificate chain in |ssl_info|. A
85 // backup pin is a pin intended for disaster recovery, not day-to-day use, and
86 // thus must be absent from the certificate chain. The Public-Key-Pins header
87 // specification requires both.
88 bool IsPinListValid(const HashValueVector
& pins
,
89 const HashValueVector
& from_cert_chain
) {
90 // Fast fail: 1 live + 1 backup = at least 2 pins. (Check for actual
91 // liveness and backupness below.)
95 if (from_cert_chain
.empty())
98 return IsBackupPinPresent(pins
, from_cert_chain
) &&
99 HashesIntersect(pins
, from_cert_chain
);
102 bool ParseAndAppendPin(std::string::const_iterator begin
,
103 std::string::const_iterator end
,
105 HashValueVector
* hashes
) {
106 const base::StringPiece
value(begin
, end
);
111 if (!base::Base64Decode(value
, &decoded
))
115 if (decoded
.size() != hash
.size())
118 memcpy(hash
.data(), decoded
.data(), hash
.size());
119 hashes
->push_back(hash
);
123 bool ParseHPKPHeaderImpl(const std::string
& value
,
124 MaxAgeParsing max_age_status
,
125 base::TimeDelta
* max_age
,
126 bool* include_subdomains
,
127 HashValueVector
* hashes
,
129 bool parsed_max_age
= false;
130 bool include_subdomains_candidate
= false;
131 uint32 max_age_candidate
= 0;
132 GURL parsed_report_uri
;
133 HashValueVector pins
;
134 bool require_max_age
= max_age_status
== REQUIRE_MAX_AGE
;
136 HttpUtil::NameValuePairsIterator
name_value_pairs(
137 value
.begin(), value
.end(), ';',
138 HttpUtil::NameValuePairsIterator::VALUES_OPTIONAL
);
140 while (name_value_pairs
.GetNext()) {
141 if (base::LowerCaseEqualsASCII(
142 base::StringPiece(name_value_pairs
.name_begin(),
143 name_value_pairs
.name_end()),
145 if (!MaxAgeToInt(name_value_pairs
.value_begin(),
146 name_value_pairs
.value_end(), &max_age_candidate
)) {
149 parsed_max_age
= true;
150 } else if (base::LowerCaseEqualsASCII(
151 base::StringPiece(name_value_pairs
.name_begin(),
152 name_value_pairs
.name_end()),
154 // Pins are always quoted.
155 if (!name_value_pairs
.value_is_quoted() ||
156 !ParseAndAppendPin(name_value_pairs
.value_begin(),
157 name_value_pairs
.value_end(), HASH_VALUE_SHA1
,
161 } else if (base::LowerCaseEqualsASCII(
162 base::StringPiece(name_value_pairs
.name_begin(),
163 name_value_pairs
.name_end()),
165 // Pins are always quoted.
166 if (!name_value_pairs
.value_is_quoted() ||
167 !ParseAndAppendPin(name_value_pairs
.value_begin(),
168 name_value_pairs
.value_end(), HASH_VALUE_SHA256
,
172 } else if (base::LowerCaseEqualsASCII(
173 base::StringPiece(name_value_pairs
.name_begin(),
174 name_value_pairs
.name_end()),
175 "includesubdomains")) {
176 include_subdomains_candidate
= true;
177 } else if (base::LowerCaseEqualsASCII(
178 base::StringPiece(name_value_pairs
.name_begin(),
179 name_value_pairs
.name_end()),
181 // report-uris are always quoted.
182 if (!name_value_pairs
.value_is_quoted())
185 parsed_report_uri
= GURL(name_value_pairs
.value());
186 if (parsed_report_uri
.is_empty() || !parsed_report_uri
.is_valid())
189 // Silently ignore unknown directives for forward compatibility.
193 if (!name_value_pairs
.valid())
196 if (!parsed_max_age
&& require_max_age
)
199 *max_age
= base::TimeDelta::FromSeconds(max_age_candidate
);
200 *include_subdomains
= include_subdomains_candidate
;
202 *report_uri
= parsed_report_uri
;
209 // Parse the Strict-Transport-Security header, as currently defined in
210 // http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14:
212 // Strict-Transport-Security = "Strict-Transport-Security" ":"
213 // [ directive ] *( ";" [ directive ] )
215 // directive = directive-name [ "=" directive-value ]
216 // directive-name = token
217 // directive-value = token | quoted-string
219 // 1. The order of appearance of directives is not significant.
221 // 2. All directives MUST appear only once in an STS header field.
222 // Directives are either optional or required, as stipulated in
223 // their definitions.
225 // 3. Directive names are case-insensitive.
227 // 4. UAs MUST ignore any STS header fields containing directives, or
228 // other header field value data, that does not conform to the
229 // syntax defined in this specification.
231 // 5. If an STS header field contains directive(s) not recognized by
232 // the UA, the UA MUST ignore the unrecognized directives and if the
233 // STS header field otherwise satisfies the above requirements (1
234 // through 4), the UA MUST process the recognized directives.
235 bool ParseHSTSHeader(const std::string
& value
,
236 base::TimeDelta
* max_age
,
237 bool* include_subdomains
) {
238 uint32 max_age_candidate
= 0;
239 bool include_subdomains_candidate
= false;
241 // We must see max-age exactly once.
242 int max_age_observed
= 0;
243 // We must see includeSubdomains exactly 0 or 1 times.
244 int include_subdomains_observed
= 0;
249 AFTER_MAX_AGE_EQUALS
,
251 AFTER_INCLUDE_SUBDOMAINS
,
256 base::StringTokenizer
tokenizer(value
, " \t=;");
257 tokenizer
.set_options(base::StringTokenizer::RETURN_DELIMS
);
258 tokenizer
.set_quote_chars("\"");
259 std::string unquoted
;
260 while (tokenizer
.GetNext()) {
261 DCHECK(!tokenizer
.token_is_delim() || tokenizer
.token().length() == 1);
265 if (base::IsAsciiWhitespace(*tokenizer
.token_begin()))
267 if (base::LowerCaseEqualsASCII(tokenizer
.token(), "max-age")) {
268 state
= AFTER_MAX_AGE_LABEL
;
270 } else if (base::LowerCaseEqualsASCII(tokenizer
.token(),
271 "includesubdomains")) {
272 state
= AFTER_INCLUDE_SUBDOMAINS
;
273 include_subdomains_observed
++;
274 include_subdomains_candidate
= true;
276 state
= AFTER_UNKNOWN_LABEL
;
280 case AFTER_MAX_AGE_LABEL
:
281 if (base::IsAsciiWhitespace(*tokenizer
.token_begin()))
283 if (*tokenizer
.token_begin() != '=')
285 DCHECK_EQ(tokenizer
.token().length(), 1U);
286 state
= AFTER_MAX_AGE_EQUALS
;
289 case AFTER_MAX_AGE_EQUALS
:
290 if (base::IsAsciiWhitespace(*tokenizer
.token_begin()))
292 unquoted
= HttpUtil::Unquote(tokenizer
.token());
293 if (!MaxAgeToInt(unquoted
.begin(), unquoted
.end(), &max_age_candidate
))
295 state
= AFTER_MAX_AGE
;
299 case AFTER_INCLUDE_SUBDOMAINS
:
300 if (base::IsAsciiWhitespace(*tokenizer
.token_begin()))
302 else if (*tokenizer
.token_begin() == ';')
303 state
= DIRECTIVE_END
;
308 case AFTER_UNKNOWN_LABEL
:
309 // Consume and ignore the post-label contents (if any).
310 if (*tokenizer
.token_begin() != ';')
312 state
= DIRECTIVE_END
;
317 // We've consumed all the input. Let's see what state we ended up in.
318 if (max_age_observed
!= 1 ||
319 (include_subdomains_observed
!= 0 && include_subdomains_observed
!= 1)) {
326 case AFTER_INCLUDE_SUBDOMAINS
:
327 case AFTER_UNKNOWN_LABEL
:
328 *max_age
= base::TimeDelta::FromSeconds(max_age_candidate
);
329 *include_subdomains
= include_subdomains_candidate
;
332 case AFTER_MAX_AGE_LABEL
:
333 case AFTER_MAX_AGE_EQUALS
:
341 // "Public-Key-Pins" ":"
342 // "max-age" "=" delta-seconds ";"
343 // "pin-" algo "=" base64 [ ";" ... ]
344 // [ ";" "includeSubdomains" ]
345 // [ ";" "report-uri" "=" uri-reference ]
346 bool ParseHPKPHeader(const std::string
& value
,
347 const HashValueVector
& chain_hashes
,
348 base::TimeDelta
* max_age
,
349 bool* include_subdomains
,
350 HashValueVector
* hashes
,
352 base::TimeDelta candidate_max_age
;
353 bool candidate_include_subdomains
;
354 HashValueVector candidate_hashes
;
355 GURL candidate_report_uri
;
357 if (!ParseHPKPHeaderImpl(value
, REQUIRE_MAX_AGE
, &candidate_max_age
,
358 &candidate_include_subdomains
, &candidate_hashes
,
359 &candidate_report_uri
)) {
363 if (!IsPinListValid(candidate_hashes
, chain_hashes
))
366 *max_age
= candidate_max_age
;
367 *include_subdomains
= candidate_include_subdomains
;
368 hashes
->swap(candidate_hashes
);
369 *report_uri
= candidate_report_uri
;
373 // "Public-Key-Pins-Report-Only" ":"
374 // [ "max-age" "=" delta-seconds ";" ]
375 // "pin-" algo "=" base64 [ ";" ... ]
376 // [ ";" "includeSubdomains" ]
377 // [ ";" "report-uri" "=" uri-reference ]
378 bool ParseHPKPReportOnlyHeader(const std::string
& value
,
379 bool* include_subdomains
,
380 HashValueVector
* hashes
,
382 // max-age is irrelevant for Report-Only headers.
383 base::TimeDelta unused_max_age
;
384 return ParseHPKPHeaderImpl(value
, DO_NOT_REQUIRE_MAX_AGE
, &unused_max_age
,
385 include_subdomains
, hashes
, report_uri
);