Internet-Draft | Cookies: HTTP State Management Mechanism | December 2020 |
West & Wilander | Expires 10 June 2021 | [Page] |
This document defines the HTTP Cookie and Set-Cookie header fields. Theseheader fields can be used by HTTP servers to store state (called cookies) atHTTP user agents, letting the servers maintain a stateful session over themostly stateless HTTP protocol. Although cookies have many historicalinfelicities that degrade their security and privacy, the Cookie and Set-Cookieheader fields are widely used on the Internet. This document obsoletes RFC6265.¶
Discussion of this draft takes place on the HTTP working group mailing list(ietf-http-wg@w3.org), which is archived athttps://lists.w3.org/Archives/Public/ietf-http-wg/.¶
Working Group information can be found athttp://httpwg.github.io/; sourcecode and issues list for this draft can be found athttps://github.com/httpwg/http-extensions/labels/6265bis.¶
This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.¶
Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is athttps://datatracker.ietf.org/drafts/current/.¶
Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."¶
This Internet-Draft will expire on 10 June 2021.¶
Copyright (c) 2020 IETF Trust and the persons identified as the document authors. All rights reserved.¶
This document is subject to BCP 78 and the IETF Trust's Legal Provisions Relating to IETF Documents (https://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.¶
This document may contain material from IETF Documents or IETF Contributions published or made publicly available before November 10, 2008. The person(s) controlling the copyright in some of this material may not have granted the IETF Trust the right to allow modifications of such material outside the IETF Standards Process. Without obtaining an adequate license from the person(s) controlling the copyright in such materials, this document may not be modified outside the IETF Standards Process, and derivative works of it may not be created outside the IETF Standards Process, except to format it for publication as an RFC or to translate it into languages other than English.¶
This document defines the HTTP Cookie and Set-Cookie header fields. Usingthe Set-Cookie header field, an HTTP server can pass name/value pairs andassociated metadata (called cookies) to a user agent. When the user agent makessubsequent requests to the server, the user agent uses the metadata and otherinformation to determine whether to return the name/value pairs in the Cookieheader.¶
Although simple on their surface, cookies have a number of complexities. Forexample, the server indicates a scope for each cookie when sending it to theuser agent. The scope indicates the maximum amount of time in which the useragent should return the cookie, the servers to which the user agent shouldreturn the cookie, and the URI schemes for which the cookie is applicable.¶
For historical reasons, cookies contain a number of security and privacyinfelicities. For example, a server can indicate that a given cookie isintended for "secure" connections, but the Secure attribute does not provideintegrity in the presence of an active network attacker. Similarly, cookiesfor a given host are shared across all the ports on that host, even though theusual "same-origin policy" used by web browsers isolates content retrieved viadifferent ports.¶
There are two audiences for this specification: developers of cookie-generatingservers and developers of cookie-consuming user agents.¶
To maximize interoperability with user agents, servers SHOULD limit themselvesto the well-behaved profile defined inSection 4 when generating cookies.¶
User agents MUST implement the more liberal processing rules defined inSection 5, in order to maximize interoperability with existing servers that do notconform to the well-behaved profile defined inSection 4.¶
This document specifies the syntax and semantics of these headers as they areactually used on the Internet. In particular, this document does not createnew syntax or semantics beyond those in use today. The recommendations forcookie generation provided inSection 4 represent a preferred subset of currentserver behavior, and even the more liberal cookie processing algorithm providedinSection 5 does not recommend all of the syntactic and semantic variations inuse today. Where some existing software differs from the recommended protocolin significant ways, the document contains a note explaining the difference.¶
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD","SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to beinterpreted as described in[RFC2119].¶
Requirements phrased in the imperative as part of algorithms (such as "strip anyleading space characters" or "return false and abort these steps") are to beinterpreted with the meaning of the key word ("MUST", "SHOULD", "MAY", etc.)used in introducing the algorithm.¶
Conformance requirements phrased as algorithms or specific steps can beimplemented in any manner, so long as the end result is equivalent. Inparticular, the algorithms defined in this specification are intended to beeasy to understand and are not intended to be performant.¶
This specification uses the Augmented Backus-Naur Form (ABNF) notation of[RFC5234].¶
The following core rules are included by reference, as defined in[RFC5234],Appendix B.1: ALPHA (letters), CR (carriage return), CRLF (CR LF), CTLs(controls), DIGIT (decimal 0-9), DQUOTE (double quote), HEXDIG(hexadecimal 0-9/A-F/a-f), LF (line feed), NUL (null octet), OCTET (any8-bit sequence of data except NUL), SP (space), HTAB (horizontal tab),CHAR (any[USASCII] character), VCHAR (any visible[USASCII] character),and WSP (whitespace).¶
The OWS (optional whitespace) and BWS (bad whitespace) rules are defined inSection 3.2.3 of[RFC7230].¶
The terms "user agent", "client", "server", "proxy", and "origin server" havethe same meaning as in the HTTP/1.1 specification ([RFC7230], Section 2).¶
The request-host is the name of the host, as known by the user agent, to whichthe user agent is sending an HTTP request or from which it is receiving an HTTPresponse (i.e., the name of the host to which it sent the corresponding HTTPrequest).¶
The term request-uri refers to "request-target" as defined in Section 5.3 of[RFC7230].¶
Two sequences of octets are said to case-insensitively match each other if andonly if they are equivalent under the i;ascii-casemap collation defined in[RFC4790].¶
The term string means a sequence of non-NUL octets.¶
The terms "active document", "ancestor browsing context", "browsing context","dedicated worker", "Document", "WorkerGlobalScope", "sandboxed origin browsingcontext flag", "parent browsing context", "shared worker", "the worker'sDocuments", "nested browsing context", and "top-level browsing context" aredefined in[HTML].¶
"Service Workers" are defined in the Service Workers specification[SERVICE-WORKERS].¶
The term "origin", the mechanism of deriving an origin from a URI, and the "thesame" matching algorithm for origins are defined in[RFC6454].¶
"Safe" HTTP methods includeGET
,HEAD
,OPTIONS
, andTRACE
, as definedin Section 4.2.1 of[RFC7231].¶
A domain's "public suffix" is the portion of a domain that is controlled by apublic registry, such as "com", "co.uk", and "pvt.k12.wy.us". A domain's"registrable domain" is the domain's public suffix plus the label to its left.That is, forhttps://www.site.example
, the public suffix isexample
, and theregistrable domain issite.example
. Whenever possible, user agents SHOULDuse an up-to-date public suffix list, such as the one maintained by the Mozillaproject at[PSL].¶
The term "request", as well as a request's "client", "current url", "method",and "target browsing context", are defined in[FETCH].¶
This section outlines a way for an origin server to send state information to auser agent and for the user agent to return the state information to the originserver.¶
To store state, the origin server includes a Set-Cookie header in an HTTPresponse. In subsequent requests, the user agent returns a Cookie requestheader to the origin server. The Cookie header contains cookies the user agentreceived in previous Set-Cookie headers. The origin server is free to ignorethe Cookie header or use its contents for an application-defined purpose.¶
Origin servers MAY send a Set-Cookie response header with any response. Useragents MAY ignore Set-Cookie headers contained in responses with 100-levelstatus codes but MUST process Set-Cookie headers contained in other responses(including responses with 400- and 500-level status codes). An origin servercan include multiple Set-Cookie header fields in a single response. Thepresence of a Cookie or a Set-Cookie header field does not preclude HTTPcaches from storing and reusing a response.¶
Origin servers SHOULD NOT fold multiple Set-Cookie header fields into a singleheader field. The usual mechanism for folding HTTP headers fields (i.e., asdefined in Section 3.2.2 of[RFC7230]) might change the semantics of the Set-Cookie headerfield because the %x2C (",") character is used by Set-Cookie in a way thatconflicts with such folding.¶
Using the Set-Cookie header, a server can send the user agent a short stringin an HTTP response that the user agent will return in future HTTP requests thatare within the scope of the cookie. For example, the server can send the useragent a "session identifier" named SID with the value 31d4d96e407aad42. Theuser agent then returns the session identifier in subsequent requests.¶
== Server -> User Agent ==Set-Cookie: SID=31d4d96e407aad42== User Agent -> Server ==Cookie: SID=31d4d96e407aad42¶
The server can alter the default scope of the cookie using the Path andDomain attributes. For example, the server can instruct the user agent toreturn the cookie to every path and every subdomain of site.example.¶
== Server -> User Agent ==Set-Cookie: SID=31d4d96e407aad42; Path=/; Domain=site.example== User Agent -> Server ==Cookie: SID=31d4d96e407aad42¶
As shown in the next example, the server can store multiple cookies at the useragent. For example, the server can store a session identifier as well as theuser's preferred language by returning two Set-Cookie header fields. Noticethat the server uses the Secure and HttpOnly attributes to provideadditional security protections for the more sensitive session identifier (seeSection 4.1.2).¶
== Server -> User Agent ==Set-Cookie: SID=31d4d96e407aad42; Path=/; Secure; HttpOnlySet-Cookie: lang=en-US; Path=/; Domain=site.example== User Agent -> Server ==Cookie: SID=31d4d96e407aad42; lang=en-US¶
Notice that the Cookie header above contains two cookies, one named SID andone named lang. If the server wishes the user agent to persist the cookie overmultiple "sessions" (e.g., user agent restarts), the server can specify anexpiration date in the Expires attribute. Note that the user agent mightdelete the cookie before the expiration date if the user agent's cookie storeexceeds its quota or if the user manually deletes the server's cookie.¶
== Server -> User Agent ==Set-Cookie: lang=en-US; Expires=Wed, 09 Jun 2021 10:18:14 GMT== User Agent -> Server ==Cookie: SID=31d4d96e407aad42; lang=en-US¶
Finally, to remove a cookie, the server returns a Set-Cookie header with anexpiration date in the past. The server will be successful in removing thecookie only if the Path and the Domain attribute in the Set-Cookie headermatch the values used when the cookie was created.¶
== Server -> User Agent ==Set-Cookie: lang=; Expires=Sun, 06 Nov 1994 08:49:37 GMT== User Agent -> Server ==Cookie: SID=31d4d96e407aad42¶
This section describes the syntax and semantics of a well-behaved profile of theCookie and Set-Cookie headers.¶
The Set-Cookie HTTP response header is used to send cookies from the server tothe user agent.¶
Informally, the Set-Cookie response header contains the header name"Set-Cookie" followed by a ":" and a cookie. Each cookie begins with aname-value-pair, followed by zero or more attribute-value pairs. ServersSHOULD NOT send Set-Cookie headers that fail to conform to the followinggrammar:¶
set-cookie-header = "Set-Cookie:" SP BWS set-cookie-stringset-cookie-string = BWS cookie-pair *( BWS ";" OWS cookie-av )cookie-pair = cookie-name BWS "=" BWS cookie-valuecookie-name = 1*cookie-octetcookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E / %x80-FF ; octets excluding CTLs, ; whitespace DQUOTE, comma, semicolon, ; and backslashcookie-av = expires-av / max-age-av / domain-av / path-av / secure-av / httponly-av / samesite-av / extension-avexpires-av = "Expires" BWS "=" BWS sane-cookie-datesane-cookie-date = <IMF-fixdate, defined in [RFC7231], Section 7.1.1.1>max-age-av = "Max-Age" BWS "=" BWS non-zero-digit *DIGIT ; In practice, both expires-av and max-age-av ; are limited to dates representable by the ; user agent.non-zero-digit = %x31-39 ; digits 1 through 9domain-av = "Domain" BWS "=" BWS domain-valuedomain-value = <subdomain> ; defined in [RFC1034], Section 3.5, as ; enhanced by [RFC1123], Section 2.1path-av = "Path" BWS "=" BWS path-valuepath-value = *av-octetsecure-av = "Secure"httponly-av = "HttpOnly"samesite-av = "SameSite" BWS "=" BWS samesite-valuesamesite-value = "Strict" / "Lax" / "None"extension-av = *av-octetav-octet = %x20-3A / %x3C-7E ; any CHAR except CTLs or ";"¶
Note that some of the grammatical terms above reference documents that usedifferent grammatical notations than this document (which uses ABNF from[RFC5234]).¶
The semantics of the cookie-value are not defined by this document.¶
To maximize compatibility with user agents, servers that wish to store arbitrarydata in a cookie-value SHOULD encode that data, for example, using Base64[RFC4648].¶
Per the grammar above, the cookie-value MAY be wrapped in DQUOTE characters.Note that in this case, the initial and trailing DQUOTE characters are notstripped. They are part of the cookie-value, and will be included in Cookieheaders sent to the server.¶
The portions of the set-cookie-string produced by the cookie-av term areknown as attributes. To maximize compatibility with user agents, servers SHOULDNOT produce two attributes with the same name in the same set-cookie-string.(SeeSection 5.4 for how user agents handle this case.)¶
Servers SHOULD NOT include more than one Set-Cookie header field in the sameresponse with the same cookie-name. (SeeSection 5.3 for how user agentshandle this case.)¶
If a server sends multiple responses containing Set-Cookie headersconcurrently to the user agent (e.g., when communicating with the user agentover multiple sockets), these responses create a "race condition" that can leadto unpredictable behavior.¶
NOTE: Some existing user agents differ in their interpretation of two-digityears. To avoid compatibility issues, servers SHOULD use the rfc1123-dateformat, which requires a four-digit year.¶
NOTE: Some user agents store and process dates in cookies as 32-bit UNIX time_tvalues. Implementation bugs in the libraries supporting time_t processing onsome systems might cause such user agents to process dates after the year 2038incorrectly.¶
This section describes simplified semantics of the Set-Cookie header. Thesesemantics are detailed enough to be useful for understanding the most commonuses of cookies by servers. The full semantics are described inSection 5.¶
When the user agent receives a Set-Cookie header, the user agent stores thecookie together with its attributes. Subsequently, when the user agent makesan HTTP request, the user agent includes the applicable, non-expired cookiesin the Cookie header.¶
If the user agent receives a new cookie with the same cookie-name,domain-value, and path-value as a cookie that it has already stored, theexisting cookie is evicted and replaced with the new cookie. Notice thatservers can delete cookies by sending the user agent a new cookie with anExpires attribute with a value in the past.¶
Unless the cookie's attributes indicate otherwise, the cookie is returned onlyto the origin server (and not, for example, to any subdomains), and it expiresat the end of the current session (as defined by the user agent). User agentsignore unrecognized cookie attributes (but not the entire cookie).¶
The Expires attribute indicates the maximum lifetime of the cookie,represented as the date and time at which the cookie expires. The user agent isnot required to retain the cookie until the specified date has passed. In fact,user agents often evict cookies due to memory pressure or privacy concerns.¶
The Max-Age attribute indicates the maximum lifetime of the cookie,represented as the number of seconds until the cookie expires. The user agent isnot required to retain the cookie for the specified duration. In fact, useragents often evict cookies due to memory pressure or privacy concerns.¶
NOTE: Some existing user agents do not support the Max-Age attribute. Useragents that do not support the Max-Age attribute ignore the attribute.¶
If a cookie has both the Max-Age and the Expires attribute, the Max-Ageattribute has precedence and controls the expiration date of the cookie. If acookie has neither the Max-Age nor the Expires attribute, the user agentwill retain the cookie until "the current session is over" (as defined by theuser agent).¶
The Domain attribute specifies those hosts to which the cookie will be sent.For example, if the value of the Domain attribute is "site.example", the useragent will include the cookie in the Cookie header when making HTTP requests tosite.example, www.site.example, and www.corp.site.example. (Note that aleading %x2E ("."), if present, is ignored even though that character is notpermitted, but a trailing %x2E ("."), if present, will cause the user agent toignore the attribute.) If the server omits the Domain attribute, the useragent will return the cookie only to the origin server.¶
WARNING: Some existing user agents treat an absent Domain attribute as if theDomain attribute were present and contained the current host name. Forexample, if site.example returns a Set-Cookie header without a Domainattribute, these user agents will erroneously send the cookie towww.site.example as well.¶
The user agent will reject cookies unless the Domain attribute specifies ascope for the cookie that would include the origin server. For example, theuser agent will accept a cookie with a Domain attribute of "site.example" orof "foo.site.example" from foo.site.example, but the user agent will not accepta cookie with a Domain attribute of "bar.site.example" or of"baz.foo.site.example".¶
NOTE: For security reasons, many user agents are configured to reject Domainattributes that correspond to "public suffixes". For example, some useragents will reject Domain attributes of "com" or "co.uk". (SeeSection 5.4 formore information.)¶
The scope of each cookie is limited to a set of paths, controlled by thePath attribute. If the server omits the Path attribute, the user agent willuse the "directory" of the request-uri's path component as the default value.(SeeSection 5.1.4 for more details.)¶
The user agent will include the cookie in an HTTP request only if the pathportion of the request-uri matches (or is a subdirectory of) the cookie'sPath attribute, where the %x2F ("/") character is interpreted as a directoryseparator.¶
Although seemingly useful for isolating cookies between different paths withina given host, the Path attribute cannot be relied upon for security (seeSection 8).¶
The Secure attribute limits the scope of the cookie to "secure" channels(where "secure" is defined by the user agent). When a cookie has the Secureattribute, the user agent will include the cookie in an HTTP request only ifthe request is transmitted over a secure channel (typically HTTP over TransportLayer Security (TLS)[RFC2818]).¶
Although seemingly useful for protecting cookies from active network attackers,the Secure attribute protects only the cookie's confidentiality. An activenetwork attacker can overwrite Secure cookies from an insecure channel,disrupting their integrity (seeSection 8.6 for more details).¶
The HttpOnly attribute limits the scope of the cookie to HTTP requests. Inparticular, the attribute instructs the user agent to omit the cookie whenproviding access to cookies via "non-HTTP" APIs (such as a web browser API thatexposes cookies to scripts).¶
Note that the HttpOnly attribute is independent of the Secure attribute: acookie can have both the HttpOnly and the Secure attribute.¶
The "SameSite" attribute limits the scope of the cookie such that it will onlybe attached to requests if those requests are same-site, as defined by thealgorithm inSection 5.2. For example, requests forhttps://site.example/sekrit-image
will attach same-site cookies if and only ifinitiated from a context whose "site for cookies" is an origin with a scheme andregistered domain of "https" and "site.example" respectively.¶
If the "SameSite" attribute's value is "Strict", the cookie will only be sentalong with "same-site" requests. If the value is "Lax", the cookie will be sentwith same-site requests, and with "cross-site" top-level navigations, asdescribed inSection 5.3.7.1. If the value is "None", the cookie will be sentwith same-site and cross-site requests. If the "SameSite" attribute's value issomething other than these three known keywords, the attribute's value will besubject to a default enforcement mode that is equivalent to "Lax".¶
The "SameSite" attribute affects cookie creation as well as delivery. Cookieswhich assert "SameSite=Lax" or "SameSite=Strict" cannot be set in responses tocross-site subresource requests, or cross-site nested navigations. They can beset along with any top-level navigation, cross-site or otherwise.¶
Section 8.5 andSection 8.6 of this document spell out some of the drawbacks of cookies'historical implementation. In particular, it is impossible for a server to haveconfidence that a given cookie was set with a particular set of attributes. Inorder to provide such confidence in a backwards-compatible way, two common setsof requirements can be inferred from the first few characters of the cookie'sname.¶
The normative requirements for the prefixes described below are detailed in thestorage model algorithm defined inSection 5.4.¶
If a cookie's name begins with a case-sensitive match for the string__Secure-
, then the cookie will have been set with aSecure
attribute.¶
For example, the followingSet-Cookie
header would be rejected by a conformantuser agent, as it does not have aSecure
attribute.¶
Set-Cookie: __Secure-SID=12345; Domain=site.example¶
Whereas the followingSet-Cookie
header would be accepted:¶
Set-Cookie: __Secure-SID=12345; Domain=site.example; Secure¶
If a cookie's name begins with a case-sensitive match for the string__Host-
, then the cookie will have been set with aSecure
attribute, aPath
attribute with a value of/
, and noDomain
attribute.¶
This combination yields a cookie that hews as closely as a cookie can totreating the origin as a security boundary. The lack of aDomain
attributeensures that the cookie'shost-only-flag
is true, locking the cookie to aparticular host, rather than allowing it to span subdomains. Setting thePath
to/
means that the cookie is effective for the entire host, and won't beoverridden for specific paths. TheSecure
attribute ensures that the cookieis unaltered by non-secure origins, and won't span protocols.¶
Ports are the only piece of the origin model that__Host-
cookies continueto ignore.¶
For example, the following cookies would always be rejected:¶
Set-Cookie: __Host-SID=12345Set-Cookie: __Host-SID=12345; SecureSet-Cookie: __Host-SID=12345; Domain=site.exampleSet-Cookie: __Host-SID=12345; Domain=site.example; Path=/Set-Cookie: __Host-SID=12345; Secure; Domain=site.example; Path=/¶
While the following would be accepted if set from a secure origin (e.g."https://site.example/"), and rejected otherwise:¶
Set-Cookie: __Host-SID=12345; Secure; Path=/¶
The user agent sends stored cookies to the origin server in the Cookie header.If the server conforms to the requirements inSection 4.1 (and the user agentconforms to the requirements inSection 5), the user agent will send a Cookieheader that conforms to the following grammar:¶
cookie-header = "Cookie:" SP cookie-stringcookie-string = cookie-pair *( ";" SP cookie-pair )¶
Each cookie-pair represents a cookie stored by the user agent. Thecookie-pair contains the cookie-name and cookie-value the user agentreceived in the Set-Cookie header.¶
Notice that the cookie attributes are not returned. In particular, the servercannot determine from the Cookie header alone when a cookie will expire, forwhich hosts the cookie is valid, for which paths the cookie is valid, orwhether the cookie was set with the Secure or HttpOnly attributes.¶
The semantics of individual cookies in the Cookie header are not defined bythis document. Servers are expected to imbue these cookies withapplication-specific semantics.¶
Although cookies are serialized linearly in the Cookie header, servers SHOULDNOT rely upon the serialization order. In particular, if the Cookie headercontains two cookies with the same name (e.g., that were set with differentPath or Domain attributes), servers SHOULD NOT rely upon the order in whichthese cookies appear in the header.¶
This section specifies the Cookie and Set-Cookie headers in sufficientdetail that a user agent implementing these requirements precisely caninteroperate with existing servers (even those that do not conform to thewell-behaved profile described inSection 4).¶
A user agent could enforce more restrictions than those specified herein (e.g.,for the sake of improved security); however, experiments have shown that suchstrictness reduces the likelihood that a user agent will be able to interoperatewith existing servers.¶
This section defines some algorithms used by user agents to process specificsubcomponents of the Cookie and Set-Cookie headers.¶
The user agent MUST use an algorithm equivalent to the following algorithm toparse a cookie-date. Note that the various boolean flags defined as a partof the algorithm (i.e., found-time, found-day-of-month, found-month,found-year) are initially "not set".¶
Using the grammar below, divide the cookie-date into date-tokens.¶
cookie-date = *delimiter date-token-list *delimiterdate-token-list = date-token *( 1*delimiter date-token )date-token = 1*non-delimiterdelimiter = %x09 / %x20-2F / %x3B-40 / %x5B-60 / %x7B-7Enon-delimiter = %x00-08 / %x0A-1F / DIGIT / ":" / ALPHA / %x7F-FFnon-digit = %x00-2F / %x3A-FFday-of-month = 1*2DIGIT [ non-digit *OCTET ]month = ( "jan" / "feb" / "mar" / "apr" / "may" / "jun" / "jul" / "aug" / "sep" / "oct" / "nov" / "dec" ) *OCTETyear = 2*4DIGIT [ non-digit *OCTET ]time = hms-time [ non-digit *OCTET ]hms-time = time-field ":" time-field ":" time-fieldtime-field = 1*2DIGIT¶
Process each date-token sequentially in the order the date-tokensappear in the cookie-date:¶
If the year-value is greater than or equal to 0 and less than or equal to69, increment the year-value by 2000.¶
Abort these steps and fail to parse the cookie-date if:¶
(Note that leap seconds cannot be represented in this syntax.)¶
A canonicalized host name is the string generated by the following algorithm:¶
A string domain-matches a given domain string if at least one of the followingconditions hold:¶
The user agent MUST use an algorithm equivalent to the following algorithm tocompute the default-path of a cookie:¶
A request-path path-matches a given cookie-path if at least one of thefollowing conditions holds:¶
The cookie-path and the request-path are identical.¶
Note that this differs from the rules in[RFC3986] for equivalence of thepath component, and hence two equivalent paths can have different cookies.¶
Two origins, A and B, are considered same-site if the following algorithmreturns true:¶
If A and B are both scheme/host/port triples:¶
Note: The port component of the origins is not considered.¶
A request is "same-site" if its target's URI's origin is same-site with therequest's client's "site for cookies" (which is an origin), or if the requesthas no client. The request is otherwise "cross-site".¶
The request's client's "site for cookies" is calculated depending upon itsclient's type, as described in the following subsections:¶
The URI displayed in a user agent's address bar is the only security contextdirectly exposed to users, and therefore the only signal users can reasonablyrely upon to determine whether or not they trust a particular website. Theorigin of that URI represents the context in which a user most likely believesthemselves to be interacting. We'll define this origin, the top-level browsingcontext's active document's origin, as the "top-level origin".¶
For a document displayed in a top-level browsing context, we can stop here: thedocument's "site for cookies" is the top-level origin.¶
For documents which are displayed in nested browsing contexts, we need to auditthe origins of each of a document's ancestor browsing contexts' active documentsin order to account for the "multiple-nested scenarios" described in Section 4of[RFC7034]. A document's "site for cookies" is the top-level origin if andonly if the top-level origin is same-site with the document's origin, and witheach of the document's ancestor documents' origins. Otherwise its "site forcookies" is an origin set to a globally unique identifier.¶
Given a Document (document
), the following algorithm returns its "site forcookies":¶
top-document
be the active document indocument
's browsing context'stop-level browsing context.¶top-origin
be the origin oftop-document
's URI iftop-document
'ssandboxed origin browsing context flag is set, andtop-document
's originotherwise.¶documents
be a list containingdocument
and each ofdocument
'sancestor browsing contexts' active documents.¶For eachitem
indocuments
:¶
top-origin
.¶Worker-driven requests aren't as clear-cut as document-driven requests, asthere isn't a clear link between a top-level browsing context and a worker.This is especially true for Service Workers[SERVICE-WORKERS], which mayexecute code in the background, without any document visible at all.¶
Note: The descriptions below assume that workers must be same-origin withthe documents that instantiate them. If this invariant changes, we'll need totake the worker's script's URI into account when determining their status.¶
Dedicated workers are simple, as each dedicated worker is bound to one and onlyone document. Requests generated from a dedicated worker (viaimportScripts
,XMLHttpRequest
,fetch()
, etc) define their "site for cookies" as thatdocument's "site for cookies".¶
Shared workers may be bound to multiple documents at once. As it is quitepossible for those documents to have distinct "site for cookies" values, theworker's "site for cookies" will be an origin set to a globally uniqueidentifier in cases where the values are not all same-site with the worker'sorigin, and the worker's origin in cases where the values agree.¶
Given a WorkerGlobalScope (worker
), the following algorithm returns its "sitefor cookies":¶
Service Workers are more complicated, as they act as a completely separateexecution context with only tangential relationship to the Document whichregistered them.¶
Requests which simply pass through a Service Worker will be handled as describedabove: the request's client will be the Document or Worker which initiated therequest, and its "site for cookies" will be those defined inSection 5.2.1 andSection 5.2.2.1¶
Requests which are initiated by the Service Worker itself (via a direct call tofetch()
, for instance), on the other hand, will have a client which is aServiceWorkerGlobalScope. Its "site for cookies" will be the Service Worker'sURI's origin.¶
Given a ServiceWorkerGlobalScope (worker
), the following algorithm returns its"site for cookies":¶
worker
's origin.¶When a user agent receives a Set-Cookie header field in an HTTP response, theuser agent MAY ignore the Set-Cookie header field in its entirety. Forexample, the user agent might wish to block responses to "third-party" requestsfrom setting cookies (seeSection 7.1).¶
If the user agent does not ignore the Set-Cookie header field in its entirety,the user agent MUST parse the field-value of the Set-Cookie header field as aset-cookie-string (defined below).¶
NOTE: The algorithm below is more permissive than the grammar inSection 4.1.For example, the algorithm strips leading and trailing whitespace from thecookie name and value (but maintains internal whitespace), whereas the grammarinSection 4.1 forbids whitespace in these positions. User agents use thisalgorithm so as to interoperate with servers that do not follow therecommendations inSection 4.¶
A user agent MUST use an algorithm equivalent to the following algorithm toparse a set-cookie-string:¶
If the set-cookie-string contains a %x3B (";") character:¶
Otherwise:¶
If the name-value-pair string lacks a %x3D ("=") character, then the namestring is empty, and the value string is the value of name-value-pair.¶
Otherwise, the name string consists of the characters up to, but notincluding, the first %x3D ("=") character, and the (possibly empty) valuestring consists of the characters after the first %x3D ("=") character.¶
The user agent MUST use an algorithm equivalent to the following algorithm toparse the unparsed-attributes:¶
If the remaining unparsed-attributes contains a %x3B (";") character:¶
Otherwise:¶
Let the cookie-av string be the characters consumed in this step.¶
If the cookie-av string contains a %x3D ("=") character:¶
Otherwise:¶
When the user agent finishes parsing the set-cookie-string, the user agent issaid to "receive a cookie" from the request-uri with name cookie-name,value cookie-value, and attributes cookie-attribute-list. (SeeSection 5.4for additional requirements triggered by receiving a cookie.)¶
If the attribute-name case-insensitively matches the string "Expires", theuser agent MUST process the cookie-av as follows.¶
If the attribute-name case-insensitively matches the string "Max-Age", theuser agent MUST process the cookie-av as follows.¶
If the attribute-name case-insensitively matches the string "Domain", the useragent MUST process the cookie-av as follows.¶
If the first character of the attribute-value string is %x2E ("."):¶
Otherwise:¶
If the attribute-name case-insensitively matches the string "Path", the useragent MUST process the cookie-av as follows.¶
If the attribute-value is empty or if the first character of theattribute-value is not %x2F ("/"):¶
Otherwise:¶
If the attribute-name case-insensitively matches the string "Secure", theuser agent MUST append an attribute to the cookie-attribute-list with anattribute-name of Secure and an empty attribute-value.¶
If the attribute-name case-insensitively matches the string "HttpOnly", theuser agent MUST append an attribute to the cookie-attribute-list with anattribute-name of HttpOnly and an empty attribute-value.¶
If the attribute-name case-insensitively matches the string "SameSite", theuser agent MUST process the cookie-av as follows:¶
enforcement
be "Default".¶enforcement
to "None".¶enforcement
to "Strict".¶enforcement
to "Lax".¶enforcement
.¶Note: This algorithm maps the "None" value, as well as any unknown value, tothe "None" behavior, which is helpful for backwards compatibility whenintroducing new variants.¶
Same-site cookies in "Strict" enforcement mode will not be sent along withtop-level navigations which are triggered from a cross-site document context.As discussed inSection 8.8.2, this might or might not be compatiblewith existing session management systems. In the interests of providing adrop-in mechanism that mitigates the risk of CSRF attacks, developers may settheSameSite
attribute in a "Lax" enforcement mode that carves out anexception which sends same-site cookies along with cross-site requests if andonly if they are top-level navigations which use a "safe" (in the[RFC7231]sense) HTTP method. (Note that a request's method may be changed from POSTto GET for some redirects (see sections 6.4.2 and 6.4.3 of[RFC7231]); in thesecases, a request's "safe"ness is determined based on the method of the currentredirect hop.)¶
Lax enforcement provides reasonable defense in depth against CSRF attacks thatrely on unsafe HTTP methods (likePOST
), but does not offer a robust defenseagainst CSRF as a general category of attack:¶
<link rel='prerender'>
[prerendering] can be exploitedto create "same-site" requests without the risk of user detection.¶When possible, developers should use a session management mechanism such asthat described inSection 8.8.2 to mitigate the risk of CSRF morecompletely.¶
The user agent stores the following fields about each cookie: name, value,expiry-time, domain, path, creation-time, last-access-time,persistent-flag, host-only-flag, secure-only-flag, http-only-flag,and same-site-flag.¶
When the user agent "receives a cookie" from a request-uri with namecookie-name, value cookie-value, and attributes cookie-attribute-list, theuser agent MUST process the cookie as follows:¶
If the cookie-attribute-list contains an attribute with an attribute-nameof "Max-Age":¶
Otherwise, if the cookie-attribute-list contains an attribute with anattribute-name of "Expires" (and does not contain an attribute with anattribute-name of "Max-Age"):¶
Otherwise:¶
If the cookie-attribute-list contains an attribute with anattribute-name of "Domain":¶
Otherwise:¶
If the user agent is configured to reject "public suffixes" and thedomain-attribute is a public suffix:¶
If the domain-attribute is identical to the canonicalizedrequest-host:¶
Otherwise:¶
NOTE: This step preventsattacker.example
from disrupting the integrity ofsite.example
by setting a cookie with a Domain attribute of "example".¶
If the domain-attribute is non-empty:¶
If the canonicalized request-host does not domain-match thedomain-attribute:¶
Otherwise:¶
Otherwise:¶
If the cookie's secure-only-flag is false, and the scheme component ofrequest-uri does not denote a "secure" protocol, then abort these steps andignore the cookie entirely if the cookie store contains one or more cookiesthat meet all of the following criteria:¶
Note: The path comparison is not symmetric, ensuring only that anewly-created, non-secure cookie does not overlay an existing securecookie, providing some mitigation against cookie-fixing attacks. That is,given an existing secure cookie named 'a' with a path of '/login', anon-secure cookie named 'a' could be set for a path of '/' or '/foo', butnot for a path of '/login' or '/login/en'.¶
If the cookie'ssame-site-flag
is not "None":¶
If the cookie was received from a request which is navigating atop-level browsing context[HTML] (e.g. if the request's "reservedclient" is eithernull
or an environment whose "target browsingcontext" is a top-level browing context), skip the remaining substepsand continue processing the cookie.¶
Note: Top-level navigations can create a cookie with anySameSite
value, even if the new cookie wouldn't have been sent along withthe request had it already existed prior to the navigation.¶
If the cookie-name begins with a case-sensitive match for the string"__Host-", abort these steps and ignore the cookie entirely unless thecookie meets all the following criteria:¶
If the cookie store contains a cookie with the same name, domain,host-only-flag, and path as the newly-created cookie:¶
A cookie is "expired" if the cookie has an expiry date in the past.¶
The user agent MUST evict all expired cookies from the cookie store if, at anytime, an expired cookie exists in the cookie store.¶
At any time, the user agent MAY "remove excess cookies" from the cookie storeif the number of cookies sharing a domain field exceeds someimplementation-defined upper bound (such as 50 cookies).¶
At any time, the user agent MAY "remove excess cookies" from the cookie storeif the cookie store exceeds some predetermined upper bound (such as 3000cookies).¶
When the user agent removes excess cookies from the cookie store, the useragent MUST evict cookies in the following priority order:¶
If two cookies have the same removal priority, the user agent MUST evict thecookie with the earliest last-access-time first.¶
When "the current session is over" (as defined by the user agent), the useragent MUST remove from the cookie store all cookies with the persistent-flagset to false.¶
The user agent includes stored cookies in the Cookie HTTP request header.¶
When the user agent generates an HTTP request, the user agent MUST NOT attachmore than one Cookie header field.¶
A user agent MAY omit the Cookie header in its entirety. For example, theuser agent might wish to block sending cookies during "third-party" requestsfrom setting cookies (seeSection 7.1).¶
If the user agent does attach a Cookie header field to an HTTP request, theuser agent MUST send the cookie-string (defined below) as the value of theheader field.¶
The user agent MUST use an algorithm equivalent to the following algorithm tocompute the cookie-string from a cookie store and a request-uri:¶
Let cookie-list be the set of cookies from the cookie store that meets allof the following requirements:¶
Either:¶
Or:¶
If the cookie's secure-only-flag is true, then the request-uri'sscheme must denote a "secure" protocol (as defined by the user agent).¶
NOTE: The notion of a "secure" protocol is not defined by this document.Typically, user agents consider a protocol secure if the protocol makesuse of transport-layer security, such as SSL or TLS. For example, mostuser agents consider "https" to be a scheme that denotes a secureprotocol.¶
If the cookie's same-site-flag is not "None", and the HTTP request iscross-site (as defined inSection 5.2) then exclude thecookie unless all of the following statements hold:¶
The user agent SHOULD sort the cookie-list in the following order:¶
NOTE: Not all user agents sort the cookie-list in this order, but this orderreflects common practice when this document was written, and, historically,there have been servers that (erroneously) depended on this order.¶
Serialize the cookie-list into a cookie-string by processing each cookiein the cookie-list in order:¶
NOTE: Despite its name, the cookie-string is actually a sequence of octets, nota sequence of characters. To convert the cookie-string (or componentsthereof) into a sequence of characters (e.g., for presentation to the user),the user agent might wish to try using the UTF-8 character encoding[RFC3629]to decode the octet sequence. This decoding might fail, however, because notevery sequence of octets is valid UTF-8.¶
Practical user agent implementations have limits on the number and size ofcookies that they can store. General-use user agents SHOULD provide each of thefollowing minimum capabilities:¶
Servers SHOULD use as few and as small cookies as possible to avoid reachingthese implementation limits and to minimize network bandwidth due to theCookie header being included in every request.¶
Servers SHOULD gracefully degrade if the user agent fails to return one or morecookies in the Cookie header because the user agent might evict any cookie atany time on orders from the user.¶
One reason the Cookie and Set-Cookie headers use such esoteric syntax isthat many platforms (both in servers and user agents) provide a string-basedapplication programming interface (API) to cookies, requiringapplication-layer programmers to generate and parse the syntax used by theCookie and Set-Cookie headers, which many programmers have done incorrectly,resulting in interoperability problems.¶
Instead of providing string-based APIs to cookies, platforms would bewell-served by providing more semantic APIs. It is beyond the scope of thisdocument to recommend specific API designs, but there are clear benefits toaccepting an abstract "Date" object instead of a serialized date string.¶
IDNA2008[RFC5890] supersedes IDNA2003[RFC3490]. However, there aredifferences between the two specifications, and thus there can be differencesin processing (e.g., converting) domain name labels that have been registeredunder one from those registered under the other. There will be a transitionperiod of some time during which IDNA2003-based domain name labels will existin the wild. User agents SHOULD implement IDNA2008[RFC5890] and MAYimplement[UTS46] or[RFC5895] in order to facilitate their IDNA transition.If a user agent does not implement IDNA2008, the user agent MUST implementIDNA2003[RFC3490].¶
Cookies are often criticized for letting servers track users. For example, anumber of "web analytics" companies use cookies to recognize when a user returnsto a web site or visits another web site. Although cookies are not the onlymechanism servers can use to track users across HTTP requests, cookiesfacilitate tracking because they are persistent across user agent sessions andcan be shared between hosts.¶
Particularly worrisome are so-called "third-party" cookies. In rendering an HTMLdocument, a user agent often requests resources from other servers (such asadvertising networks). These third-party servers can use cookies to track theuser even if the user never visits the server directly. For example, if a uservisits a site that contains content from a third party and then later visitsanother site that contains content from the same third party, the third partycan track the user between the two sites.¶
Given this risk to user privacy, some user agents restrict how third-partycookies behave, and those restrictions vary widly. For instance, user agentsmight block third-party cookies entirely by refusing to send Cookie headers orprocess Set-Cookie headers during third-party requests. They might take a lessdraconian approach by partitioning cookies based on the first-party context,sending one set of cookies to a given third party in one first-party context,and another to the same third party in another.¶
This document grants user agents wide latitude to experiment with third-partycookie policies that balance the privacy and compatibility needs of their users.However, this document does not endorse any particular third-party cookiepolicy.¶
Third-party cookie blocking policies are often ineffective at achieving theirprivacy goals if servers attempt to work around their restrictions to trackusers. In particular, two collaborating servers can often track users withoutusing cookies at all by injecting identifying information into dynamic URLs.¶
User agents SHOULD provide users with a mechanism for managing the cookiesstored in the cookie store. For example, a user agent might let users deleteall cookies received during a specified time period or all the cookies relatedto a particular domain. In addition, many user agents include a user interfaceelement that lets users examine the cookies stored in their cookie store.¶
User agents SHOULD provide users with a mechanism for disabling cookies. Whencookies are disabled, the user agent MUST NOT include a Cookie header inoutbound HTTP requests and the user agent MUST NOT process Set-Cookie headersin inbound HTTP responses.¶
Some user agents provide users the option of preventing persistent storage ofcookies across sessions. When configured thusly, user agents MUST treat allreceived cookies as if the persistent-flag were set to false. Some popularuser agents expose this functionality via "private browsing" mode[Aggarwal2010].¶
Some user agents provide users with the ability to approve individual writes tothe cookie store. In many common usage scenarios, these controls generate alarge number of prompts. However, some privacy-conscious users find thesecontrols useful nonetheless.¶
Although servers can set the expiration date for cookies to the distant future,most user agents do not actually retain cookies for multiple decades. Ratherthan choosing gratuitously long expiration periods, servers SHOULD promote userprivacy by selecting reasonable cookie expiration periods based on the purposeof the cookie. For example, a typical session identifier might reasonably beset to expire in two weeks.¶
Cookies have a number of security pitfalls. This section overviews a few of themore salient issues.¶
In particular, cookies encourage developers to rely on ambient authority forauthentication, often becoming vulnerable to attacks such as cross-site requestforgery[CSRF]. Also, when storing session identifiers in cookies, developersoften create session fixation vulnerabilities.¶
Transport-layer encryption, such as that employed in HTTPS, is insufficient toprevent a network attacker from obtaining or altering a victim's cookies becausethe cookie protocol itself has various vulnerabilities (see "Weak Confidentiality"and "Weak Integrity", below). In addition, by default, cookies do not provideconfidentiality or integrity from network attackers, even when used in conjunctionwith HTTPS.¶
A server that uses cookies to authenticate users can suffer securityvulnerabilities because some user agents let remote parties issue HTTP requestsfrom the user agent (e.g., via HTTP redirects or HTML forms). When issuingthose requests, user agents attach cookies even if the remote party does notknow the contents of the cookies, potentially letting the remote party exerciseauthority at an unwary server.¶
Although this security concern goes by a number of names (e.g., cross-siterequest forgery, confused deputy), the issue stems from cookies being a form ofambient authority. Cookies encourage server operators to separate designation(in the form of URLs) from authorization (in the form of cookies).Consequently, the user agent might supply the authorization for a resourcedesignated by the attacker, possibly causing the server or its clients toundertake actions designated by the attacker as though they were authorized bythe user.¶
Instead of using cookies for authorization, server operators might wish toconsider entangling designation and authorization by treating URLs ascapabilities. Instead of storing secrets in cookies, this approach storessecrets in URLs, requiring the remote entity to supply the secret itself.Although this approach is not a panacea, judicious application of theseprinciples can lead to more robust security.¶
Unless sent over a secure channel (such as TLS), the information in the Cookieand Set-Cookie headers is transmitted in the clear.¶
Servers SHOULD encrypt and sign the contents of cookies (using whatever formatthe server desires) when transmitting them to the user agent (even when sendingthe cookies over a secure channel). However, encrypting and signing cookiecontents does not prevent an attacker from transplanting a cookie from one useragent to another or from replaying the cookie at a later time.¶
In addition to encrypting and signing the contents of every cookie, servers thatrequire a higher level of security SHOULD use the Cookie and Set-Cookieheaders only over a secure channel. When using cookies over a secure channel,servers SHOULD set the Secure attribute (seeSection 4.1.2.5) for everycookie. If a server does not set the Secure attribute, the protectionprovided by the secure channel will be largely moot.¶
For example, consider a webmail server that stores a session identifier in acookie and is typically accessed over HTTPS. If the server does not set theSecure attribute on its cookies, an active network attacker can intercept anyoutbound HTTP request from the user agent and redirect that request to thewebmail server over HTTP. Even if the webmail server is not listening for HTTPconnections, the user agent will still include cookies in the request. Theactive network attacker can intercept these cookies, replay them against theserver, and learn the contents of the user's email. If, instead, the server hadset the Secure attribute on its cookies, the user agent would not haveincluded the cookies in the clear-text request.¶
Instead of storing session information directly in a cookie (where it might beexposed to or replayed by an attacker), servers commonly store a nonce (or"session identifier") in a cookie. When the server receives an HTTP requestwith a nonce, the server can look up state information associated with thecookie using the nonce as a key.¶
Using session identifier cookies limits the damage an attacker can cause if theattacker learns the contents of a cookie because the nonce is useful only forinteracting with the server (unlike non-nonce cookie content, which might itselfbe sensitive). Furthermore, using a single nonce prevents an attacker from"splicing" together cookie content from two interactions with the server, whichcould cause the server to behave unexpectedly.¶
Using session identifiers is not without risk. For example, the server SHOULDtake care to avoid "session fixation" vulnerabilities. A session fixation attackproceeds in three steps. First, the attacker transplants a session identifierfrom his or her user agent to the victim's user agent. Second, the victim usesthat session identifier to interact with the server, possibly imbuing thesession identifier with the user's credentials or confidential information.Third, the attacker uses the session identifier to interact with serverdirectly, possibly obtaining the user's authority or confidential information.¶
Cookies do not provide isolation by port. If a cookie is readable by a servicerunning on one port, the cookie is also readable by a service running on anotherport of the same server. If a cookie is writable by a service on one port, thecookie is also writable by a service running on another port of the same server.For this reason, servers SHOULD NOT both run mutually distrusting services ondifferent ports of the same host and use cookies to store security-sensitiveinformation.¶
Cookies do not provide isolation by scheme. Although most commonly used withthe http and https schemes, the cookies for a given host might also beavailable to other schemes, such as ftp and gopher. Although this lack ofisolation by scheme is most apparent in non-HTTP APIs that permit access tocookies (e.g., HTML's document.cookie API), the lack of isolation by schemeis actually present in requirements for processing cookies themselves (e.g.,consider retrieving a URI with the gopher scheme via HTTP).¶
Cookies do not always provide isolation by path. Although the network-levelprotocol does not send cookies stored for one path to another, some useragents expose cookies via non-HTTP APIs, such as HTML's document.cookie API.Because some of these user agents (e.g., web browsers) do not isolate resourcesreceived from different paths, a resource retrieved from one path might be ableto access cookies stored for another path.¶
Cookies do not provide integrity guarantees for sibling domains (and theirsubdomains). For example, consider foo.site.example and bar.site.example. Thefoo.site.example server can set a cookie with a Domain attribute of"site.example" (possibly overwriting an existing "site.example" cookie set bybar.site.example), and the user agent will include that cookie in HTTP requeststo bar.site.example. In the worst case, bar.site.example will be unable todistinguish this cookie from a cookie it set itself. The foo.site.exampleserver might be able to leverage this ability to mount an attack againstbar.site.example.¶
Even though the Set-Cookie header supports the Path attribute, the Pathattribute does not provide any integrity protection because the user agentwill accept an arbitrary Path attribute in a Set-Cookie header. Forexample, an HTTP response to a request for http://site.example/foo/bar can seta cookie with a Path attribute of "/qux". Consequently, servers SHOULD NOTboth run mutually distrusting services on different paths of the same host anduse cookies to store security-sensitive information.¶
An active network attacker can also inject cookies into the Cookie headersent to https://site.example/ by impersonating a response fromhttp://site.example/ and injecting a Set-Cookie header. The HTTPS serverat site.example will be unable to distinguish these cookies from cookies thatit set itself in an HTTPS response. An active network attacker might be ableto leverage this ability to mount an attack against site.example even ifsite.example uses HTTPS exclusively.¶
Servers can partially mitigate these attacks by encrypting and signing thecontents of their cookies. However, using cryptography does not mitigate theissue completely because an attacker can replay a cookie he or she received fromthe authentic site.example server in the user's session, with unpredictableresults.¶
Finally, an attacker might be able to force the user agent to delete cookies bystoring a large number of cookies. Once the user agent reaches its storagelimit, the user agent will be forced to evict some cookies. Servers SHOULD NOTrely upon user agents retaining cookies.¶
Cookies rely upon the Domain Name System (DNS) for security. If the DNS ispartially or fully compromised, the cookie protocol might fail to provide thesecurity properties required by applications.¶
"SameSite" cookies offer a robust defense against CSRF attack when deployed instrict mode, and when supported by the client. It is, however, prudent to ensurethat this designation is not the extent of a site's defense against CSRF, assame-site navigations and submissions can certainly be executed in conjunctionwith other attack vectors such as cross-site scripting.¶
Developers are strongly encouraged to deploy the usual server-side defenses(CSRF tokens, ensuring that "safe" HTTP methods are idempotent, etc) to mitigatethe risk more fully.¶
Additionally, client-side techniques such as those described in[app-isolation] may also prove effective against CSRF, and are certainly worthexploring in combination with "SameSite" cookies.¶
Setting theSameSite
attribute in "strict" mode provides robust defense indepth against CSRF attacks, but has the potential to confuse users unless sites'developers carefully ensure that their cookie-based session management systemsdeal reasonably well with top-level navigations.¶
Consider the scenario in which a user reads their email at MegaCorp Inc'swebmail providerhttps://site.example/
. They might expect that clicking on anemailed link tohttps://projects.example/secret/project
would show them the secretproject that they're authorized to see, but ifprojects.example
has marked theirsession cookies asSameSite
, then this cross-site navigation won't send themalong with the request.projects.example
will render a 404 error to avoid leakingsecret information, and the user will be quite confused.¶
Developers can avoid this confusion by adopting a session management system thatrelies on not one, but two cookies: one conceptually granting "read" access,another granting "write" access. The latter could be marked asSameSite
, andits absence would prompt a reauthentication step before executing anynon-idempotent action. The former could drop theSameSite
attribute entirely,or choose the "Lax" version of enforcement, in order to allow users access todata via top-level navigation.¶
TheSameSite
attribute is inappropriate for some important use-cases. Inparticular, note that content intended for embedding in a cross-site contexts(social networking widgets or commenting services, for instance) will not haveaccess to same-site cookies. Cookies may be required for requests triggered inthese cross-site contexts in order to provide seamless functionality that relieson a user's state.¶
Likewise, some forms of Single-Sign-On might require cookie-based authenticationin a cross-site context; these mechanisms will not function as intended withsame-site cookies.¶
SameSite cookies in and of themselves don't do anything to address thegeneral privacy concerns outlined in Section 7.1 of[RFC6265]. The "SameSite"attribute is set by the server, and serves to mitigate the risk of certain kindsof attacks that the server is worried about. The user is not involved in thisdecision. Moreover, a number of side-channels exist which could allow a serverto link distinct requests even in the absence of cookies (for example, connectionand/or socket pooling between same-site and cross-site requests).¶
The permanent message header field registry (see[RFC3864]) needs to beupdated with the following registration:¶
The permanent message header field registry (see[RFC3864]) needs to beupdated with the following registration:¶
The "Cookie Attribute Registry" defines the name space of attribute used tocontrol cookies' behavior. The registry is maintained athttps://www.iana.org/assignments/cookie-attribute-names.¶
Each registered attribute name is associated with a description, and areference detailing how the attribute is to be processed and stored.¶
New registrations happen on a "RFC Required" basis (see Section 4.7 of[RFC8126]). The attribute to be registered MUST match theextension-av
syntax defined inSection 4.1.1. Note that attribute names are generallydefined in CamelCase, but technically accepted case-insensitively.¶
The "Cookie Attribute Registry" will be updated with the registrations below:¶
Name | Reference |
---|---|
Domain | Section 4.1.2.3 of this document |
Expires | Section 4.1.2.1 of this document |
HttpOnly | Section 4.1.2.6 of this document |
Max-Age | Section 4.1.2.2 of this document |
Path | Section 4.1.2.4 of this document |
SameSite | Section 4.1.2.7 of this document |
Secure | Section 4.1.2.5 of this document |
Fixes to formatting caused by mistakes in the initial port to Markdown:¶
path-value
andextension-av
grammar, errata 4148 by updating theday-of-month
,year
, andtime
grammar, and errata 3663 by adding the requested note.https://www.rfc-editor.org/errata_search.php?rfc=6265¶Cookie2
andSet-Cookie2
from the IANA Considerations section:https://github.com/httpwg/http-extensions/issues/247¶__Secure-
and__Host-
cookie name prefix processing instructions.¶SameSite
attribute.¶Closed a number of editorial bugs:¶
__Host-
prefix requires an explicitPath
attribute:https://github.com/httpwg/http-extensions/issues/222¶host-only-flag
when calculating its uniqueness:https://github.com/httpwg/http-extensions/issues/199¶SameSite
cookies to be set for all top-level navigations.https://github.com/httpwg/http-extensions/issues/594¶Set-Cookie: token
as creating the cookie("", "token")
:https://github.com/httpwg/http-extensions/issues/159¶Set-Cookie: =
andSet-Cookie:
:https://github.com/httpwg/http-extensions/issues/159¶SameSite
attributes in a cookie string:https://github.com/httpwg/http-extensions/issues/901¶cookie-pair
and theCookie
headerproduction:https://github.com/httpwg/http-extensions/issues/1074,https://github.com/httpwg/http-extensions/issues/1119.¶same-site-flag
, equivalent to"SameSite=Lax":https://github.com/httpwg/http-extensions/pull/1325.¶RFC 6265 was written by Adam Barth. This document is a minor update ofRFC 6265, adding small features, and aligning the specification with thereality of today's deployments. Here, we're standing upon the shouldersof a giant since the majority of the text is still Adam's.¶
draft-ietf-httpbis-rfc6265bis-07
Document | Document type | This is an older version of an Internet-Draft whose latest revision state is "Active". | |
---|---|---|---|
Select version | |||
Compare versions | |||
Authors | Mike West,John Wilander | ||
Replaces | draft-ietf-httpbis-cookie-prefixes draft-thomson-http-omnomnom draft-ietf-httpbis-cookie-same-site draft-ietf-httpbis-cookie-alone | ||
RFC stream | |||
Other formats | |||
Additional resources | Mailing list discussion |