Update V8 to version 4.7.53.
[chromium-blink-merge.git] / net / http / http_security_headers.cc
blobb99b206c3f3214e9e9df5307ce14460565beba7a
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"
13 #include "url/gurl.h"
15 namespace net {
17 namespace {
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,
29 uint32* result) {
30 const base::StringPiece s(begin, end);
31 if (s.empty())
32 return false;
34 int64 i = 0;
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)
45 return false;
46 if (i < 0)
47 return false;
48 if (i > kMaxHSTSAgeSecs)
49 i = kMaxHSTSAgeSecs;
50 *result = (uint32)i;
51 return true;
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();
59 ++i) {
60 HashValueVector::const_iterator j =
61 std::find_if(from_cert_chain.begin(), from_cert_chain.end(),
62 HashValuesEqual(*i));
63 if (j == from_cert_chain.end())
64 return true;
67 return false;
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));
77 if (j != b.end())
78 return true;
80 return false;
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.)
92 if (pins.size() < 2)
93 return false;
95 if (from_cert_chain.empty())
96 return false;
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,
104 HashValueTag tag,
105 HashValueVector* hashes) {
106 const base::StringPiece value(begin, end);
107 if (value.empty())
108 return false;
110 std::string decoded;
111 if (!base::Base64Decode(value, &decoded))
112 return false;
114 HashValue hash(tag);
115 if (decoded.size() != hash.size())
116 return false;
118 memcpy(hash.data(), decoded.data(), hash.size());
119 hashes->push_back(hash);
120 return true;
123 bool ParseHPKPHeaderImpl(const std::string& value,
124 MaxAgeParsing max_age_status,
125 base::TimeDelta* max_age,
126 bool* include_subdomains,
127 HashValueVector* hashes,
128 GURL* report_uri) {
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()),
144 "max-age")) {
145 if (!MaxAgeToInt(name_value_pairs.value_begin(),
146 name_value_pairs.value_end(), &max_age_candidate)) {
147 return false;
149 parsed_max_age = true;
150 } else if (base::LowerCaseEqualsASCII(
151 base::StringPiece(name_value_pairs.name_begin(),
152 name_value_pairs.name_end()),
153 "pin-sha256")) {
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,
158 &pins)) {
159 return false;
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()),
169 "report-uri")) {
170 // report-uris are always quoted.
171 if (!name_value_pairs.value_is_quoted())
172 return false;
174 parsed_report_uri = GURL(name_value_pairs.value());
175 if (parsed_report_uri.is_empty() || !parsed_report_uri.is_valid())
176 return false;
177 } else {
178 // Silently ignore unknown directives for forward compatibility.
182 if (!name_value_pairs.valid())
183 return false;
185 if (!parsed_max_age && require_max_age)
186 return false;
188 *max_age = base::TimeDelta::FromSeconds(max_age_candidate);
189 *include_subdomains = include_subdomains_candidate;
190 hashes->swap(pins);
191 *report_uri = parsed_report_uri;
193 return true;
196 } // namespace
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;
235 enum ParserState {
236 START,
237 AFTER_MAX_AGE_LABEL,
238 AFTER_MAX_AGE_EQUALS,
239 AFTER_MAX_AGE,
240 AFTER_INCLUDE_SUBDOMAINS,
241 AFTER_UNKNOWN_LABEL,
242 DIRECTIVE_END
243 } state = START;
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);
251 switch (state) {
252 case START:
253 case DIRECTIVE_END:
254 if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
255 continue;
256 if (base::LowerCaseEqualsASCII(tokenizer.token(), "max-age")) {
257 state = AFTER_MAX_AGE_LABEL;
258 max_age_observed++;
259 } else if (base::LowerCaseEqualsASCII(tokenizer.token(),
260 "includesubdomains")) {
261 state = AFTER_INCLUDE_SUBDOMAINS;
262 include_subdomains_observed++;
263 include_subdomains_candidate = true;
264 } else {
265 state = AFTER_UNKNOWN_LABEL;
267 break;
269 case AFTER_MAX_AGE_LABEL:
270 if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
271 continue;
272 if (*tokenizer.token_begin() != '=')
273 return false;
274 DCHECK_EQ(tokenizer.token().length(), 1U);
275 state = AFTER_MAX_AGE_EQUALS;
276 break;
278 case AFTER_MAX_AGE_EQUALS:
279 if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
280 continue;
281 unquoted = HttpUtil::Unquote(tokenizer.token());
282 if (!MaxAgeToInt(unquoted.begin(), unquoted.end(), &max_age_candidate))
283 return false;
284 state = AFTER_MAX_AGE;
285 break;
287 case AFTER_MAX_AGE:
288 case AFTER_INCLUDE_SUBDOMAINS:
289 if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
290 continue;
291 else if (*tokenizer.token_begin() == ';')
292 state = DIRECTIVE_END;
293 else
294 return false;
295 break;
297 case AFTER_UNKNOWN_LABEL:
298 // Consume and ignore the post-label contents (if any).
299 if (*tokenizer.token_begin() != ';')
300 continue;
301 state = DIRECTIVE_END;
302 break;
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)) {
309 return false;
312 switch (state) {
313 case DIRECTIVE_END:
314 case AFTER_MAX_AGE:
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;
319 return true;
320 case START:
321 case AFTER_MAX_AGE_LABEL:
322 case AFTER_MAX_AGE_EQUALS:
323 return false;
324 default:
325 NOTREACHED();
326 return false;
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,
340 GURL* report_uri) {
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)) {
349 return false;
352 if (!IsPinListValid(candidate_hashes, chain_hashes))
353 return false;
355 *max_age = candidate_max_age;
356 *include_subdomains = candidate_include_subdomains;
357 hashes->swap(candidate_hashes);
358 *report_uri = candidate_report_uri;
359 return true;
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,
370 GURL* report_uri) {
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);
377 } // namespace net