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 #include "net/cookies/cookie_util.h"
6
7 #include <cstdio>
8 #include <cstdlib>
9 #include <string>
10 #include <utility>
11
12 #include "base/check.h"
13 #include "base/feature_list.h"
14 #include "base/functional/bind.h"
15 #include "base/functional/callback.h"
16 #include "base/metrics/histogram_functions.h"
17 #include "base/metrics/histogram_macros.h"
18 #include "base/notreached.h"
19 #include "base/strings/strcat.h"
20 #include "base/strings/string_piece.h"
21 #include "base/strings/string_tokenizer.h"
22 #include "base/strings/string_util.h"
23 #include "base/types/optional_util.h"
24 #include "build/build_config.h"
25 #include "net/base/features.h"
26 #include "net/base/isolation_info.h"
27 #include "net/base/registry_controlled_domains/registry_controlled_domain.h"
28 #include "net/base/url_util.h"
29 #include "net/cookies/cookie_access_delegate.h"
30 #include "net/cookies/cookie_constants.h"
31 #include "net/cookies/cookie_inclusion_status.h"
32 #include "net/cookies/cookie_monster.h"
33 #include "net/cookies/cookie_options.h"
34 #include "net/first_party_sets/first_party_set_metadata.h"
35 #include "net/first_party_sets/same_party_context.h"
36 #include "net/http/http_util.h"
37 #include "url/gurl.h"
38 #include "url/url_constants.h"
39
40 namespace net::cookie_util {
41
42 namespace {
43
44 using ContextType = CookieOptions::SameSiteCookieContext::ContextType;
45 using ContextMetadata = CookieOptions::SameSiteCookieContext::ContextMetadata;
46
MinNonNullTime()47 base::Time MinNonNullTime() {
48 return base::Time::FromInternalValue(1);
49 }
50
51 // Tries to assemble a base::Time given a base::Time::Exploded representing a
52 // UTC calendar date.
53 //
54 // If the date falls outside of the range supported internally by
55 // FromUTCExploded() on the current platform, then the result is:
56 //
57 // * Time(1) if it's below the range FromUTCExploded() supports.
58 // * Time::Max() if it's above the range FromUTCExploded() supports.
SaturatedTimeFromUTCExploded(const base::Time::Exploded & exploded,base::Time * out)59 bool SaturatedTimeFromUTCExploded(const base::Time::Exploded& exploded,
60 base::Time* out) {
61 // Try to calculate the base::Time in the normal fashion.
62 if (base::Time::FromUTCExploded(exploded, out)) {
63 // Don't return Time(0) on success.
64 if (out->is_null())
65 *out = MinNonNullTime();
66 return true;
67 }
68
69 // base::Time::FromUTCExploded() has platform-specific limits:
70 //
71 // * Windows: Years 1601 - 30827
72 // * 32-bit POSIX: Years 1970 - 2038
73 //
74 // Work around this by returning min/max valid times for times outside those
75 // ranges when imploding the time is doomed to fail.
76 //
77 // Note that the following implementation is NOT perfect. It will accept
78 // some invalid calendar dates in the out-of-range case.
79 if (!exploded.HasValidValues())
80 return false;
81
82 if (exploded.year > base::Time::kExplodedMaxYear) {
83 *out = base::Time::Max();
84 return true;
85 }
86 if (exploded.year < base::Time::kExplodedMinYear) {
87 *out = MinNonNullTime();
88 return true;
89 }
90
91 return false;
92 }
93
94 struct ComputeSameSiteContextResult {
95 ContextType context_type = ContextType::CROSS_SITE;
96 ContextMetadata metadata;
97 };
98
MakeSameSiteCookieContext(const ComputeSameSiteContextResult & result,const ComputeSameSiteContextResult & schemeful_result)99 CookieOptions::SameSiteCookieContext MakeSameSiteCookieContext(
100 const ComputeSameSiteContextResult& result,
101 const ComputeSameSiteContextResult& schemeful_result) {
102 return CookieOptions::SameSiteCookieContext(
103 result.context_type, schemeful_result.context_type, result.metadata,
104 schemeful_result.metadata);
105 }
106
107 ContextMetadata::ContextRedirectTypeBug1221316
ComputeContextRedirectTypeBug1221316(bool url_chain_is_length_one,bool same_site_initiator,bool site_for_cookies_is_same_site,bool same_site_redirect_chain)108 ComputeContextRedirectTypeBug1221316(bool url_chain_is_length_one,
109 bool same_site_initiator,
110 bool site_for_cookies_is_same_site,
111 bool same_site_redirect_chain) {
112 if (url_chain_is_length_one)
113 return ContextMetadata::ContextRedirectTypeBug1221316::kNoRedirect;
114
115 if (!same_site_initiator || !site_for_cookies_is_same_site)
116 return ContextMetadata::ContextRedirectTypeBug1221316::kCrossSiteRedirect;
117
118 if (!same_site_redirect_chain) {
119 return ContextMetadata::ContextRedirectTypeBug1221316::
120 kPartialSameSiteRedirect;
121 }
122
123 return ContextMetadata::ContextRedirectTypeBug1221316::kAllSameSiteRedirect;
124 }
125
126 // This function consolidates the common logic for computing SameSite cookie
127 // access context in various situations (HTTP vs JS; get vs set).
128 //
129 // `is_http` is whether the current cookie access request is associated with a
130 // network request (as opposed to a non-HTTP API, i.e., JavaScript).
131 //
132 // `compute_schemefully` is whether the current computation is for a
133 // schemeful_context, i.e. whether scheme should be considered when comparing
134 // two sites.
135 //
136 // See documentation of `ComputeSameSiteContextForRequest` for explanations of
137 // other parameters.
ComputeSameSiteContext(const std::vector<GURL> & url_chain,const SiteForCookies & site_for_cookies,const absl::optional<url::Origin> & initiator,bool is_http,bool is_main_frame_navigation,bool compute_schemefully)138 ComputeSameSiteContextResult ComputeSameSiteContext(
139 const std::vector<GURL>& url_chain,
140 const SiteForCookies& site_for_cookies,
141 const absl::optional<url::Origin>& initiator,
142 bool is_http,
143 bool is_main_frame_navigation,
144 bool compute_schemefully) {
145 DCHECK(!url_chain.empty());
146 const GURL& request_url = url_chain.back();
147 const auto is_same_site_with_site_for_cookies =
148 [&site_for_cookies, compute_schemefully](const GURL& url) {
149 return site_for_cookies.IsFirstPartyWithSchemefulMode(
150 url, compute_schemefully);
151 };
152
153 bool site_for_cookies_is_same_site =
154 is_same_site_with_site_for_cookies(request_url);
155
156 // If the request is a main frame navigation, site_for_cookies must either be
157 // null (for opaque origins, e.g., data: origins) or same-site with the
158 // request URL (both schemefully and schemelessly), and the URL cannot be
159 // ws/wss (these schemes are not navigable).
160 DCHECK(!is_main_frame_navigation || site_for_cookies_is_same_site ||
161 site_for_cookies.IsNull());
162 DCHECK(!is_main_frame_navigation || !request_url.SchemeIsWSOrWSS());
163
164 // Defaults to a cross-site context type.
165 ComputeSameSiteContextResult result;
166
167 // Create a SiteForCookies object from the initiator so that we can reuse
168 // IsFirstPartyWithSchemefulMode().
169 bool same_site_initiator =
170 !initiator ||
171 SiteForCookies::FromOrigin(initiator.value())
172 .IsFirstPartyWithSchemefulMode(request_url, compute_schemefully);
173
174 // Check that the URLs in the redirect chain are all same-site with the
175 // site_for_cookies and hence (by transitivity) same-site with the request
176 // URL. (If the URL chain only has one member, it's the request_url and we've
177 // already checked it previously.)
178 bool same_site_redirect_chain =
179 url_chain.size() == 1u ||
180 base::ranges::all_of(url_chain, is_same_site_with_site_for_cookies);
181
182 // Record what type of redirect was experienced.
183
184 result.metadata.redirect_type_bug_1221316 =
185 ComputeContextRedirectTypeBug1221316(
186 url_chain.size() == 1u, same_site_initiator,
187 site_for_cookies_is_same_site, same_site_redirect_chain);
188
189 if (!site_for_cookies_is_same_site)
190 return result;
191
192 // Whether the context would be SAME_SITE_STRICT if not considering redirect
193 // chains, but is different after considering redirect chains.
194 bool cross_site_redirect_downgraded_from_strict = false;
195 // Allows the kCookieSameSiteConsidersRedirectChain feature to override the
196 // result and use SAME_SITE_STRICT.
197 bool use_strict = false;
198
199 if (same_site_initiator) {
200 if (same_site_redirect_chain) {
201 result.context_type = ContextType::SAME_SITE_STRICT;
202 return result;
203 }
204 cross_site_redirect_downgraded_from_strict = true;
205 // If we are not supposed to consider redirect chains, record that the
206 // context result should ultimately be strictly same-site. We cannot
207 // just return early from here because we don't yet know what the context
208 // gets downgraded to, so we can't return with the correct metadata until we
209 // go through the rest of the logic below to determine that.
210 use_strict = !base::FeatureList::IsEnabled(
211 features::kCookieSameSiteConsidersRedirectChain);
212 }
213
214 if (!is_http || is_main_frame_navigation) {
215 if (cross_site_redirect_downgraded_from_strict) {
216 result.metadata.cross_site_redirect_downgrade =
217 ContextMetadata::ContextDowngradeType::kStrictToLax;
218 }
219 result.context_type =
220 use_strict ? ContextType::SAME_SITE_STRICT : ContextType::SAME_SITE_LAX;
221 return result;
222 }
223
224 if (cross_site_redirect_downgraded_from_strict) {
225 result.metadata.cross_site_redirect_downgrade =
226 ContextMetadata::ContextDowngradeType::kStrictToCross;
227 }
228 result.context_type =
229 use_strict ? ContextType::SAME_SITE_STRICT : ContextType::CROSS_SITE;
230
231 return result;
232 }
233
234 // Setting any SameSite={Strict,Lax} cookie only requires a LAX context, so
235 // normalize any strictly same-site contexts to Lax for cookie writes.
NormalizeStrictToLaxForSet(ComputeSameSiteContextResult & result)236 void NormalizeStrictToLaxForSet(ComputeSameSiteContextResult& result) {
237 if (result.context_type == ContextType::SAME_SITE_STRICT)
238 result.context_type = ContextType::SAME_SITE_LAX;
239
240 switch (result.metadata.cross_site_redirect_downgrade) {
241 case ContextMetadata::ContextDowngradeType::kStrictToLax:
242 result.metadata.cross_site_redirect_downgrade =
243 ContextMetadata::ContextDowngradeType::kNoDowngrade;
244 break;
245 case ContextMetadata::ContextDowngradeType::kStrictToCross:
246 result.metadata.cross_site_redirect_downgrade =
247 ContextMetadata::ContextDowngradeType::kLaxToCross;
248 break;
249 default:
250 break;
251 }
252 }
253
ComputeSameSiteContextForSet(const std::vector<GURL> & url_chain,const SiteForCookies & site_for_cookies,const absl::optional<url::Origin> & initiator,bool is_http,bool is_main_frame_navigation)254 CookieOptions::SameSiteCookieContext ComputeSameSiteContextForSet(
255 const std::vector<GURL>& url_chain,
256 const SiteForCookies& site_for_cookies,
257 const absl::optional<url::Origin>& initiator,
258 bool is_http,
259 bool is_main_frame_navigation) {
260 CookieOptions::SameSiteCookieContext same_site_context;
261
262 ComputeSameSiteContextResult result = ComputeSameSiteContext(
263 url_chain, site_for_cookies, initiator, is_http, is_main_frame_navigation,
264 false /* compute_schemefully */);
265 ComputeSameSiteContextResult schemeful_result = ComputeSameSiteContext(
266 url_chain, site_for_cookies, initiator, is_http, is_main_frame_navigation,
267 true /* compute_schemefully */);
268
269 NormalizeStrictToLaxForSet(result);
270 NormalizeStrictToLaxForSet(schemeful_result);
271
272 return MakeSameSiteCookieContext(result, schemeful_result);
273 }
274
CookieWithAccessResultSorter(const CookieWithAccessResult & a,const CookieWithAccessResult & b)275 bool CookieWithAccessResultSorter(const CookieWithAccessResult& a,
276 const CookieWithAccessResult& b) {
277 return CookieMonster::CookieSorter(&a.cookie, &b.cookie);
278 }
279
280 } // namespace
281
FireStorageAccessHistogram(StorageAccessResult result)282 void FireStorageAccessHistogram(StorageAccessResult result) {
283 UMA_HISTOGRAM_ENUMERATION("API.StorageAccess.AllowedRequests2", result);
284 }
285
DomainIsHostOnly(const std::string & domain_string)286 bool DomainIsHostOnly(const std::string& domain_string) {
287 return (domain_string.empty() || domain_string[0] != '.');
288 }
289
CookieDomainAsHost(const std::string & cookie_domain)290 std::string CookieDomainAsHost(const std::string& cookie_domain) {
291 if (DomainIsHostOnly(cookie_domain))
292 return cookie_domain;
293 return cookie_domain.substr(1);
294 }
295
GetEffectiveDomain(const std::string & scheme,const std::string & host)296 std::string GetEffectiveDomain(const std::string& scheme,
297 const std::string& host) {
298 if (scheme == "http" || scheme == "https" || scheme == "ws" ||
299 scheme == "wss") {
300 return registry_controlled_domains::GetDomainAndRegistry(
301 host,
302 registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES);
303 }
304
305 return CookieDomainAsHost(host);
306 }
307
GetCookieDomainWithString(const GURL & url,const std::string & domain_string,CookieInclusionStatus & status,std::string * result)308 bool GetCookieDomainWithString(const GURL& url,
309 const std::string& domain_string,
310 CookieInclusionStatus& status,
311 std::string* result) {
312 // Disallow non-ASCII domain names.
313 if (!base::IsStringASCII(domain_string)) {
314 if (base::FeatureList::IsEnabled(features::kCookieDomainRejectNonASCII)) {
315 status.AddExclusionReason(
316 CookieInclusionStatus::EXCLUDE_DOMAIN_NON_ASCII);
317 return false;
318 }
319 status.AddWarningReason(CookieInclusionStatus::WARN_DOMAIN_NON_ASCII);
320 }
321
322 const std::string url_host(url.host());
323
324 // Disallow invalid hostnames containing multiple `.` at the end.
325 // Httpbis-rfc6265bis draft-11, §5.1.2 says to convert the request host "into
326 // a sequence of individual domain name labels"; a label can only be empty if
327 // it is the last label in the name, but a name ending in `..` would have an
328 // empty label in the penultimate position and is thus invalid.
329 if (url_host.ends_with("..")) {
330 return false;
331 }
332 // If no domain was specified in the domain string, default to a host cookie.
333 // We match IE/Firefox in allowing a domain=IPADDR if it matches (case
334 // in-sensitive) the url ip address hostname and ignoring a leading dot if one
335 // exists. It should be treated as a host cookie.
336 if (domain_string.empty() ||
337 (url.HostIsIPAddress() &&
338 (base::EqualsCaseInsensitiveASCII(url_host, domain_string) ||
339 base::EqualsCaseInsensitiveASCII("." + url_host, domain_string)))) {
340 *result = url_host;
341 DCHECK(DomainIsHostOnly(*result));
342 return true;
343 }
344
345 // Disallow domain names with %-escaped characters.
346 for (char c : domain_string) {
347 if (c == '%')
348 return false;
349 }
350
351 url::CanonHostInfo ignored;
352 std::string cookie_domain(CanonicalizeHost(domain_string, &ignored));
353 // Get the normalized domain specified in cookie line.
354 if (cookie_domain.empty())
355 return false;
356 if (cookie_domain[0] != '.')
357 cookie_domain = "." + cookie_domain;
358
359 // Ensure |url| and |cookie_domain| have the same domain+registry.
360 const std::string url_scheme(url.scheme());
361 const std::string url_domain_and_registry(
362 GetEffectiveDomain(url_scheme, url_host));
363 if (url_domain_and_registry.empty()) {
364 // We match IE/Firefox by treating an exact match between the normalized
365 // domain attribute and the request host to be treated as a host cookie.
366 std::string normalized_domain_string = base::ToLowerASCII(
367 domain_string[0] == '.' ? domain_string.substr(1) : domain_string);
368
369 if (url_host == normalized_domain_string) {
370 *result = url_host;
371 DCHECK(DomainIsHostOnly(*result));
372 return true;
373 }
374
375 // Otherwise, IP addresses/intranet hosts/public suffixes can't set
376 // domain cookies.
377 return false;
378 }
379 const std::string cookie_domain_and_registry(
380 GetEffectiveDomain(url_scheme, cookie_domain));
381 if (url_domain_and_registry != cookie_domain_and_registry)
382 return false; // Can't set a cookie on a different domain + registry.
383
384 // Ensure |url_host| is |cookie_domain| or one of its subdomains. Given that
385 // we know the domain+registry are the same from the above checks, this is
386 // basically a simple string suffix check.
387 const bool is_suffix = (url_host.length() < cookie_domain.length()) ?
388 (cookie_domain != ("." + url_host)) :
389 (url_host.compare(url_host.length() - cookie_domain.length(),
390 cookie_domain.length(), cookie_domain) != 0);
391 if (is_suffix)
392 return false;
393
394 *result = cookie_domain;
395 return true;
396 }
397
398 // Parse a cookie expiration time. We try to be lenient, but we need to
399 // assume some order to distinguish the fields. The basic rules:
400 // - The month name must be present and prefix the first 3 letters of the
401 // full month name (jan for January, jun for June).
402 // - If the year is <= 2 digits, it must occur after the day of month.
403 // - The time must be of the format hh:mm:ss.
404 // An average cookie expiration will look something like this:
405 // Sat, 15-Apr-17 21:01:22 GMT
ParseCookieExpirationTime(const std::string & time_string)406 base::Time ParseCookieExpirationTime(const std::string& time_string) {
407 static const char* const kMonths[] = {
408 "jan", "feb", "mar", "apr", "may", "jun",
409 "jul", "aug", "sep", "oct", "nov", "dec" };
410 // We want to be pretty liberal, and support most non-ascii and non-digit
411 // characters as a delimiter. We can't treat : as a delimiter, because it
412 // is the delimiter for hh:mm:ss, and we want to keep this field together.
413 // We make sure to include - and +, since they could prefix numbers.
414 // If the cookie attribute came in in quotes (ex expires="XXX"), the quotes
415 // will be preserved, and we will get them here. So we make sure to include
416 // quote characters, and also \ for anything that was internally escaped.
417 static const char kDelimiters[] = "\t !\"#$%&'()*+,-./;<=>?@[\\]^_`{|}~";
418
419 base::Time::Exploded exploded = {0};
420
421 base::StringTokenizer tokenizer(time_string, kDelimiters);
422
423 bool found_day_of_month = false;
424 bool found_month = false;
425 bool found_time = false;
426 bool found_year = false;
427
428 while (tokenizer.GetNext()) {
429 const std::string token = tokenizer.token();
430 DCHECK(!token.empty());
431 bool numerical = base::IsAsciiDigit(token[0]);
432
433 // String field
434 if (!numerical) {
435 if (!found_month) {
436 for (size_t i = 0; i < std::size(kMonths); ++i) {
437 // Match prefix, so we could match January, etc
438 if (base::StartsWith(token, base::StringPiece(kMonths[i], 3),
439 base::CompareCase::INSENSITIVE_ASCII)) {
440 exploded.month = static_cast<int>(i) + 1;
441 found_month = true;
442 break;
443 }
444 }
445 } else {
446 // If we've gotten here, it means we've already found and parsed our
447 // month, and we have another string, which we would expect to be the
448 // the time zone name. According to the RFC and my experiments with
449 // how sites format their expirations, we don't have much of a reason
450 // to support timezones. We don't want to ever barf on user input,
451 // but this DCHECK should pass for well-formed data.
452 // DCHECK(token == "GMT");
453 }
454 // Numeric field w/ a colon
455 } else if (token.find(':') != std::string::npos) {
456 if (!found_time &&
457 #ifdef COMPILER_MSVC
458 sscanf_s(
459 #else
460 sscanf(
461 #endif
462 token.c_str(), "%2u:%2u:%2u", &exploded.hour,
463 &exploded.minute, &exploded.second) == 3) {
464 found_time = true;
465 } else {
466 // We should only ever encounter one time-like thing. If we're here,
467 // it means we've found a second, which shouldn't happen. We keep
468 // the first. This check should be ok for well-formed input:
469 // NOTREACHED();
470 }
471 // Numeric field
472 } else {
473 // Overflow with atoi() is unspecified, so we enforce a max length.
474 if (!found_day_of_month && token.length() <= 2) {
475 exploded.day_of_month = atoi(token.c_str());
476 found_day_of_month = true;
477 } else if (!found_year && token.length() <= 5) {
478 exploded.year = atoi(token.c_str());
479 found_year = true;
480 } else {
481 // If we're here, it means we've either found an extra numeric field,
482 // or a numeric field which was too long. For well-formed input, the
483 // following check would be reasonable:
484 // NOTREACHED();
485 }
486 }
487 }
488
489 if (!found_day_of_month || !found_month || !found_time || !found_year) {
490 // We didn't find all of the fields we need. For well-formed input, the
491 // following check would be reasonable:
492 // NOTREACHED() << "Cookie parse expiration failed: " << time_string;
493 return base::Time();
494 }
495
496 // Normalize the year to expand abbreviated years to the full year.
497 if (exploded.year >= 70 && exploded.year <= 99)
498 exploded.year += 1900;
499 if (exploded.year >= 0 && exploded.year <= 69)
500 exploded.year += 2000;
501
502 // Note that clipping the date if it is outside of a platform-specific range
503 // is permitted by: https://tools.ietf.org/html/rfc6265#section-5.2.1
504 base::Time result;
505 if (SaturatedTimeFromUTCExploded(exploded, &result))
506 return result;
507
508 // One of our values was out of expected range. For well-formed input,
509 // the following check would be reasonable:
510 // NOTREACHED() << "Cookie exploded expiration failed: " << time_string;
511
512 return base::Time();
513 }
514
CookieDomainAndPathToURL(const std::string & domain,const std::string & path,const std::string & source_scheme)515 GURL CookieDomainAndPathToURL(const std::string& domain,
516 const std::string& path,
517 const std::string& source_scheme) {
518 // Note: domain_no_dot could be empty for e.g. file cookies.
519 std::string domain_no_dot = CookieDomainAsHost(domain);
520 if (domain_no_dot.empty() || source_scheme.empty())
521 return GURL();
522 return GURL(base::StrCat(
523 {source_scheme, url::kStandardSchemeSeparator, domain_no_dot, path}));
524 }
525
CookieDomainAndPathToURL(const std::string & domain,const std::string & path,bool is_https)526 GURL CookieDomainAndPathToURL(const std::string& domain,
527 const std::string& path,
528 bool is_https) {
529 return CookieDomainAndPathToURL(
530 domain, path,
531 std::string(is_https ? url::kHttpsScheme : url::kHttpScheme));
532 }
533
CookieDomainAndPathToURL(const std::string & domain,const std::string & path,CookieSourceScheme source_scheme)534 GURL CookieDomainAndPathToURL(const std::string& domain,
535 const std::string& path,
536 CookieSourceScheme source_scheme) {
537 return CookieDomainAndPathToURL(domain, path,
538 source_scheme == CookieSourceScheme::kSecure);
539 }
540
CookieOriginToURL(const std::string & domain,bool is_https)541 GURL CookieOriginToURL(const std::string& domain, bool is_https) {
542 return CookieDomainAndPathToURL(domain, "/", is_https);
543 }
544
SimulatedCookieSource(const CanonicalCookie & cookie,const std::string & source_scheme)545 GURL SimulatedCookieSource(const CanonicalCookie& cookie,
546 const std::string& source_scheme) {
547 return CookieDomainAndPathToURL(cookie.Domain(), cookie.Path(),
548 source_scheme);
549 }
550
ProvisionalAccessScheme(const GURL & source_url)551 CookieAccessScheme ProvisionalAccessScheme(const GURL& source_url) {
552 return source_url.SchemeIsCryptographic()
553 ? CookieAccessScheme::kCryptographic
554 : IsLocalhost(source_url) ? CookieAccessScheme::kTrustworthy
555 : CookieAccessScheme::kNonCryptographic;
556 }
557
IsDomainMatch(const std::string & domain,const std::string & host)558 bool IsDomainMatch(const std::string& domain, const std::string& host) {
559 // Can domain match in two ways; as a domain cookie (where the cookie
560 // domain begins with ".") or as a host cookie (where it doesn't).
561
562 // Some consumers of the CookieMonster expect to set cookies on
563 // URLs like http://.strange.url. To retrieve cookies in this instance,
564 // we allow matching as a host cookie even when the domain_ starts with
565 // a period.
566 if (host == domain)
567 return true;
568
569 // Domain cookie must have an initial ".". To match, it must be
570 // equal to url's host with initial period removed, or a suffix of
571 // it.
572
573 // Arguably this should only apply to "http" or "https" cookies, but
574 // extension cookie tests currently use the funtionality, and if we
575 // ever decide to implement that it should be done by preventing
576 // such cookies from being set.
577 if (domain.empty() || domain[0] != '.')
578 return false;
579
580 // The host with a "." prefixed.
581 if (domain.compare(1, std::string::npos, host) == 0)
582 return true;
583
584 // A pure suffix of the host (ok since we know the domain already
585 // starts with a ".")
586 return (host.length() > domain.length() &&
587 host.compare(host.length() - domain.length(), domain.length(),
588 domain) == 0);
589 }
590
IsOnPath(const std::string & cookie_path,const std::string & url_path)591 bool IsOnPath(const std::string& cookie_path, const std::string& url_path) {
592 // A zero length would be unsafe for our trailing '/' checks, and
593 // would also make no sense for our prefix match. The code that
594 // creates a CanonicalCookie should make sure the path is never zero length,
595 // but we double check anyway.
596 if (cookie_path.empty()) {
597 return false;
598 }
599
600 // The Mozilla code broke this into three cases, based on if the cookie path
601 // was longer, the same length, or shorter than the length of the url path.
602 // I think the approach below is simpler.
603
604 // Make sure the cookie path is a prefix of the url path. If the url path is
605 // shorter than the cookie path, then the cookie path can't be a prefix.
606 if (!base::StartsWith(url_path, cookie_path, base::CompareCase::SENSITIVE)) {
607 return false;
608 }
609
610 // |url_path| is >= |cookie_path|, and |cookie_path| is a prefix of
611 // |url_path|. If they are the are the same length then they are identical,
612 // otherwise need an additional check:
613
614 // In order to avoid in correctly matching a cookie path of /blah
615 // with a request path of '/blahblah/', we need to make sure that either
616 // the cookie path ends in a trailing '/', or that we prefix up to a '/'
617 // in the url path. Since we know that the url path length is greater
618 // than the cookie path length, it's safe to index one byte past.
619 if (cookie_path.length() != url_path.length() && cookie_path.back() != '/' &&
620 url_path[cookie_path.length()] != '/') {
621 return false;
622 }
623
624 return true;
625 }
626
ParseRequestCookieLine(const std::string & header_value,ParsedRequestCookies * parsed_cookies)627 void ParseRequestCookieLine(const std::string& header_value,
628 ParsedRequestCookies* parsed_cookies) {
629 std::string::const_iterator i = header_value.begin();
630 while (i != header_value.end()) {
631 // Here we are at the beginning of a cookie.
632
633 // Eat whitespace.
634 while (i != header_value.end() && *i == ' ') ++i;
635 if (i == header_value.end()) return;
636
637 // Find cookie name.
638 std::string::const_iterator cookie_name_beginning = i;
639 while (i != header_value.end() && *i != '=') ++i;
640 auto cookie_name = base::MakeStringPiece(cookie_name_beginning, i);
641
642 // Find cookie value.
643 base::StringPiece cookie_value;
644 // Cookies may have no value, in this case '=' may or may not be there.
645 if (i != header_value.end() && i + 1 != header_value.end()) {
646 ++i; // Skip '='.
647 std::string::const_iterator cookie_value_beginning = i;
648 if (*i == '"') {
649 ++i; // Skip '"'.
650 while (i != header_value.end() && *i != '"') ++i;
651 if (i == header_value.end()) return;
652 ++i; // Skip '"'.
653 cookie_value = base::MakeStringPiece(cookie_value_beginning, i);
654 // i points to character after '"', potentially a ';'.
655 } else {
656 while (i != header_value.end() && *i != ';') ++i;
657 cookie_value = base::MakeStringPiece(cookie_value_beginning, i);
658 // i points to ';' or end of string.
659 }
660 }
661 parsed_cookies->emplace_back(std::string(cookie_name),
662 std::string(cookie_value));
663 // Eat ';'.
664 if (i != header_value.end()) ++i;
665 }
666 }
667
SerializeRequestCookieLine(const ParsedRequestCookies & parsed_cookies)668 std::string SerializeRequestCookieLine(
669 const ParsedRequestCookies& parsed_cookies) {
670 std::string buffer;
671 for (const auto& parsed_cookie : parsed_cookies) {
672 if (!buffer.empty())
673 buffer.append("; ");
674 buffer.append(parsed_cookie.first.begin(), parsed_cookie.first.end());
675 buffer.push_back('=');
676 buffer.append(parsed_cookie.second.begin(), parsed_cookie.second.end());
677 }
678 return buffer;
679 }
680
ComputeSameSiteContextForRequest(const std::string & http_method,const std::vector<GURL> & url_chain,const SiteForCookies & site_for_cookies,const absl::optional<url::Origin> & initiator,bool is_main_frame_navigation,bool force_ignore_site_for_cookies)681 CookieOptions::SameSiteCookieContext ComputeSameSiteContextForRequest(
682 const std::string& http_method,
683 const std::vector<GURL>& url_chain,
684 const SiteForCookies& site_for_cookies,
685 const absl::optional<url::Origin>& initiator,
686 bool is_main_frame_navigation,
687 bool force_ignore_site_for_cookies) {
688 // Set SameSiteCookieContext according to the rules laid out in
689 // https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis:
690 //
691 // * Include both "strict" and "lax" same-site cookies if the request's
692 // |url|, |initiator|, and |site_for_cookies| all have the same
693 // registrable domain. Note: this also covers the case of a request
694 // without an initiator (only happens for browser-initiated main frame
695 // navigations). If computing schemefully, the schemes must also match.
696 //
697 // * Include only "lax" same-site cookies if the request's |URL| and
698 // |site_for_cookies| have the same registrable domain, _and_ the
699 // request's |http_method| is "safe" ("GET" or "HEAD"), and the request
700 // is a main frame navigation.
701 //
702 // This case should occur only for cross-site requests which
703 // target a top-level browsing context, with a "safe" method.
704 //
705 // * Include both "strict" and "lax" same-site cookies if the request is
706 // tagged with a flag allowing it.
707 //
708 // Note that this can be the case for requests initiated by extensions,
709 // which need to behave as though they are made by the document itself,
710 // but appear like cross-site ones.
711 //
712 // * Otherwise, do not include same-site cookies.
713
714 if (force_ignore_site_for_cookies)
715 return CookieOptions::SameSiteCookieContext::MakeInclusive();
716
717 ComputeSameSiteContextResult result = ComputeSameSiteContext(
718 url_chain, site_for_cookies, initiator, true /* is_http */,
719 is_main_frame_navigation, false /* compute_schemefully */);
720 ComputeSameSiteContextResult schemeful_result = ComputeSameSiteContext(
721 url_chain, site_for_cookies, initiator, true /* is_http */,
722 is_main_frame_navigation, true /* compute_schemefully */);
723
724 // If the method is safe, the context is Lax. Otherwise, make a note that
725 // the method is unsafe.
726 if (!net::HttpUtil::IsMethodSafe(http_method)) {
727 if (result.context_type == ContextType::SAME_SITE_LAX)
728 result.context_type = ContextType::SAME_SITE_LAX_METHOD_UNSAFE;
729 if (schemeful_result.context_type == ContextType::SAME_SITE_LAX)
730 schemeful_result.context_type = ContextType::SAME_SITE_LAX_METHOD_UNSAFE;
731 }
732
733 ContextMetadata::HttpMethod http_method_enum =
734 HttpMethodStringToEnum(http_method);
735
736 if (result.metadata.cross_site_redirect_downgrade !=
737 ContextMetadata::ContextDowngradeType::kNoDowngrade) {
738 result.metadata.http_method_bug_1221316 = http_method_enum;
739 }
740
741 if (schemeful_result.metadata.cross_site_redirect_downgrade !=
742 ContextMetadata::ContextDowngradeType::kNoDowngrade) {
743 schemeful_result.metadata.http_method_bug_1221316 = http_method_enum;
744 }
745
746 return MakeSameSiteCookieContext(result, schemeful_result);
747 }
748
749 NET_EXPORT CookieOptions::SameSiteCookieContext
ComputeSameSiteContextForScriptGet(const GURL & url,const SiteForCookies & site_for_cookies,const absl::optional<url::Origin> & initiator,bool force_ignore_site_for_cookies)750 ComputeSameSiteContextForScriptGet(const GURL& url,
751 const SiteForCookies& site_for_cookies,
752 const absl::optional<url::Origin>& initiator,
753 bool force_ignore_site_for_cookies) {
754 if (force_ignore_site_for_cookies)
755 return CookieOptions::SameSiteCookieContext::MakeInclusive();
756
757 // We don't check the redirect chain for script access to cookies (only the
758 // URL itself).
759 ComputeSameSiteContextResult result = ComputeSameSiteContext(
760 {url}, site_for_cookies, initiator, false /* is_http */,
761 false /* is_main_frame_navigation */, false /* compute_schemefully */);
762 ComputeSameSiteContextResult schemeful_result = ComputeSameSiteContext(
763 {url}, site_for_cookies, initiator, false /* is_http */,
764 false /* is_main_frame_navigation */, true /* compute_schemefully */);
765
766 return MakeSameSiteCookieContext(result, schemeful_result);
767 }
768
ComputeSameSiteContextForResponse(const std::vector<GURL> & url_chain,const SiteForCookies & site_for_cookies,const absl::optional<url::Origin> & initiator,bool is_main_frame_navigation,bool force_ignore_site_for_cookies)769 CookieOptions::SameSiteCookieContext ComputeSameSiteContextForResponse(
770 const std::vector<GURL>& url_chain,
771 const SiteForCookies& site_for_cookies,
772 const absl::optional<url::Origin>& initiator,
773 bool is_main_frame_navigation,
774 bool force_ignore_site_for_cookies) {
775 if (force_ignore_site_for_cookies)
776 return CookieOptions::SameSiteCookieContext::MakeInclusiveForSet();
777
778 DCHECK(!url_chain.empty());
779 if (is_main_frame_navigation && !site_for_cookies.IsNull()) {
780 // If the request is a main frame navigation, site_for_cookies must either
781 // be null (for opaque origins, e.g., data: origins) or same-site with the
782 // request URL (both schemefully and schemelessly), and the URL cannot be
783 // ws/wss (these schemes are not navigable).
784 DCHECK(
785 site_for_cookies.IsFirstPartyWithSchemefulMode(url_chain.back(), true));
786 DCHECK(!url_chain.back().SchemeIsWSOrWSS());
787 CookieOptions::SameSiteCookieContext result =
788 CookieOptions::SameSiteCookieContext::MakeInclusiveForSet();
789
790 const GURL& request_url = url_chain.back();
791
792 for (bool compute_schemefully : {false, true}) {
793 bool same_site_initiator =
794 !initiator ||
795 SiteForCookies::FromOrigin(initiator.value())
796 .IsFirstPartyWithSchemefulMode(request_url, compute_schemefully);
797
798 const auto is_same_site_with_site_for_cookies =
799 [&site_for_cookies, compute_schemefully](const GURL& url) {
800 return site_for_cookies.IsFirstPartyWithSchemefulMode(
801 url, compute_schemefully);
802 };
803
804 bool same_site_redirect_chain =
805 url_chain.size() == 1u ||
806 base::ranges::all_of(url_chain, is_same_site_with_site_for_cookies);
807
808 CookieOptions::SameSiteCookieContext::ContextMetadata& result_metadata =
809 compute_schemefully ? result.schemeful_metadata() : result.metadata();
810
811 result_metadata.redirect_type_bug_1221316 =
812 ComputeContextRedirectTypeBug1221316(
813 url_chain.size() == 1u, same_site_initiator,
814 true /* site_for_cookies_is_same_site */,
815 same_site_redirect_chain);
816 }
817 return result;
818 }
819
820 return ComputeSameSiteContextForSet(url_chain, site_for_cookies, initiator,
821 true /* is_http */,
822 is_main_frame_navigation);
823 }
824
ComputeSameSiteContextForScriptSet(const GURL & url,const SiteForCookies & site_for_cookies,bool force_ignore_site_for_cookies)825 CookieOptions::SameSiteCookieContext ComputeSameSiteContextForScriptSet(
826 const GURL& url,
827 const SiteForCookies& site_for_cookies,
828 bool force_ignore_site_for_cookies) {
829 if (force_ignore_site_for_cookies)
830 return CookieOptions::SameSiteCookieContext::MakeInclusiveForSet();
831
832 // It doesn't matter what initiator origin we pass here. Either way, the
833 // context will be considered same-site iff the site_for_cookies is same-site
834 // with the url. We don't check the redirect chain for script access to
835 // cookies (only the URL itself).
836 return ComputeSameSiteContextForSet(
837 {url}, site_for_cookies, absl::nullopt /* initiator */,
838 false /* is_http */, false /* is_main_frame_navigation */);
839 }
840
ComputeSameSiteContextForSubresource(const GURL & url,const SiteForCookies & site_for_cookies,bool force_ignore_site_for_cookies)841 CookieOptions::SameSiteCookieContext ComputeSameSiteContextForSubresource(
842 const GURL& url,
843 const SiteForCookies& site_for_cookies,
844 bool force_ignore_site_for_cookies) {
845 if (force_ignore_site_for_cookies)
846 return CookieOptions::SameSiteCookieContext::MakeInclusive();
847
848 // If the URL is same-site as site_for_cookies it's same-site as all frames
849 // in the tree from the initiator frame up --- including the initiator frame.
850
851 // Schemeless check
852 if (!site_for_cookies.IsFirstPartyWithSchemefulMode(url, false)) {
853 return CookieOptions::SameSiteCookieContext(ContextType::CROSS_SITE,
854 ContextType::CROSS_SITE);
855 }
856
857 // Schemeful check
858 if (!site_for_cookies.IsFirstPartyWithSchemefulMode(url, true)) {
859 return CookieOptions::SameSiteCookieContext(ContextType::SAME_SITE_STRICT,
860 ContextType::CROSS_SITE);
861 }
862
863 return CookieOptions::SameSiteCookieContext::MakeInclusive();
864 }
865
IsSchemefulSameSiteEnabled()866 bool IsSchemefulSameSiteEnabled() {
867 return base::FeatureList::IsEnabled(features::kSchemefulSameSite);
868 }
869
ComputeFirstPartySetMetadataMaybeAsync(const SchemefulSite & request_site,const IsolationInfo & isolation_info,const CookieAccessDelegate * cookie_access_delegate,bool force_ignore_top_frame_party,base::OnceCallback<void (FirstPartySetMetadata)> callback)870 absl::optional<FirstPartySetMetadata> ComputeFirstPartySetMetadataMaybeAsync(
871 const SchemefulSite& request_site,
872 const IsolationInfo& isolation_info,
873 const CookieAccessDelegate* cookie_access_delegate,
874 bool force_ignore_top_frame_party,
875 base::OnceCallback<void(FirstPartySetMetadata)> callback) {
876 if (!isolation_info.IsEmpty() && isolation_info.party_context().has_value() &&
877 cookie_access_delegate) {
878 return cookie_access_delegate->ComputeFirstPartySetMetadataMaybeAsync(
879 request_site,
880 force_ignore_top_frame_party
881 ? nullptr
882 : base::OptionalToPtr(
883 isolation_info.network_isolation_key().GetTopFrameSite()),
884 isolation_info.party_context().value(), std::move(callback));
885 }
886
887 return FirstPartySetMetadata();
888 }
889
890 CookieOptions::SameSiteCookieContext::ContextMetadata::HttpMethod
HttpMethodStringToEnum(const std::string & in)891 HttpMethodStringToEnum(const std::string& in) {
892 using HttpMethod =
893 CookieOptions::SameSiteCookieContext::ContextMetadata::HttpMethod;
894 if (in == "GET")
895 return HttpMethod::kGet;
896 if (in == "HEAD")
897 return HttpMethod::kHead;
898 if (in == "POST")
899 return HttpMethod::kPost;
900 if (in == "PUT")
901 return HttpMethod::KPut;
902 if (in == "DELETE")
903 return HttpMethod::kDelete;
904 if (in == "CONNECT")
905 return HttpMethod::kConnect;
906 if (in == "OPTIONS")
907 return HttpMethod::kOptions;
908 if (in == "TRACE")
909 return HttpMethod::kTrace;
910 if (in == "PATCH")
911 return HttpMethod::kPatch;
912
913 return HttpMethod::kUnknown;
914 }
915
GetSamePartyStatus(const CanonicalCookie & cookie,const CookieOptions & options,const bool same_party_attribute_enabled)916 CookieSamePartyStatus GetSamePartyStatus(
917 const CanonicalCookie& cookie,
918 const CookieOptions& options,
919 const bool same_party_attribute_enabled) {
920 if (!same_party_attribute_enabled || !cookie.IsSameParty() ||
921 !options.is_in_nontrivial_first_party_set()) {
922 return CookieSamePartyStatus::kNoSamePartyEnforcement;
923 }
924
925 switch (options.same_party_context().context_type()) {
926 case SamePartyContext::Type::kCrossParty:
927 return CookieSamePartyStatus::kEnforceSamePartyExclude;
928 case SamePartyContext::Type::kSameParty:
929 return CookieSamePartyStatus::kEnforceSamePartyInclude;
930 };
931 }
932
IsCookieAccessResultInclude(CookieAccessResult cookie_access_result)933 bool IsCookieAccessResultInclude(CookieAccessResult cookie_access_result) {
934 return cookie_access_result.status.IsInclude();
935 }
936
StripAccessResults(const CookieAccessResultList & cookie_access_results_list)937 CookieList StripAccessResults(
938 const CookieAccessResultList& cookie_access_results_list) {
939 CookieList cookies;
940 for (const CookieWithAccessResult& cookie_with_access_result :
941 cookie_access_results_list) {
942 cookies.push_back(cookie_with_access_result.cookie);
943 }
944 return cookies;
945 }
946
RecordCookiePortOmniboxHistograms(const GURL & url)947 NET_EXPORT void RecordCookiePortOmniboxHistograms(const GURL& url) {
948 int port = url.EffectiveIntPort();
949
950 if (port == url::PORT_UNSPECIFIED)
951 return;
952
953 if (IsLocalhost(url)) {
954 UMA_HISTOGRAM_ENUMERATION("Cookie.Port.OmniboxURLNavigation.Localhost",
955 ReducePortRangeForCookieHistogram(port));
956 } else {
957 UMA_HISTOGRAM_ENUMERATION("Cookie.Port.OmniboxURLNavigation.RemoteHost",
958 ReducePortRangeForCookieHistogram(port));
959 }
960 }
961
DCheckIncludedAndExcludedCookieLists(const CookieAccessResultList & included_cookies,const CookieAccessResultList & excluded_cookies)962 NET_EXPORT void DCheckIncludedAndExcludedCookieLists(
963 const CookieAccessResultList& included_cookies,
964 const CookieAccessResultList& excluded_cookies) {
965 // Check that all elements of `included_cookies` really should be included,
966 // and that all elements of `excluded_cookies` really should be excluded.
967 DCHECK(base::ranges::all_of(included_cookies,
968 [](const net::CookieWithAccessResult& cookie) {
969 return cookie.access_result.status.IsInclude();
970 }));
971 DCHECK(base::ranges::none_of(excluded_cookies,
972 [](const net::CookieWithAccessResult& cookie) {
973 return cookie.access_result.status.IsInclude();
974 }));
975
976 // Check that the included cookies are still in the correct order.
977 DCHECK(
978 base::ranges::is_sorted(included_cookies, CookieWithAccessResultSorter));
979 }
980
981 } // namespace net::cookie_util
982