1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // Portions of this code based on Mozilla:
6 // (netwerk/cookie/src/nsCookieService.cpp)
7 /* ***** BEGIN LICENSE BLOCK *****
8 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
9 *
10 * The contents of this file are subject to the Mozilla Public License Version
11 * 1.1 (the "License"); you may not use this file except in compliance with
12 * the License. You may obtain a copy of the License at
13 * http://www.mozilla.org/MPL/
14 *
15 * Software distributed under the License is distributed on an "AS IS" basis,
16 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
17 * for the specific language governing rights and limitations under the
18 * License.
19 *
20 * The Original Code is mozilla.org code.
21 *
22 * The Initial Developer of the Original Code is
23 * Netscape Communications Corporation.
24 * Portions created by the Initial Developer are Copyright (C) 2003
25 * the Initial Developer. All Rights Reserved.
26 *
27 * Contributor(s):
28 * Daniel Witte (dwitte@stanford.edu)
29 * Michiel van Leeuwen (mvl@exedo.nl)
30 *
31 * Alternatively, the contents of this file may be used under the terms of
32 * either the GNU General Public License Version 2 or later (the "GPL"), or
33 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
34 * in which case the provisions of the GPL or the LGPL are applicable instead
35 * of those above. If you wish to allow use of your version of this file only
36 * under the terms of either the GPL or the LGPL, and not to allow others to
37 * use your version of this file under the terms of the MPL, indicate your
38 * decision by deleting the provisions above and replace them with the notice
39 * and other provisions required by the GPL or the LGPL. If you do not delete
40 * the provisions above, a recipient may use your version of this file under
41 * the terms of any one of the MPL, the GPL or the LGPL.
42 *
43 * ***** END LICENSE BLOCK ***** */
44
45 #include "net/cookies/parsed_cookie.h"
46
47 #include "base/logging.h"
48 #include "base/metrics/histogram_macros.h"
49 #include "base/numerics/checked_math.h"
50 #include "base/strings/string_util.h"
51 #include "net/base/features.h"
52 #include "net/cookies/cookie_constants.h"
53 #include "net/cookies/cookie_inclusion_status.h"
54 #include "net/http/http_util.h"
55
56 namespace {
57
58 const char kPathTokenName[] = "path";
59 const char kDomainTokenName[] = "domain";
60 const char kExpiresTokenName[] = "expires";
61 const char kMaxAgeTokenName[] = "max-age";
62 const char kSecureTokenName[] = "secure";
63 const char kHttpOnlyTokenName[] = "httponly";
64 const char kSameSiteTokenName[] = "samesite";
65 const char kPriorityTokenName[] = "priority";
66 const char kSamePartyTokenName[] = "sameparty";
67 const char kPartitionedTokenName[] = "partitioned";
68
69 const char kTerminator[] = "\n\r\0";
70 const int kTerminatorLen = sizeof(kTerminator) - 1;
71 const char kWhitespace[] = " \t";
72 const char kValueSeparator = ';';
73 const char kTokenSeparator[] = ";=";
74
75 // Returns true if |c| occurs in |chars|
76 // TODO(erikwright): maybe make this take an iterator, could check for end also?
CharIsA(const char c,const char * chars)77 inline bool CharIsA(const char c, const char* chars) {
78 return strchr(chars, c) != nullptr;
79 }
80
81 // Seek the iterator to the first occurrence of |character|.
82 // Returns true if it hits the end, false otherwise.
SeekToCharacter(std::string::const_iterator * it,const std::string::const_iterator & end,const char character)83 inline bool SeekToCharacter(std::string::const_iterator* it,
84 const std::string::const_iterator& end,
85 const char character) {
86 for (; *it != end && **it != character; ++(*it)) {
87 }
88 return *it == end;
89 }
90
91 // Seek the iterator to the first occurrence of a character in |chars|.
92 // Returns true if it hit the end, false otherwise.
SeekTo(std::string::const_iterator * it,const std::string::const_iterator & end,const char * chars)93 inline bool SeekTo(std::string::const_iterator* it,
94 const std::string::const_iterator& end,
95 const char* chars) {
96 for (; *it != end && !CharIsA(**it, chars); ++(*it)) {
97 }
98 return *it == end;
99 }
100 // Seek the iterator to the first occurrence of a character not in |chars|.
101 // Returns true if it hit the end, false otherwise.
SeekPast(std::string::const_iterator * it,const std::string::const_iterator & end,const char * chars)102 inline bool SeekPast(std::string::const_iterator* it,
103 const std::string::const_iterator& end,
104 const char* chars) {
105 for (; *it != end && CharIsA(**it, chars); ++(*it)) {
106 }
107 return *it == end;
108 }
SeekBackPast(std::string::const_iterator * it,const std::string::const_iterator & end,const char * chars)109 inline bool SeekBackPast(std::string::const_iterator* it,
110 const std::string::const_iterator& end,
111 const char* chars) {
112 for (; *it != end && CharIsA(**it, chars); --(*it)) {
113 }
114 return *it == end;
115 }
116
117 // Returns the string piece within |value| that is a valid cookie value.
ValidStringPieceForValue(const std::string & value)118 base::StringPiece ValidStringPieceForValue(const std::string& value) {
119 std::string::const_iterator it = value.begin();
120 std::string::const_iterator end =
121 net::ParsedCookie::FindFirstTerminator(value);
122 std::string::const_iterator value_start;
123 std::string::const_iterator value_end;
124
125 net::ParsedCookie::ParseValue(&it, end, &value_start, &value_end);
126
127 return base::MakeStringPiece(value_start, value_end);
128 }
129
130 } // namespace
131
132 namespace net {
133
ParsedCookie(const std::string & cookie_line,CookieInclusionStatus * status_out)134 ParsedCookie::ParsedCookie(const std::string& cookie_line,
135 CookieInclusionStatus* status_out) {
136 // Put a pointer on the stack so the rest of the function can assign to it if
137 // the default nullptr is passed in.
138 CookieInclusionStatus blank_status;
139 if (status_out == nullptr) {
140 status_out = &blank_status;
141 }
142 *status_out = CookieInclusionStatus();
143
144 ParseTokenValuePairs(cookie_line, *status_out);
145 if (IsValid()) {
146 SetupAttributes();
147 } else if (status_out->IsInclude()) {
148 // TODO(crbug.com/1228815): Apply more specific exclusion reasons.
149 status_out->AddExclusionReason(
150 CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE);
151 }
152
153 // Status should indicate exclusion if the resulting ParsedCookie is invalid.
154 DCHECK(IsValid() || !status_out->IsInclude());
155 }
156
157 ParsedCookie::~ParsedCookie() = default;
158
IsValid() const159 bool ParsedCookie::IsValid() const {
160 return !pairs_.empty();
161 }
162
SameSite(CookieSameSiteString * samesite_string) const163 CookieSameSite ParsedCookie::SameSite(
164 CookieSameSiteString* samesite_string) const {
165 CookieSameSite samesite = CookieSameSite::UNSPECIFIED;
166 if (same_site_index_ != 0) {
167 samesite = StringToCookieSameSite(pairs_[same_site_index_].second,
168 samesite_string);
169 } else if (samesite_string) {
170 *samesite_string = CookieSameSiteString::kUnspecified;
171 }
172 return samesite;
173 }
174
Priority() const175 CookiePriority ParsedCookie::Priority() const {
176 return (priority_index_ == 0)
177 ? COOKIE_PRIORITY_DEFAULT
178 : StringToCookiePriority(pairs_[priority_index_].second);
179 }
180
SetName(const std::string & name)181 bool ParsedCookie::SetName(const std::string& name) {
182 const std::string& value = pairs_.empty() ? "" : pairs_[0].second;
183
184 // Ensure there are no invalid characters in `name`. This should be done
185 // before calling ParseTokenString because we want terminating characters
186 // ('\r', '\n', and '\0') and '=' in `name` to cause a rejection instead of
187 // truncation.
188 // TODO(crbug.com/1233602) Once we change logic more broadly to reject
189 // cookies containing these characters, we should be able to simplify this
190 // logic since IsValidCookieNameValuePair() also calls IsValidCookieName().
191 // Also, this check will currently fail if `name` has a tab character in the
192 // leading or trailing whitespace, which is inconsistent with what happens
193 // when parsing a cookie line in the constructor (but the old logic for
194 // SetName() behaved this way as well).
195 if (!IsValidCookieName(name)) {
196 return false;
197 }
198
199 // Use the same whitespace trimming code as the constructor.
200 const std::string& parsed_name = ParseTokenString(name);
201
202 if (!IsValidCookieNameValuePair(parsed_name, value)) {
203 return false;
204 }
205
206 if (pairs_.empty())
207 pairs_.emplace_back("", "");
208 pairs_[0].first = parsed_name;
209
210 return true;
211 }
212
SetValue(const std::string & value)213 bool ParsedCookie::SetValue(const std::string& value) {
214 const std::string& name = pairs_.empty() ? "" : pairs_[0].first;
215
216 // Ensure there are no invalid characters in `value`. This should be done
217 // before calling ParseValueString because we want terminating characters
218 // ('\r', '\n', and '\0') in `value` to cause a rejection instead of
219 // truncation.
220 // TODO(crbug.com/1233602) Once we change logic more broadly to reject
221 // cookies containing these characters, we should be able to simplify this
222 // logic since IsValidCookieNameValuePair() also calls IsValidCookieValue().
223 // Also, this check will currently fail if `value` has a tab character in
224 // the leading or trailing whitespace, which is inconsistent with what
225 // happens when parsing a cookie line in the constructor (but the old logic
226 // for SetValue() behaved this way as well).
227 if (!IsValidCookieValue(value)) {
228 return false;
229 }
230
231 // Use the same whitespace trimming code as the constructor.
232 const std::string& parsed_value = ParseValueString(value);
233
234 if (!IsValidCookieNameValuePair(name, parsed_value)) {
235 return false;
236 }
237 if (pairs_.empty())
238 pairs_.emplace_back("", "");
239 pairs_[0].second = parsed_value;
240
241 return true;
242 }
243
SetPath(const std::string & path)244 bool ParsedCookie::SetPath(const std::string& path) {
245 return SetString(&path_index_, kPathTokenName, path);
246 }
247
SetDomain(const std::string & domain)248 bool ParsedCookie::SetDomain(const std::string& domain) {
249 return SetString(&domain_index_, kDomainTokenName, domain);
250 }
251
SetExpires(const std::string & expires)252 bool ParsedCookie::SetExpires(const std::string& expires) {
253 return SetString(&expires_index_, kExpiresTokenName, expires);
254 }
255
SetMaxAge(const std::string & maxage)256 bool ParsedCookie::SetMaxAge(const std::string& maxage) {
257 return SetString(&maxage_index_, kMaxAgeTokenName, maxage);
258 }
259
SetIsSecure(bool is_secure)260 bool ParsedCookie::SetIsSecure(bool is_secure) {
261 return SetBool(&secure_index_, kSecureTokenName, is_secure);
262 }
263
SetIsHttpOnly(bool is_http_only)264 bool ParsedCookie::SetIsHttpOnly(bool is_http_only) {
265 return SetBool(&httponly_index_, kHttpOnlyTokenName, is_http_only);
266 }
267
SetSameSite(const std::string & same_site)268 bool ParsedCookie::SetSameSite(const std::string& same_site) {
269 return SetString(&same_site_index_, kSameSiteTokenName, same_site);
270 }
271
SetPriority(const std::string & priority)272 bool ParsedCookie::SetPriority(const std::string& priority) {
273 return SetString(&priority_index_, kPriorityTokenName, priority);
274 }
275
SetIsSameParty(bool is_same_party)276 bool ParsedCookie::SetIsSameParty(bool is_same_party) {
277 return SetBool(&same_party_index_, kSamePartyTokenName, is_same_party);
278 }
279
SetIsPartitioned(bool is_partitioned)280 bool ParsedCookie::SetIsPartitioned(bool is_partitioned) {
281 return SetBool(&partitioned_index_, kPartitionedTokenName, is_partitioned);
282 }
283
ToCookieLine() const284 std::string ParsedCookie::ToCookieLine() const {
285 std::string out;
286 for (auto it = pairs_.begin(); it != pairs_.end(); ++it) {
287 if (!out.empty())
288 out.append("; ");
289 out.append(it->first);
290 // Determine whether to emit the pair's value component. We should always
291 // print it for the first pair(see crbug.com/977619). After the first pair,
292 // we need to consider whether the name component is a special token.
293 if (it == pairs_.begin() ||
294 (it->first != kSecureTokenName && it->first != kHttpOnlyTokenName &&
295 it->first != kSamePartyTokenName &&
296 it->first != kPartitionedTokenName)) {
297 out.append("=");
298 out.append(it->second);
299 }
300 }
301 return out;
302 }
303
304 // static
FindFirstTerminator(const std::string & s)305 std::string::const_iterator ParsedCookie::FindFirstTerminator(
306 const std::string& s) {
307 std::string::const_iterator end = s.end();
308 size_t term_pos = s.find_first_of(std::string(kTerminator, kTerminatorLen));
309 if (term_pos != std::string::npos) {
310 // We found a character we should treat as an end of string.
311 end = s.begin() + term_pos;
312 }
313 return end;
314 }
315
316 // static
ParseToken(std::string::const_iterator * it,const std::string::const_iterator & end,std::string::const_iterator * token_start,std::string::const_iterator * token_end)317 bool ParsedCookie::ParseToken(std::string::const_iterator* it,
318 const std::string::const_iterator& end,
319 std::string::const_iterator* token_start,
320 std::string::const_iterator* token_end) {
321 DCHECK(it && token_start && token_end);
322 std::string::const_iterator token_real_end;
323
324 // Seek past any whitespace before the "token" (the name).
325 // token_start should point at the first character in the token
326 if (SeekPast(it, end, kWhitespace))
327 return false; // No token, whitespace or empty.
328 *token_start = *it;
329
330 // Seek over the token, to the token separator.
331 // token_real_end should point at the token separator, i.e. '='.
332 // If it == end after the seek, we probably have a token-value.
333 SeekTo(it, end, kTokenSeparator);
334 token_real_end = *it;
335
336 // Ignore any whitespace between the token and the token separator.
337 // token_end should point after the last interesting token character,
338 // pointing at either whitespace, or at '=' (and equal to token_real_end).
339 if (*it != *token_start) { // We could have an empty token name.
340 --(*it); // Go back before the token separator.
341 // Skip over any whitespace to the first non-whitespace character.
342 SeekBackPast(it, *token_start, kWhitespace);
343 // Point after it.
344 ++(*it);
345 }
346 *token_end = *it;
347
348 // Seek us back to the end of the token.
349 *it = token_real_end;
350 return true;
351 }
352
353 // static
ParseValue(std::string::const_iterator * it,const std::string::const_iterator & end,std::string::const_iterator * value_start,std::string::const_iterator * value_end)354 void ParsedCookie::ParseValue(std::string::const_iterator* it,
355 const std::string::const_iterator& end,
356 std::string::const_iterator* value_start,
357 std::string::const_iterator* value_end) {
358 DCHECK(it && value_start && value_end);
359
360 // Seek past any whitespace that might be in-between the token and value.
361 SeekPast(it, end, kWhitespace);
362 // value_start should point at the first character of the value.
363 *value_start = *it;
364
365 // Just look for ';' to terminate ('=' allowed).
366 // We can hit the end, maybe they didn't terminate.
367 SeekToCharacter(it, end, kValueSeparator);
368
369 // Will point at the ; separator or the end.
370 *value_end = *it;
371
372 // Ignore any unwanted whitespace after the value.
373 if (*value_end != *value_start) { // Could have an empty value
374 --(*value_end);
375 // Skip over any whitespace to the first non-whitespace character.
376 SeekBackPast(value_end, *value_start, kWhitespace);
377 // Point after it.
378 ++(*value_end);
379 }
380 }
381
382 // static
ParseTokenString(const std::string & token)383 std::string ParsedCookie::ParseTokenString(const std::string& token) {
384 std::string::const_iterator it = token.begin();
385 std::string::const_iterator end = FindFirstTerminator(token);
386
387 std::string::const_iterator token_start, token_end;
388 if (ParseToken(&it, end, &token_start, &token_end))
389 return std::string(token_start, token_end);
390 return std::string();
391 }
392
393 // static
ParseValueString(const std::string & value)394 std::string ParsedCookie::ParseValueString(const std::string& value) {
395 return std::string(ValidStringPieceForValue(value));
396 }
397
398 // static
ValueMatchesParsedValue(const std::string & value)399 bool ParsedCookie::ValueMatchesParsedValue(const std::string& value) {
400 // ValidStringPieceForValue() returns a valid substring of |value|.
401 // If |value| can be fully parsed the result will have the same length
402 // as |value|.
403 return ValidStringPieceForValue(value).length() == value.length();
404 }
405
406 // static
IsValidCookieName(const std::string & name)407 bool ParsedCookie::IsValidCookieName(const std::string& name) {
408 // IsValidCookieName() returns whether a string matches the following
409 // grammar:
410 //
411 // cookie-name = *cookie-name-octet
412 // cookie-name-octet = %x20-3A / %x3C / %x3E-7E / %x80-FF
413 // ; octets excluding CTLs, ";", and "="
414 //
415 // This can be used to determine whether cookie names and cookie attribute
416 // names contain any invalid characters.
417 //
418 // Note that RFC6265bis section 4.1.1 suggests a stricter grammar for
419 // parsing cookie names, but we choose to allow a wider range of characters
420 // than what's allowed by that grammar (while still conforming to the
421 // requirements of the parsing algorithm defined in section 5.2).
422 //
423 // For reference, see:
424 // - https://crbug.com/238041
425 for (char i : name) {
426 if (HttpUtil::IsControlChar(i) || i == ';' || i == '=')
427 return false;
428 }
429 return true;
430 }
431
432 // static
IsValidCookieValue(const std::string & value)433 bool ParsedCookie::IsValidCookieValue(const std::string& value) {
434 // IsValidCookieValue() returns whether a string matches the following
435 // grammar:
436 //
437 // cookie-value = *cookie-value-octet
438 // cookie-value-octet = %x20-3A / %x3C-7E / %x80-FF
439 // ; octets excluding CTLs and ";"
440 //
441 // This can be used to determine whether cookie values contain any invalid
442 // characters.
443 //
444 // Note that RFC6265bis section 4.1.1 suggests a stricter grammar for
445 // parsing cookie values, but we choose to allow a wider range of characters
446 // than what's allowed by that grammar (while still conforming to the
447 // requirements of the parsing algorithm defined in section 5.2).
448 //
449 // For reference, see:
450 // - https://crbug.com/238041
451 for (char i : value) {
452 if (HttpUtil::IsControlChar(i) || i == ';')
453 return false;
454 }
455 return true;
456 }
457
458 // static
CookieAttributeValueHasValidCharSet(const std::string & value)459 bool ParsedCookie::CookieAttributeValueHasValidCharSet(
460 const std::string& value) {
461 // A cookie attribute value has the same character set restrictions as cookie
462 // values, so re-use the validation function for that.
463 return IsValidCookieValue(value);
464 }
465
466 // static
CookieAttributeValueHasValidSize(const std::string & value)467 bool ParsedCookie::CookieAttributeValueHasValidSize(const std::string& value) {
468 return (value.size() <= kMaxCookieAttributeValueSize);
469 }
470
471 // static
IsValidCookieNameValuePair(const std::string & name,const std::string & value,CookieInclusionStatus * status_out)472 bool ParsedCookie::IsValidCookieNameValuePair(
473 const std::string& name,
474 const std::string& value,
475 CookieInclusionStatus* status_out) {
476 // Ignore cookies with neither name nor value.
477 if (name.empty() && value.empty()) {
478 if (status_out != nullptr) {
479 // TODO(crbug.com/1228815): Apply more specific exclusion reasons.
480 status_out->AddExclusionReason(
481 CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE);
482 }
483 // TODO(crbug.com/1228815) Note - if the exclusion reasons change to no
484 // longer be the same, we'll need to not return right away and evaluate all
485 // of the checks.
486 return false;
487 }
488
489 // Enforce a length limit for name + value per RFC6265bis.
490 base::CheckedNumeric<size_t> name_value_pair_size = name.size();
491 name_value_pair_size += value.size();
492 if (!name_value_pair_size.IsValid() ||
493 (name_value_pair_size.ValueOrDie() > kMaxCookieNamePlusValueSize)) {
494 if (status_out != nullptr) {
495 status_out->AddExclusionReason(
496 CookieInclusionStatus::EXCLUDE_NAME_VALUE_PAIR_EXCEEDS_MAX_SIZE);
497 }
498 return false;
499 }
500
501 // Ignore Set-Cookie directives containing control characters. See
502 // http://crbug.com/238041.
503 if (!IsValidCookieName(name) || !IsValidCookieValue(value)) {
504 // TODO(crbug.com/1228815): Apply more specific exclusion reasons.
505 if (status_out != nullptr) {
506 status_out->AddExclusionReason(
507 CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE);
508 }
509 return false;
510 }
511 return true;
512 }
513
514 // Parse all token/value pairs and populate pairs_.
ParseTokenValuePairs(const std::string & cookie_line,CookieInclusionStatus & status_out)515 void ParsedCookie::ParseTokenValuePairs(const std::string& cookie_line,
516 CookieInclusionStatus& status_out) {
517 pairs_.clear();
518
519 // Ok, here we go. We should be expecting to be starting somewhere
520 // before the cookie line, not including any header name...
521 std::string::const_iterator start = cookie_line.begin();
522 std::string::const_iterator it = start;
523
524 // TODO(erikwright): Make sure we're stripping \r\n in the network code.
525 // Then we can log any unexpected terminators.
526 std::string::const_iterator end = FindFirstTerminator(cookie_line);
527
528 // For metrics on truncating character presence in the cookie line.
529 if (end < cookie_line.end()) {
530 switch (*end) {
531 case '\0':
532 truncating_char_in_cookie_string_type_ =
533 TruncatingCharacterInCookieStringType::kTruncatingCharNull;
534 break;
535 case '\r':
536 truncating_char_in_cookie_string_type_ =
537 TruncatingCharacterInCookieStringType::kTruncatingCharNewline;
538 break;
539 case '\n':
540 truncating_char_in_cookie_string_type_ =
541 TruncatingCharacterInCookieStringType::kTruncatingCharLineFeed;
542 break;
543 default:
544 NOTREACHED();
545 }
546 }
547
548 // Exit early for an empty cookie string.
549 if (it == end) {
550 // TODO(crbug.com/1228815): Apply more specific exclusion reasons.
551 status_out.AddExclusionReason(
552 CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE);
553 return;
554 }
555
556 for (int pair_num = 0; it != end; ++pair_num) {
557 TokenValuePair pair;
558
559 std::string::const_iterator token_start, token_end;
560 if (!ParseToken(&it, end, &token_start, &token_end)) {
561 // Allow first token to be treated as empty-key if unparsable
562 if (pair_num != 0)
563 break;
564
565 // If parsing failed, start the value parsing at the very beginning.
566 token_start = start;
567 }
568
569 if (it == end || *it != '=') {
570 // We have a token-value, we didn't have any token name.
571 if (pair_num == 0) {
572 // For the first time around, we want to treat single values
573 // as a value with an empty name. (Mozilla bug 169091).
574 // IE seems to also have this behavior, ex "AAA", and "AAA=10" will
575 // set 2 different cookies, and setting "BBB" will then replace "AAA".
576 pair.first = "";
577 // Rewind to the beginning of what we thought was the token name,
578 // and let it get parsed as a value.
579 it = token_start;
580 } else {
581 // Any not-first attribute we want to treat a value as a
582 // name with an empty value... This is so something like
583 // "secure;" will get parsed as a Token name, and not a value.
584 pair.first = std::string(token_start, token_end);
585 }
586 } else {
587 // We have a TOKEN=VALUE.
588 pair.first = std::string(token_start, token_end);
589 ++it; // Skip past the '='.
590 }
591
592 // OK, now try to parse a value.
593 std::string::const_iterator value_start, value_end;
594 ParseValue(&it, end, &value_start, &value_end);
595
596 // OK, we're finished with a Token/Value.
597 pair.second = std::string(value_start, value_end);
598
599 // For metrics, check if either the name or value contain an internal HTAB
600 // (0x9). That is, not leading or trailing.
601 if (pair_num == 0 &&
602 (pair.first.find_first_of("\t") != std::string::npos ||
603 pair.second.find_first_of("\t") != std::string::npos)) {
604 internal_htab_ = true;
605 }
606
607 bool ignore_pair = false;
608 if (pair_num == 0) {
609 if (!IsValidCookieNameValuePair(pair.first, pair.second, &status_out)) {
610 pairs_.clear();
611 break;
612 }
613 } else {
614 // From RFC2109: "Attributes (names) (attr) are case-insensitive."
615 pair.first = base::ToLowerASCII(pair.first);
616
617 // Attribute names have the same character set limitations as cookie
618 // names, but only a handful of values are allowed. We don't check that
619 // this attribute name is one of the allowed ones here, so just re-use
620 // the cookie name check.
621 if (!IsValidCookieName(pair.first)) {
622 // TODO(crbug.com/1228815): Apply more specific exclusion reasons.
623 status_out.AddExclusionReason(
624 CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE);
625 pairs_.clear();
626 break;
627 }
628
629 if (!CookieAttributeValueHasValidCharSet(pair.second)) {
630 // If the attribute value contains invalid characters, the whole
631 // cookie should be ignored.
632 status_out.AddExclusionReason(
633 CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE);
634 pairs_.clear();
635 break;
636 }
637
638 if (!CookieAttributeValueHasValidSize(pair.second)) {
639 // If the attribute value is too large, it should be ignored.
640 ignore_pair = true;
641 status_out.AddWarningReason(
642 CookieInclusionStatus::WARN_ATTRIBUTE_VALUE_EXCEEDS_MAX_SIZE);
643 }
644 }
645
646 if (!ignore_pair) {
647 pairs_.push_back(pair);
648 }
649
650 // We've processed a token/value pair, we're either at the end of
651 // the string or a ValueSeparator like ';', which we want to skip.
652 if (it != end)
653 ++it;
654 }
655 }
656
SetupAttributes()657 void ParsedCookie::SetupAttributes() {
658 // We skip over the first token/value, the user supplied one.
659 for (size_t i = 1; i < pairs_.size(); ++i) {
660 if (pairs_[i].first == kPathTokenName) {
661 path_index_ = i;
662 } else if (pairs_[i].first == kDomainTokenName) {
663 domain_index_ = i;
664 } else if (pairs_[i].first == kExpiresTokenName) {
665 expires_index_ = i;
666 } else if (pairs_[i].first == kMaxAgeTokenName) {
667 maxage_index_ = i;
668 } else if (pairs_[i].first == kSecureTokenName) {
669 secure_index_ = i;
670 } else if (pairs_[i].first == kHttpOnlyTokenName) {
671 httponly_index_ = i;
672 } else if (pairs_[i].first == kSameSiteTokenName) {
673 same_site_index_ = i;
674 } else if (pairs_[i].first == kPriorityTokenName) {
675 priority_index_ = i;
676 } else if (pairs_[i].first == kSamePartyTokenName) {
677 same_party_index_ = i;
678 } else if (pairs_[i].first == kPartitionedTokenName) {
679 partitioned_index_ = i;
680 } else {
681 /* some attribute we don't know or don't care about. */
682 }
683 }
684 }
685
SetString(size_t * index,const std::string & key,const std::string & untrusted_value)686 bool ParsedCookie::SetString(size_t* index,
687 const std::string& key,
688 const std::string& untrusted_value) {
689 // This function should do equivalent input validation to the
690 // constructor. Otherwise, the Set* functions can put this ParsedCookie in a
691 // state where parsing the output of ToCookieLine() produces a different
692 // ParsedCookie.
693 //
694 // Without input validation, invoking pc.SetPath(" baz ") would result in
695 // pc.ToCookieLine() == "path= baz ". Parsing the "path= baz " string would
696 // produce a cookie with "path" attribute equal to "baz" (no spaces). We
697 // should not produce cookie lines that parse to different key/value pairs!
698
699 // Inputs containing invalid characters or attribute value strings that are
700 // too large should be ignored. Note that we check the attribute value size
701 // after removing leading and trailing whitespace.
702 if (!CookieAttributeValueHasValidCharSet(untrusted_value))
703 return false;
704
705 // Use the same whitespace trimming code as the constructor.
706 const std::string parsed_value = ParseValueString(untrusted_value);
707
708 if (!CookieAttributeValueHasValidSize(parsed_value))
709 return false;
710
711 if (parsed_value.empty()) {
712 ClearAttributePair(*index);
713 return true;
714 } else {
715 return SetAttributePair(index, key, parsed_value);
716 }
717 }
718
SetBool(size_t * index,const std::string & key,bool value)719 bool ParsedCookie::SetBool(size_t* index, const std::string& key, bool value) {
720 if (!value) {
721 ClearAttributePair(*index);
722 return true;
723 } else {
724 return SetAttributePair(index, key, std::string());
725 }
726 }
727
SetAttributePair(size_t * index,const std::string & key,const std::string & value)728 bool ParsedCookie::SetAttributePair(size_t* index,
729 const std::string& key,
730 const std::string& value) {
731 if (!HttpUtil::IsToken(key))
732 return false;
733 if (!IsValid())
734 return false;
735 if (*index) {
736 pairs_[*index].second = value;
737 } else {
738 pairs_.emplace_back(key, value);
739 *index = pairs_.size() - 1;
740 }
741 return true;
742 }
743
ClearAttributePair(size_t index)744 void ParsedCookie::ClearAttributePair(size_t index) {
745 // The first pair (name/value of cookie at pairs_[0]) cannot be cleared.
746 // Cookie attributes that don't have a value at the moment, are
747 // represented with an index being equal to 0.
748 if (index == 0)
749 return;
750
751 size_t* indexes[] = {&path_index_, &domain_index_, &expires_index_,
752 &maxage_index_, &secure_index_, &httponly_index_,
753 &same_site_index_, &priority_index_, &same_party_index_,
754 &partitioned_index_};
755 for (size_t* attribute_index : indexes) {
756 if (*attribute_index == index)
757 *attribute_index = 0;
758 else if (*attribute_index > index)
759 --(*attribute_index);
760 }
761 pairs_.erase(pairs_.begin() + index);
762 }
763
764 } // namespace net
765