Make USB permissions work in the new permission message system
[chromium-blink-merge.git] / net / http / http_security_headers.cc
blob597adaa96bf8734f190a9cae144355b0eaa7172a
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-sha1")) {
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,
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 "pin-sha256")) {
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,
169 &pins)) {
170 return false;
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()),
180 "report-uri")) {
181 // report-uris are always quoted.
182 if (!name_value_pairs.value_is_quoted())
183 return false;
185 parsed_report_uri = GURL(name_value_pairs.value());
186 if (parsed_report_uri.is_empty() || !parsed_report_uri.is_valid())
187 return false;
188 } else {
189 // Silently ignore unknown directives for forward compatibility.
193 if (!name_value_pairs.valid())
194 return false;
196 if (!parsed_max_age && require_max_age)
197 return false;
199 *max_age = base::TimeDelta::FromSeconds(max_age_candidate);
200 *include_subdomains = include_subdomains_candidate;
201 hashes->swap(pins);
202 *report_uri = parsed_report_uri;
204 return true;
207 } // namespace
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;
246 enum ParserState {
247 START,
248 AFTER_MAX_AGE_LABEL,
249 AFTER_MAX_AGE_EQUALS,
250 AFTER_MAX_AGE,
251 AFTER_INCLUDE_SUBDOMAINS,
252 AFTER_UNKNOWN_LABEL,
253 DIRECTIVE_END
254 } state = START;
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);
262 switch (state) {
263 case START:
264 case DIRECTIVE_END:
265 if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
266 continue;
267 if (base::LowerCaseEqualsASCII(tokenizer.token(), "max-age")) {
268 state = AFTER_MAX_AGE_LABEL;
269 max_age_observed++;
270 } else if (base::LowerCaseEqualsASCII(tokenizer.token(),
271 "includesubdomains")) {
272 state = AFTER_INCLUDE_SUBDOMAINS;
273 include_subdomains_observed++;
274 include_subdomains_candidate = true;
275 } else {
276 state = AFTER_UNKNOWN_LABEL;
278 break;
280 case AFTER_MAX_AGE_LABEL:
281 if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
282 continue;
283 if (*tokenizer.token_begin() != '=')
284 return false;
285 DCHECK_EQ(tokenizer.token().length(), 1U);
286 state = AFTER_MAX_AGE_EQUALS;
287 break;
289 case AFTER_MAX_AGE_EQUALS:
290 if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
291 continue;
292 unquoted = HttpUtil::Unquote(tokenizer.token());
293 if (!MaxAgeToInt(unquoted.begin(), unquoted.end(), &max_age_candidate))
294 return false;
295 state = AFTER_MAX_AGE;
296 break;
298 case AFTER_MAX_AGE:
299 case AFTER_INCLUDE_SUBDOMAINS:
300 if (base::IsAsciiWhitespace(*tokenizer.token_begin()))
301 continue;
302 else if (*tokenizer.token_begin() == ';')
303 state = DIRECTIVE_END;
304 else
305 return false;
306 break;
308 case AFTER_UNKNOWN_LABEL:
309 // Consume and ignore the post-label contents (if any).
310 if (*tokenizer.token_begin() != ';')
311 continue;
312 state = DIRECTIVE_END;
313 break;
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)) {
320 return false;
323 switch (state) {
324 case DIRECTIVE_END:
325 case AFTER_MAX_AGE:
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;
330 return true;
331 case START:
332 case AFTER_MAX_AGE_LABEL:
333 case AFTER_MAX_AGE_EQUALS:
334 return false;
335 default:
336 NOTREACHED();
337 return false;
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,
351 GURL* report_uri) {
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)) {
360 return false;
363 if (!IsPinListValid(candidate_hashes, chain_hashes))
364 return false;
366 *max_age = candidate_max_age;
367 *include_subdomains = candidate_include_subdomains;
368 hashes->swap(candidate_hashes);
369 *report_uri = candidate_report_uri;
370 return true;
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,
381 GURL* report_uri) {
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);
388 } // namespace net