HTTP cookie

HTTP cookies(also calledweb cookies,Internet cookies,browser cookies, or simplycookies) are small blocks ofdatacreated by aweb serverwhile auserisbrowsingawebsiteand placed on the user's computer or other device by the user'sweb browser. Cookies are placed on the device used to access a website, and more than one cookie may be placed on a user's device during a session.
Cookies serve useful and sometimes essential functions on theweb. They enable web servers to storestatefulinformation (such as items added in the shopping cart in anonline store) on the user's device or to track the user's browsing activity (including clicking particular buttons,logging in, or recording whichpages were visited in the past).They can also be used to save information that the user previously entered intoform fields, such as names, addresses,passwords, andpayment card numbersfor subsequent use.
Authentication cookiesare commonly used by web servers toauthenticatethat a user is logged in, and with whichaccountthey are logged in. Without the cookie, users would need to authenticate themselves by logging in on each page containing sensitive information that they wish to access. The security of an authentication cookie generally depends on the security of the issuing website and the user's web browser, and on whether the cookie data isencrypted.Security vulnerabilitiesmay allow a cookie's data to be read by anattacker, used to gain access touser data, or used to gain access (with the user's credentials) to the website to which the cookie belongs (seecross-site scriptingandcross-site request forgeryfor examples).
Tracking cookies, and especiallythird-party tracking cookies, are commonly used as ways to compile long-term records of individuals'browsing histories— a potentialprivacy concernthat prompted Europeanand U.S. lawmakers to take action in 2011.European law requires that all websites targetingEuropean Unionmember states gain "informed consent" from users before storing non-essential cookies on their device.
The termcookiewas coined by web-browser programmerLou Montulli. It was derived from the termmagic cookie, which is a packet of data a program receives and sends back unchanged, used byUnixprogrammers.
Magic cookies were already used in computing when computer programmerLou Montullihad the idea of using them in web communications in June 1994.At the time, he was an employee ofNetscape Communications, which was developing ane-commerceapplication forMCI.Vint CerfandJohn Klensinrepresented MCI in technical discussions with Netscape Communications. MCI did not want its servers to have to retain partial transaction states, which led them to ask Netscape to find a way to store that state in each user's computer instead. Cookies provided a solution to the problem of reliably implementing avirtual shopping cart.
Together with John Giannandrea, Montulli wrote the initial Netscape cookie specification the same year. Version 0.9beta ofMosaic Netscape, released on October 13, 1994,supported cookies.The first use of cookies (out of the labs) was checking whether visitors to the Netscape website had already visited the site. Montulli applied for a patent for the cookie technology in 1995, which was granted in 1998.Support for cookies was integrated withInternet Explorerin version 2, released in October 1995.
The introduction of cookies was not widely known to the public at the time. In particular, cookies were accepted by default, and users were not notified of their presence.The public learned about cookies after theFinancial Timespublished an article about them on February 12, 1996.In the same year, cookies received a lot of media attention, especially because of potential privacy implications. Cookies were discussed in two U.S.Federal Trade Commissionhearings in 1996 and 1997.
The development of the formal cookie specifications was already ongoing. In particular, the first discussions about a formal specification started in April 1995 on the www-talkmailing list. A special working group within theInternet Engineering Task Force(IETF) was formed. Two alternative proposals for introducing state in HTTP transactions had been proposed byBrian Behlendorfand David Kristol respectively. But the group, headed by Kristol himself and Lou Montulli, soon decided to use the Netscape specification as a starting point. In February 1996, the working group identified third-party cookies as a considerable privacy threat. The specification produced by the group was eventually published as RFC 2109 in February 1997. It specifies that third-party cookies were either not allowed at all, or at least not enabled by default.At this time, advertising companies were already using third-party cookies. The recommendation about third-party cookies of RFC 2109 was not followed by Netscape and Internet Explorer. RFC 2109 was superseded by RFC 2965 in October 2000.
RFC 2965 added aSet-Cookie2header field, which informally came to be called "RFC 2965-style cookies" as opposed to the originalSet-Cookieheader field which was called "Netscape-style cookies".Set-Cookie2was seldom used, however, and wasdeprecatedin RFC 6265 in April 2011 which was written as a definitive specification for cookies as used in the real world.No modern browser recognizes theSet-Cookie2header field.
Asession cookie(also known as anin-memory cookie,transient cookieornon-persistent cookie) exists only in temporary memory while the user navigates a website.Session cookies expire or are deleted when the user closes the web browser.Session cookies are identified by the browser by the absence of an expiration date assigned to them.
Apersistent cookieexpires at a specific date or after a specific length of time. For the persistent cookie's lifespan set by its creator, its information will be transmitted to the server every time the user visits the website that it belongs to, or every time the user views a resource belonging to that website from another website (such as an advertisement).
For this reason, persistent cookies are sometimes referred to astracking cookiesbecause they can be used by advertisers to record information about a user's web browsing habits over an extended period of time. Persistent cookies are also used for reasons such as keeping users logged into their accounts on websites, to avoid re-entering login credentials at every visit.(See§ Uses, below.)
Asecure cookiecan only be transmitted over an encrypted connection (i.e.HTTPS). They cannot be transmitted over unencrypted connections (i.e.HTTP). This makes the cookie less likely to be exposed to cookie theft viaeavesdropping. A cookie is made secure by adding theSecureflag to the cookie.
Anhttp-only cookiecannot be accessed by client-side APIs, such asJavaScript. This restriction eliminates the threat of cookie theft viacross-site scripting(XSS).However, the cookie remains vulnerable tocross-site tracing(XST) andcross-site request forgery(CSRF) attacks. A cookie is given this characteristic by adding theHttpOnlyflag to the cookie.
In 2016Google Chromeversion 51 introduceda new kind of cookie with attributeSameSitewith possible values ofStrict,LaxorNone.With attributeSameSite=Strict, the browsers would only send cookies to a target domain that is the same as the origin domain. This would effectively mitigatecross-site request forgery(CSRF) attacks. WithSameSite=Lax, browsers would send cookies with requests to a target domain even it is different from the origin domain, but only forsaferequests such as GET (POST is unsafe) and not third-party cookies (inside iframe). AttributeSameSite=Nonewould allow third-party (cross-site) cookies, however, most browsers requiresecure attributeon SameSite=None cookies.
The Same-site cookie is incorporated into a new RFC draft for "Cookies: HTTP State Management Mechanism"to update RFC 6265 (if approved).
Chrome, Firefox, and Edge started to support Same-site cookies.The key of rollout is the treatment of existing cookies without the SameSite attribute defined, Chrome has been treating those existing cookies as if SameSite=None, this would let all website/applications run as before. Google intended to change that default toSameSite=Laxin Chrome 80 planned to be released in February 2020,but due to potential for breakage of those applications/websites that rely on third-party/cross-site cookies andCOVID-19circumstances, Google postponed this change to Chrome 84.
Asupercookieis a cookie with an origin of atop-level domain(such as.com) or a public suffix (such as.co.uk). Ordinary cookies, by contrast, have an origin of a specific domain name, such asexample.com.
Supercookies can be a potential security concern and are therefore often blocked by web browsers. If unblocked by the browser, an attacker in control of a malicious website could set a supercookie and potentially disrupt or impersonate legitimate user requests to another website that shares the same top-level domain or public suffix as the malicious website. For example, a supercookie with an origin of.com, could maliciously affect a request made toexample.com, even if the cookie did not originate fromexample.com. This can be used to fake logins or change user information.
ThePublic Suffix Listhelps to mitigate the risk that supercookies pose. The Public Suffix List is a cross-vendor initiative that aims to provide an accurate and up-to-date list of domain name suffixes. Older versions of browsers may not have an up-to-date list, and will therefore be vulnerable to supercookies from certain domains.
The termsupercookieis sometimes used for tracking technologies that do not rely on HTTP cookies. Two suchsupercookiemechanisms were found on Microsoft websites in August 2011:cookie syncingthat respawned MUID (machine unique identifier) cookies, andETagcookies.Due to media attention, Microsoft later disabled this code.In a 2021 blog post, Mozilla used the termsupercookieto refer tothe use of browser cacheas a means of tracking users across sites.
Azombie cookieis data and code that has been placed by aweb serveron a visitor's computer or other device in a hidden location outside the visitor'sweb browser's dedicated cookie storage location, and that automatically recreates a HTTP cookie as a regular cookie after the original cookie had been deleted. The zombie cookie may be stored in multiple locations, such asFlash Local shared object,HTML5 Web storage, and other client-side and even server-side locations, and when absence is detected in one of the locations, the missing instance is recreated by the JavaScript code using the data stored in other locations.
A cookie wall pops up on a website and informs the user of the website's cookie usage. It has no reject option, and the website is not accessible without tracking cookies.
A cookie consists of the following components:
Cookies were originally introduced to provide a way for users to record items they want to purchase as they navigate throughout a website (a virtualshopping cartorshopping basket).Today, however, the contents of a user's shopping cart are usually stored in a database on the server, rather than in a cookie on the client. To keep track of which user is assigned to which shopping cart, the server sends a cookie to the client that contains aunique session identifier(typically, a long string of random letters and numbers). Because cookies are sent to the server with every request the client makes, that session identifier will be sent back to the server every time the user visits a new page on the website, which lets the server know which shopping cart to display to the user.
Another popular use of cookies is for logging into websites. When the user visits a website's login page, the web server typically sends the client a cookie containing a unique session identifier. When the user successfully logs in, the server remembers that that particular session identifier has been authenticated and grants the user access to its services.
Because session cookies only contain a unique session identifier, this makes the amount of personal information that a website can save about each user virtually limitless—the website is not limited to restrictions concerning how large a cookie can be. Session cookies also help to improve page load times, since the amount of information in a session cookie is small and requires little bandwidth.
Cookies can be used to remember information about the user in order to show relevant content to that user over time. For example, a web server might send a cookie containing the username that was last used to log into a website, so that it may be filled in automatically the next time the user logs in.
Many websites use cookies for personalization based on the user's preferences. Users select their preferences by entering them in a web form and submitting the form to the server. The server encodes the preferences in a cookie and sends the cookie back to the browser. This way, every time the user accesses a page on the website, the server can personalize the page according to the user's preferences. For example, theGooglesearch engine once used cookies to allow users (even non-registered ones) to decide how many search results per page they wanted to see.
Also,DuckDuckGouses cookies to allow users to set the viewing preferences like colors of the web page.
Tracking cookies are used to track users' web browsing habits. This can also be done to some extent by using theIP addressof the computer requesting the page or therefererfield of theHTTPrequest header, but cookies allow for greater precision. This can be demonstrated as follows:
By analyzing this log file, it is then possible to find out which pages the user has visited, in what sequence, and for how long.
Corporations exploit users' web habits by tracking cookies to collect information about buying habits. TheWall Street Journalfound that America's top fifty websites installed an average of sixty-four pieces of tracking technology onto computers, resulting in a total of 3,180 tracking files.The data can then be collected and sold to bidding corporations.
Cookies are arbitrary pieces of data, usually chosen and first sent by the web server, and stored on the client computer by the web browser. The browser then sends them back to the server with every request, introducingstates(memory of previous events) into otherwise statelessHTTPtransactions. Without cookies, each retrieval of aweb pageor component of a web page would be an isolated event, largely unrelated to all other page views made by the user on the website. Although cookies are usually set by the web server, they can also be set by the client using a scripting language such asJavaScript(unless the cookie'sHttpOnlyflag is set, in which case the cookie cannot be modified by scripting languages).
The cookie specificationsrequire that browsers meet the following requirements in order to support cookies:
Cookies are set using theSet-Cookieheader field, sent in an HTTP response from the web server. This header field instructs the web browser to store the cookie and send it back in future requests to the server (the browser will ignore this header field if it does not support cookies or has disabled cookies).
As an example, the browser sends its first HTTP request for the homepage of thewww.example.orgwebsite:
The server responds with twoSet-Cookieheader fields:
The server's HTTP response contains the contents of the website's homepage. But it also instructs the browser to set two cookies. The first,theme, is considered to be asession cookiesince it does not have anExpiresorMax-Ageattribute. Session cookies are intended to be deleted by the browser when the browser closes. The second,sessionToken, is considered to be apersistent cookiesince it contains anExpiresattribute, which instructs the browser to delete the cookie at a specific date and time.
Next, the browser sends another request to visit thespec.htmlpage on the website. This request contains aCookieheader field, which contains the two cookies that the server instructed the browser to set:
This way, the server knows that this HTTP request is related to the previous one. The server would answer by sending the requested page, possibly including moreSet-Cookieheader fields in the HTTP response in order to instruct the browser to add new cookies, modify existing cookies, or remove existing cookies. To remove a cookie, the server must include aSet-Cookieheader field with an expiration date in the past.
The value of a cookie may consist of any printableASCIIcharacter (!through~,Unicode\u0021through\u007E) excluding,and;andwhitespace characters. The name of a cookie excludes the same characters, as well as=, since that is the delimiter between the name and value. The cookie standard RFC 2965 is more restrictive but not implemented by browsers.
The termcookie crumbis sometimes used to refer to a cookie's name–value pair.
Cookies can also be set by scripting languages such asJavaScriptthat run within the browser. In JavaScript, the objectdocument.cookieis used for this purpose. For example, the instructiondocument.cookie = "temperature=20"creates a cookie of nametemperatureand value20.
In addition to a name and value, cookies can also have one or more attributes. Browsers do not include cookie attributes in requests to the server—they only send the cookie's name and value. Cookie attributes are used by browsers to determine when to delete a cookie, block a cookie or whether to send a cookie to the server.
TheDomainandPathattributes define the scope of the cookie. They essentially tell the browser what website the cookie belongs to. For security reasons, cookies can only be set on the current resource's top domain and its subdomains, and not for another domain and its subdomains. For example, the websiteexample.orgcannot set a cookie that has a domain offoo.combecause this would allow the websiteexample.orgto control the cookies of the domainfoo.com.
If a cookie'sDomainandPathattributes are not specified by the server, they default to the domain and path of the resource that was requested.However, in most browsers there is a difference between a cookie set fromfoo.comwithout a domain, and a cookie set with thefoo.comdomain. In the former case, the cookie will only be sent for requests tofoo.com, also known as a host-only cookie. In the latter case, all subdomains are also included (for example,docs.foo.com).A notable exception to this general rule is Edge prior to Windows 10 RS3 and Internet Explorer prior to IE 11 and Windows 10 RS4 (April 2018), which always sends cookies to subdomains regardless of whether the cookie was set with or without a domain.
Below is an example of someSet-Cookieheader fields in the HTTP response of a website after a user logged in. The HTTP request was sent to a webpage within thedocs.foo.comsubdomain:
The first cookie,LSID, has noDomainattribute, and has aPathattribute set to/accounts. This tells the browser to use the cookie only when requesting pages contained indocs.foo.com/accounts(the domain is derived from the request domain). The other two cookies,HSIDandSSID, would be used when the browser requests any subdomain in.foo.comon any path (for examplewww.foo.com/bar). The prepending dot is optional in recent standards, but can be added for compatibility with RFC 2109 based implementations.
TheExpiresattribute defines a specific date and time for when the browser should delete the cookie. The date and time are specified in the formWdy, DD Mon YYYY HH:MM:SS GMT, or in the formWdy, DD Mon YY HH:MM:SS GMTfor values of YY where YY is greater than or equal to 0 and less than or equal to 69.
Alternatively, theMax-Ageattribute can be used to set the cookie's expiration as an interval of seconds in the future, relative to the time the browser received the cookie. Below is an example of threeSet-Cookieheader fields that were received from a website after a user logged in:
The first cookie,lu, is set to expire sometime on 15 January 2013. It will be used by the client browser until that time. The second cookie,made_write_conn, does not have an expiration date, making it a session cookie. It will be deleted after the user closes their browser. The third cookie,reg_fb_gate, has its value changed todeleted, with an expiration time in the past. The browser will delete this cookie right away because its expiration time is in the past. Note that cookie will only be deleted if the domain and path attributes in theSet-Cookiefield match the values used when the cookie was created.
As of 2016Internet Explorer did not supportMax-Age.
TheSecureandHttpOnlyattributes do not have associated values. Rather, the presence of just their attribute names indicates that their behaviors should be enabled.
TheSecureattribute is meant to keep cookie communication limited to encrypted transmission, directing browsers to use cookies only viasecure/encryptedconnections. However, if a web server sets a cookie with a secure attribute from a non-secure connection, the cookie can still be intercepted when it is sent to the user byman-in-the-middle attacks. Therefore, for maximum security, cookies with the Secure attribute should only be set over a secure connection.
TheHttpOnlyattribute directs browsers not to expose cookies through channels other than HTTP (and HTTPS) requests. This means that the cookie cannot be accessed via client-side scripting languages (notablyJavaScript), and therefore cannot be stolen easily viacross-site scripting(a pervasive attack technique).
Most modern browsers support cookies and allow the user to disable them. The following are common options:
Add-on tools for managing cookie permissions also exist.
Cookies have some important implications for the privacy and anonymity of web users. While cookies are sent only to the server setting them or a server in the same Internet domain, a web page may contain images or other components stored on servers in other domains. Cookies that are set during retrieval of these components are calledthird-party cookies. A third-party cookie, belongs to a domain different from the one shown in the address bar. This sort of cookie typically appears when web pages feature content from external websites, such asbanner advertisements. This opens up the potential fortrackingthe user's browsing history and is used by advertisers toserve relevant advertisementsto each user.
As an example, suppose a user visitswww.example.org. This website contains an advertisement fromad.foxytracking.com, which, when downloaded, sets a cookie belonging to the advertisement's domain (ad.foxytracking.com). Then, the user visits another website,www.foo.com, which also contains an advertisement fromad.foxytracking.comand sets a cookie belonging to that domain (ad.foxytracking.com). Eventually, both of these cookies will be sent to the advertiser when loading their advertisements or visiting their website. The advertiser can then use these cookies to build up a browsing history of the user across all the websites that have ads from this advertiser, through the use of theHTTP refererheader field.
As of 2014, some websites were setting cookies readable for over 100 third-party domains.On average, a single website was setting 10 cookies, with a maximum number of cookies (first- and third-party) reaching over 800.
The older standards for cookies, RFC 2109and RFC 2965, recommend that browsers should protect user privacy and not allow sharing of cookies between servers by default. However, the newer standard, RFC 6265, explicitly allows user agents to implement whichever third-party cookie policy they wish. Most modern web browsers containprivacy settingsthat canblockthird-party cookies. Since 2020,Apple Safari,Firefox,andBraveblock all third-party cookies by default. Safari allows embedded sites to use Storage Access API to request permission to set first-party cookies. In May 2020,Google Chrome83 introduced new features to block third-party cookies by default in its Incognito mode for private browsing, making blocking optional during normal browsing. The same update also added an option to block first-party cookies.In April 2024, Chrome postponed third-party cookie blocking by default to 2025.In July 2024, Google announced plan to avoid blocking third-party cookies by default and instead prompt users to allow third-party cookies.
The possibility of building a profile of users is a privacy threat, especially when tracking is done across multiple domains using third-party cookies. For this reason, some countries have legislation about cookies.
Website operators who do not disclose third-party cookie use to consumers run the risk of harming consumer trust if cookie use is discovered. Having clear disclosure (such as in aprivacy policy) tends to eliminate any negative effects of such cookie discovery.
TheUnited Statesgovernment has set strict rules on setting cookies in 2000 after it was disclosed that the White Housedrug policy officeused cookies to track computer users viewing its online anti-drug advertising. In 2002, privacy activist Daniel Brandt found that theCIAhad been leaving persistent cookies on computers that had visited its website. When notified it was violating policy, CIA stated that these cookies were not intentionally set and stopped setting them. On December 25, 2005, Brandt discovered that theNational Security Agency(NSA) had been leaving two persistent cookies on visitors' computers due to a software upgrade. After being informed, the NSA immediately disabled the cookies.
In 2002, the European Union launched theDirective on Privacy and Electronic Communications(e-Privacy Directive), a policy requiring end users' consent for the placement of cookies, and similar technologies for storing and accessing information on users' equipment.In particular, Article 5 Paragraph 3 mandates that storing technically unnecessary data on a user's computer can only be done if the user is provided information about how this data is used, and the user is given the possibility of denying this storage operation. The Directive does not require users to authorise or be provided notice of cookie usage that are functionally required for delivering a service they have requested, for example to retain settings, store log-in sessions, or remember what is in a user's shopping basket.
In 2009, the law was amended by Directive 2009/136/EC, which included a change to Article 5, Paragraph 3. Instead of having an option for users to opt out of cookie storage, the revised Directive requires consent to be obtained for cookie storage.The definition of consent is cross-referenced to the definition in European data protection law, firstly the Data Protection Directive 1995 and subsequently theGeneral Data Protection Regulation(GDPR). As the definition of consent was strengthened in the text of the GDPR, this had the effect of increasing the quality of consent required by those storing and accessing information such as cookies on users devices. In a case decided under the Data Protection Directive however, theCourt of Justice of the European Unionlater confirmed however that the previous law implied the same strong quality of consent as the current instrument.In addition to the requirement of consent which stems from storing or accessing information on a user's terminal device, the information in many cookies will be considered personal data under the GDPR alone, and will require a legal basis to process. This has been the case since the 1995 Data Protection Directive, which used an identical definition of personal data, although the GDPR in interpretative Recital 30 clarifies that cookie identifiers are included. While not all data processing under the GDPR requires consent, the characteristics of behavioural advertising mean that it is difficult or impossible to justify under any other ground.
Consent under the combination of the GDPR and e-Privacy Directive has to meet a number of conditions in relation to cookies.It must be freely given and unambiguous: preticked boxes were banned under both the Data Protection Directive 1995and the GDPR (Recital 32).The GDPR is specific that consent must be as 'easy to withdraw as to give',meaning that a reject-all button must be as easy to access in terms of clicks and visibility as an 'accept all' button.It must be specific and informed, meaning that consent relates to particular purposes for the use of this data, and all organisations seeking to use this consent must be specifically named.TheCourt of Justice of the European Unionhas also ruled that consent must be 'efficient and timely', meaning that it must be gained before cookies are laid and data processing begins instead of afterwards.
The industry's response has been largely negative. Robert Bond of the law firm Speechly Bircham describes the effects as "far-reaching and incredibly onerous" for "all UK companies". Simon Davis ofPrivacy Internationalargues that proper enforcement would "destroy the entire industry".However, scholars note that the onerous nature of cookie pop-ups stems from an attempt to continue to operate a business model through convoluted requests that may be incompatible with the GDPR.
Academic studies and regulators both describe widespread non-compliance with the law. A study scraping 10,000 UK websites found that only 11.8% of sites adhered to minimal legal requirements, with only 33.4% of websites studied providing a mechanism to reject cookies that was as easy to use as accepting them.A study of 17,000 websites found that 84% of sites breached this criterion, finding additionally that many laid third party cookies with no notice at all.The UK regulator, theInformation Commissioner's Office, stated in 2019 that the industry's 'Transparency and Consent Framework' from the advertising technology group theInteractive Advertising Bureauwas 'insufficient to ensure transparency and fair processing of the personal data in question and therefore also insufficient to provide for free and informed consent, with attendant implications for PECR [e-Privacy] compliance.'Many companies that sell compliance solutions (Consent Management Platforms) permit them to be configured in manifestly illegal ways, which scholars have noted creates questions around the appropriate allocation of liability.
AW3Cspecification calledP3Pwas proposed for servers to communicate their privacy policy to browsers, allowing automatic, user-configurable handling. However, few websites implement the specification, and the W3C has discontinued work on the specification.
Third-party cookies can be blocked by most browsers to increase privacy and reduce tracking by advertising and tracking companies without negatively affecting the user's web experience on all sites. Some sites operate 'cookie walls', which make access to a site conditional on allowing cookies either technically in a browser, through pressing 'accept', or both.In 2020, theEuropean Data Protection Board, composed of all EU data protection regulators, stated that cookie walls were illegal.
Many advertising operators have an opt-out option to behavioural advertising, with a generic cookie in the browser stopping behavioural advertising.However, this is often ineffective against many forms of tracking, such as first-party tracking that is growing in popularity to avoid the impact of browsers blocking third party cookies.Furthermore, if such a setting is more difficult to place than the acceptance of tracking, it remains in breach of the conditions of the e-Privacy Directive.
Most websites use cookies as the only identifiers for user sessions, because other methods of identifying web users have limitations and vulnerabilities. If a website uses cookies as session identifiers, attackers can impersonate users' requests by stealing a full set of victims' cookies. From the web server's point of view, a request from an attacker then has the same authentication as the victim's requests; thus the request is performed on behalf of the victim's session.
Listed here are various scenarios of cookie theft and user session hijacking (even without stealing user cookies) that work with websites relying solely on HTTP cookies for user identification.
Traffic on a network can be intercepted and read by computers on the network other than the sender and receiver (particularly overunencryptedopenWi-Fi). This traffic includes cookies sent on ordinary unencryptedHTTP sessions. Where network traffic is not encrypted, attackers can therefore read the communications of other users on the network, including HTTP cookies as well as the entire contents of the conversations, for the purpose of aman-in-the-middle attack.
An attacker could use intercepted cookies to impersonate a user and perform a malicious task, such as transferring money out of the victim's bank account.
This issue can be resolved by securing the communication between the user's computer and the server by employingTransport Layer Security(HTTPSprotocol) to encrypt the connection. A server can specify theSecureflag while setting a cookie, which will cause the browser to send the cookie only over an encrypted channel, such as a TLS connection.
If an attacker is able to cause aDNS serverto cache a fabricated DNS entry (calledDNS cache poisoning), then this could allow the attacker to gain access to a user's cookies. For example, an attacker could use DNS cache poisoning to create a fabricated DNS entry off12345.www.example.comthat points to theIP addressof the attacker's server. The attacker can then post an image URL from his own server (for example,http://f12345.www.example.com/img_4_cookie.jpg). Victims reading the attacker's message would download this image fromf12345.www.example.com. Sincef12345.www.example.comis a sub-domain ofwww.example.com, victims' browsers would submit allexample.com-related cookies to the attacker's server.
If an attacker is able to accomplish this, it is usually the fault of theInternet Service Providersfor not properly securing their DNS servers. However, the severity of this attack can be lessened if the target website uses secure cookies. In this case, the attacker would have the extra challengeof obtaining the target website's TLS certificate from acertificate authority, since secure cookies can only be transmitted over an encrypted connection. Without a matching TLS certificate, victims' browsers would display a warning message about the attacker's invalid certificate, which would help deter users from visiting the attacker's fraudulent website and sending the attacker their cookies.
Cookies can also be stolen using a technique called cross-site scripting. This occurs when an attacker takes advantage of a website that allows its users to post unfilteredHTMLandJavaScriptcontent. By posting malicious HTML and JavaScript code, the attacker can cause the victim's web browser to send the victim's cookies to a website the attacker controls.
As an example, an attacker may post a message onwww.example.comwith the following link:
When another user clicks on this link, the browser executes the piece of code within theonclickattribute, thus replacing the stringdocument.cookiewith the list of cookies that are accessible from the current page. As a result, this list of cookies is sent to theattacker.comserver. If the attacker's malicious posting is on an HTTPS websitehttps://www.example.com, secure cookies will also be sent to attacker.com in plain text.
It is the responsibility of the website developers to filter out such malicious code.
Such attacks can be mitigated by using HttpOnly cookies. These cookies will not be accessible by client-side scripting languages like JavaScript, and therefore, the attacker will not be able to gather these cookies.
In older versions of many browsers, there were security holes in the implementation of theXMLHttpRequestAPI. This API allows pages to specify a proxy server that would get the reply, and this proxy server is not subject to thesame-origin policy. For example, a victim is reading an attacker's posting onwww.example.com, and the attacker's script is executed in the victim's browser. The script generates a request towww.example.comwith the proxy serverattacker.com. Since the request is forwww.example.com, allexample.comcookies will be sent along with the request, but routed through the attacker's proxy server. Hence, the attacker would be able to harvest the victim's cookies.
This attack would not work with secure cookies, since they can only be transmitted overHTTPSconnections, and the HTTPS protocol dictatesend-to-end encryption(i.e. the information is encrypted on the user's browser and decrypted on the destination server). In this case, the proxy server would only see the raw, encrypted bytes of the HTTP request.
For example, Bob might be browsing a chat forum where another user, Mallory, has posted a message. Suppose that Mallory has crafted an HTML image element that references an action on Bob's bank's website (rather than an image file), e.g.,
If Bob's bank keeps his authentication information in a cookie, and if the cookie hasn't expired, then the attempt by Bob's browser to load the image will submit the withdrawal form with his cookie, thus authorizing a transaction without Bob's approval.
Cookiejackingis an attack againstInternet Explorerwhich allows the attacker to stealsession cookiesof a user by tricking a user into dragging an object across the screen.Microsoft deemed the flaw low-risk because of "the level of required user interaction",and the necessity of having a user already logged into the website whose cookie is stolen.Despite this, a researcher tried the attack on 150 of their Facebook friends and obtained cookies of 80 of them viasocial engineering.
Besides privacy concerns, cookies also have some technical drawbacks. In particular, they do not always accurately identify users, they can be used for security attacks, and they are often at odds with the Representational State Transfer (REST) software architectural style.
If more than one browser is used on a computer, each usually has a separate storage area for cookies. Hence, cookies do not identify a person, but a combination of a user account, a computer, and a web browser. Thus, anyone who uses multiple accounts, computers, or browsers has multiple sets of cookies.
Likewise, cookies do not differentiate between multiple users who share the sameuser account, computer, and browser.
Some of the operations that can be done using cookies can also be done using other mechanisms.
AJSON Web Token(JWT) is a self-contained packet of information that can be used to store user identity and authenticity information. This allows them to be used in place of session cookies. Unlike cookies, which are automatically attached to each HTTP request by the browser, JWTs must be explicitly attached to each HTTP request by the web application.
The HTTP protocol includes thebasic access authenticationand thedigest access authenticationprotocols, which allow access to a web page only when the user has provided the correct username and password. If the server requires such credentials for granting access to a web page, the browser requests them from the user and, once obtained, the browser stores and sends them in every subsequent page request. This information can be used to track the user.
Thequery stringpart of theURLis the part that is typically used for this purpose, but other parts can be used as well. TheJava ServletandPHPsession mechanisms both use this method if cookies are not enabled.
This method consists of the web server appending query strings containing a unique session identifier to all the links inside of a web page. When the user follows a link, the browser sends the query string to the server, allowing the server to identify the user and maintain state.
These kinds of query strings are very similar to cookies in that both contain arbitrary pieces of information chosen by the server and both are sent back to the server on every request. However, there are some differences. Since a query string is part of a URL, if that URL is later reused, the same attached piece of information will be sent to the server, which could lead to confusion. For example, if the preferences of a user are encoded in the query string of a URL and the user sends this URL to another user bye-mail, those preferences will be used for that other user as well.
Moreover, if the same user accesses the same page multiple times from different sources, there is no guarantee that the same query string will be used each time. For example, if a user visits a page by coming from a pageinternal to the sitethe first time, and then visits the same page by coming from anexternalsearch enginethe second time, the query strings would likely be different. If cookies were used in this situation, the cookies would be the same.
Other drawbacks of query strings are related to security. Storing data that identifies a session in a query string enablessession fixationattacks,refererlogging attacks and othersecurity exploits. Transferring session identifiers as HTTP cookies is more secure.
Another form of session tracking is to useweb formswith hidden fields. This technique is very similar to using URL query strings to hold the information and has many of the same advantages and drawbacks. In fact, if the form is handled with theHTTPGET method, then this technique is similar to using URL query strings, since the GET method adds the form fields to the URL as a query string. But most forms are handled with HTTP POST, which causes the form information, including the hidden fields, to be sent in the HTTP request body, which is neither part of the URL, nor of a cookie.
This approach presents two advantages from the point of view of the tracker. First, having the tracking information placed in the HTTP request body rather than in the URL means it will not be noticed by the average user. Second, the session information is not copied when the user copies the URL (to bookmark the page or send it via email, for example).
All current web browsers can store a fairly large amount of data (2–32 MB) via JavaScript using theDOMpropertywindow.name. This data can be used instead of session cookies. The technique can be coupled withJSON/JavaScript objects to store complex sets of session variables on the client side.
The downside is that every separate window ortabwill initially have an emptywindow.nameproperty when opened.
In some respects, this can be more secure than cookies due to the fact that its contents are not automatically sent to the server on every request like cookies are, so it is not vulnerable to network cookie sniffing attacks.
Some users may be tracked based on theIP addressof the computer requesting the page. The server knows the IP address of the computer running the browser (or theproxy, if any is used) and could theoretically link a user's session to this IP address.
However, IP addresses are generally not a reliable way to track a session or identify a user. Many computers designed to be used by a single user, such as office PCs or home PCs, are behind a network address translator (NAT). This means that several PCs will share a public IP address. Furthermore, some systems, such asTor, are designed to retainInternet anonymity, rendering tracking by IP address impractical, impossible, or a security risk.
Because ETags are cached by the browser, and returned with subsequent requests for the same resource, a tracking server can simply repeat any ETag received from the browser to ensure an assigned ETag persists indefinitely (in a similar way to persistent cookies). Additional caching header fields can also enhance the preservation of ETag data.
ETags can be flushed in some browsers by clearing thebrowser cache.
The browser cache can also be used to store information that can be used to track individual users. This technique takes advantage of the fact that the web browser will use resources stored within the cache instead of downloading them from the website when it determines that the cache already has the most up-to-date version of the resource.
For example, a website could serve a JavaScript file with code that sets a unique identifier for the user (for example,var userId = 3243242;). After the user's initial visit, every time the user accesses the page, this file will be loaded from the cache instead of downloaded from the server. Thus, its content will never change.
Abrowser fingerprintis information collected about a browser's configuration, such as version number, screen resolution, and operating system, for the purpose of identification. Fingerprints can be used to fully or partially identify individual users or devices even when cookies are turned off.
Basicweb browserconfiguration information has long been collected byweb analyticsservices in an effort to accurately measure real humanweb trafficand discount various forms ofclick fraud. With the assistance ofclient-side scriptinglanguages, collection of much more esoteric parameters is possible.Assimilation of such information into a single string constitutes a device fingerprint. In 2010,EFFmeasured at least 18.1 bits ofentropypossible from browser fingerprinting.Canvas fingerprinting, a more recent technique, claims to add another 5.7 bits.
Some web browsers support persistence mechanisms which allow the page to store the information locally for later use.
TheHTML5standard (which most modern web browsers support to some extent) includes a JavaScript API calledWeb storagethat allows two types of storage: local storage and session storage. Local storage behaves similarly topersistent cookieswhile session storage behaves similarly tosession cookies, except that session storage is tied to an individual tab/window's lifetime (AKA a page session), not to a whole browser session like session cookies.
Internet Explorer supports persistent informationin the browser's history, in the browser's favorites, in an XML store ("user data"), or directly within a web page saved to disk.
Some web browser plugins include persistence mechanisms as well. For example,Adobe FlashhasLocal shared objectandMicrosoft Silverlighthas Isolated storage.