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_SHA256
,
161 } else if (base::LowerCaseEqualsASCII(
162 base::StringPiece(name_value_pairs
.name_begin(),
163 name_value_pairs
.name_end()),
164 "includesubdomains")) {
165 include_subdomains_candidate
= true;
166 } else if (base::LowerCaseEqualsASCII(
167 base::StringPiece(name_value_pairs
.name_begin(),
168 name_value_pairs
.name_end()),
170 // report-uris are always quoted.
171 if (!name_value_pairs
.value_is_quoted())
174 parsed_report_uri
= GURL(name_value_pairs
.value());
175 if (parsed_report_uri
.is_empty() || !parsed_report_uri
.is_valid())
178 // Silently ignore unknown directives for forward compatibility.
182 if (!name_value_pairs
.valid())
185 if (!parsed_max_age
&& require_max_age
)
188 *max_age
= base::TimeDelta::FromSeconds(max_age_candidate
);
189 *include_subdomains
= include_subdomains_candidate
;
191 *report_uri
= parsed_report_uri
;
198 // Parse the Strict-Transport-Security header, as currently defined in
199 // http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-14:
201 // Strict-Transport-Security = "Strict-Transport-Security" ":"
202 // [ directive ] *( ";" [ directive ] )
204 // directive = directive-name [ "=" directive-value ]
205 // directive-name = token
206 // directive-value = token | quoted-string
208 // 1. The order of appearance of directives is not significant.
210 // 2. All directives MUST appear only once in an STS header field.
211 // Directives are either optional or required, as stipulated in
212 // their definitions.
214 // 3. Directive names are case-insensitive.
216 // 4. UAs MUST ignore any STS header fields containing directives, or
217 // other header field value data, that does not conform to the
218 // syntax defined in this specification.
220 // 5. If an STS header field contains directive(s) not recognized by
221 // the UA, the UA MUST ignore the unrecognized directives and if the
222 // STS header field otherwise satisfies the above requirements (1
223 // through 4), the UA MUST process the recognized directives.
224 bool ParseHSTSHeader(const std::string
& value
,
225 base::TimeDelta
* max_age
,
226 bool* include_subdomains
) {
227 uint32 max_age_candidate
= 0;
228 bool include_subdomains_candidate
= false;
230 // We must see max-age exactly once.
231 int max_age_observed
= 0;
232 // We must see includeSubdomains exactly 0 or 1 times.
233 int include_subdomains_observed
= 0;
238 AFTER_MAX_AGE_EQUALS
,
240 AFTER_INCLUDE_SUBDOMAINS
,
245 base::StringTokenizer
tokenizer(value
, " \t=;");
246 tokenizer
.set_options(base::StringTokenizer::RETURN_DELIMS
);
247 tokenizer
.set_quote_chars("\"");
248 std::string unquoted
;
249 while (tokenizer
.GetNext()) {
250 DCHECK(!tokenizer
.token_is_delim() || tokenizer
.token().length() == 1);
254 if (base::IsAsciiWhitespace(*tokenizer
.token_begin()))
256 if (base::LowerCaseEqualsASCII(tokenizer
.token(), "max-age")) {
257 state
= AFTER_MAX_AGE_LABEL
;
259 } else if (base::LowerCaseEqualsASCII(tokenizer
.token(),
260 "includesubdomains")) {
261 state
= AFTER_INCLUDE_SUBDOMAINS
;
262 include_subdomains_observed
++;
263 include_subdomains_candidate
= true;
265 state
= AFTER_UNKNOWN_LABEL
;
269 case AFTER_MAX_AGE_LABEL
:
270 if (base::IsAsciiWhitespace(*tokenizer
.token_begin()))
272 if (*tokenizer
.token_begin() != '=')
274 DCHECK_EQ(tokenizer
.token().length(), 1U);
275 state
= AFTER_MAX_AGE_EQUALS
;
278 case AFTER_MAX_AGE_EQUALS
:
279 if (base::IsAsciiWhitespace(*tokenizer
.token_begin()))
281 unquoted
= HttpUtil::Unquote(tokenizer
.token());
282 if (!MaxAgeToInt(unquoted
.begin(), unquoted
.end(), &max_age_candidate
))
284 state
= AFTER_MAX_AGE
;
288 case AFTER_INCLUDE_SUBDOMAINS
:
289 if (base::IsAsciiWhitespace(*tokenizer
.token_begin()))
291 else if (*tokenizer
.token_begin() == ';')
292 state
= DIRECTIVE_END
;
297 case AFTER_UNKNOWN_LABEL
:
298 // Consume and ignore the post-label contents (if any).
299 if (*tokenizer
.token_begin() != ';')
301 state
= DIRECTIVE_END
;
306 // We've consumed all the input. Let's see what state we ended up in.
307 if (max_age_observed
!= 1 ||
308 (include_subdomains_observed
!= 0 && include_subdomains_observed
!= 1)) {
315 case AFTER_INCLUDE_SUBDOMAINS
:
316 case AFTER_UNKNOWN_LABEL
:
317 *max_age
= base::TimeDelta::FromSeconds(max_age_candidate
);
318 *include_subdomains
= include_subdomains_candidate
;
321 case AFTER_MAX_AGE_LABEL
:
322 case AFTER_MAX_AGE_EQUALS
:
330 // "Public-Key-Pins" ":"
331 // "max-age" "=" delta-seconds ";"
332 // "pin-" algo "=" base64 [ ";" ... ]
333 // [ ";" "includeSubdomains" ]
334 // [ ";" "report-uri" "=" uri-reference ]
335 bool ParseHPKPHeader(const std::string
& value
,
336 const HashValueVector
& chain_hashes
,
337 base::TimeDelta
* max_age
,
338 bool* include_subdomains
,
339 HashValueVector
* hashes
,
341 base::TimeDelta candidate_max_age
;
342 bool candidate_include_subdomains
;
343 HashValueVector candidate_hashes
;
344 GURL candidate_report_uri
;
346 if (!ParseHPKPHeaderImpl(value
, REQUIRE_MAX_AGE
, &candidate_max_age
,
347 &candidate_include_subdomains
, &candidate_hashes
,
348 &candidate_report_uri
)) {
352 if (!IsPinListValid(candidate_hashes
, chain_hashes
))
355 *max_age
= candidate_max_age
;
356 *include_subdomains
= candidate_include_subdomains
;
357 hashes
->swap(candidate_hashes
);
358 *report_uri
= candidate_report_uri
;
362 // "Public-Key-Pins-Report-Only" ":"
363 // [ "max-age" "=" delta-seconds ";" ]
364 // "pin-" algo "=" base64 [ ";" ... ]
365 // [ ";" "includeSubdomains" ]
366 // [ ";" "report-uri" "=" uri-reference ]
367 bool ParseHPKPReportOnlyHeader(const std::string
& value
,
368 bool* include_subdomains
,
369 HashValueVector
* hashes
,
371 // max-age is irrelevant for Report-Only headers.
372 base::TimeDelta unused_max_age
;
373 return ParseHPKPHeaderImpl(value
, DO_NOT_REQUIRE_MAX_AGE
, &unused_max_age
,
374 include_subdomains
, hashes
, report_uri
);