Httponly Cookie

True if the cookie has the HttpOnly attribute and cannot be accessed through a client-side script; otherwise, false. The default is false. The following code example demonstrates how to write an HttpOnly cookie and shows how it is not accessible by the client through ECMAScript. HttpOnly is a tag added to a browser cookie that prevents client-side scripts from accessing data. It provides a gate that prevents the specialized cookie from being accessed by anything other than the server.

Thank you for visiting OWASP.org. We recently migrated our community to a new web platform and regretably the content for this page needed to be programmatically ported from its previous wiki page. There’s still some work to be done.

Using Java to Set HttpOnly

Since Java Enterprise Edition 6 (JEE 6), which adopted Java Servlet 3.0technology, it’s programmatically easy to set the HttpOnly flag on acookie.

In fact setHttpOnly and isHttpOnly methods are available in theCookie interface1,and also for session cookies (JSESSIONID)2:

Cookie cookie = getMyCookie('myCookieName');cookie.setHttpOnly(true);

Moreover, since JEE 6 it’s also declaratively easy setting HttpOnlyflag in a session cookie by applying the following configuration in thedeployment descriptor WEB-INF/web.xml:

` `` ``true`` `

For Java Enterprise Edition versions prior to JEE 6 a commonworkaround is to overwrite the SET-COOKIE HTTP response headerwith a session cookie value that explicitly appends the HttpOnly flag:

String sessionid = request.getSession().getId();// be careful overwriting: JSESSIONID may have been set with other flagsresponse.setHeader('SET-COOKIE', 'JSESSIONID=' + sessionid + '; HttpOnly');

In this context, overwriting, despite appropriate for the HttpOnlyflag, is discouraged because the JSESSIONID may have been set with otherflags. A better workaround is taking care of the previously set flags orusing the ESAPI#Java_EE library: in factthe addCookie method of the SecurityWrapperResponse3takes care of previously set flags for us. So we could write a servletfilter as the following one:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; // if errors exist then create a sanitized cookie header and continue SecurityWrapperResponse securityWrapperResponse = new SecurityWrapperResponse(httpServletResponse, 'sanitize'); Cookie[] cookies = httpServletRequest.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie != null) { // ESAPI.securityConfiguration().getHttpSessionIdName() returns JSESSIONID by default configuration if (ESAPI.securityConfiguration().getHttpSessionIdName().equals(cookie.getName())) { securityWrapperResponse.addCookie(cookie); } } } } filterChain.doFilter(request, response);}

Some web application servers, that implement JEE 5, and servletcontainers that implement Java Servlet 2.5 (part of JEE 5), also allowcreating HttpOnly session cookies:

  • Tomcat 6 In context.xml set the context tag’s attributeuseHttpOnly4as follow:

<?xml version=”1.0” encoding=”UTF-8”?>

- **JBoss 5.0.1** and **JBOSS EAP 5.0.1** In`server``deployjbossweb.sarcontext.xml`set the `SessionCookie` tag[5](https://community.jboss.org/message/598558#598558) as follow:` `- IBM Websphere offer HTTPOnly for session cookies as aconfiguration option.<http://pic.dhe.ibm.com/infocenter/tivihelp/v33r1/topic/com.ibm.mam.inswas.doc/install/t_configuringthehttponlyattribute.html>
Using .NET to Set HttpOnly
- By *default*, **.NET 2.0** sets the HttpOnly attribute for1. Session ID2. Forms Authentication cookieIn .NET 2.0, HttpOnly can also be set via the HttpCookie object for allcustom application cookies- Via **web.config** in the system.web/httpCookies element`<httpCookies httpOnlyCookies='true' …> `- Or **programmatically**C# Code:`HttpCookie myCookie = new HttpCookie('myCookie');``myCookie.HttpOnly = true;``Response.AppendCookie(myCookie);`VB.NET Code:`Dim myCookie As HttpCookie = new HttpCookie('myCookie')``myCookie.HttpOnly = True``Response.AppendCookie(myCookie)`- However, in **.NET 1.1**, you would have to do this *manually*,e.g.,`Response.Cookies[cookie].Path += ';HttpOnly';`
Using Python (cherryPy) to Set HttpOnly
Python Code (cherryPy):To use HTTP-Only cookies with Cherrypy sessions just add the followingline in your configuration file:tools.sessions.httponly = TrueIf you use SLL you can also make your cookies secure (encrypted) toavoid 'man-in-the-middle' cookies reading with:tools.sessions.secure = True
Using PHP to set HttpOnly
PHP supports setting the HttpOnly flag since version 5.2.0 (November2006).For session cookies managed by PHP, the flag is set either permanentlyin php.ini [PHP manual on*HttpOnly*](http://www.php.net/manual/en/session.configuration.php#ini.session.cookie-httponly)through the parameter:`session.cookie_httponly = True`or in and during a script via thefunction[6](http://pl.php.net/manual/en/function.session-set-cookie-params.php):`void session_set_cookie_params ( int $lifetime [, string $path [, string $domain `` [, bool $secure= false [, bool $httponly= false ]]]] )`For application cookies last parameter in setcookie() sets HttpOnlyflag[7](http://pl.php.net/setcookie):`bool setcookie ( string $name [, string $value [, int $expire= 0 [, string $path `` [, string $domain [, bool $secure= false [, bool $httponly= false ]]]]]] )`### Web Application FirewallsIf code changes are infeasible, web application firewalls can be used toadd HttpOnly to session cookies:- Mod_security - using SecRule and Headerdirectives[8](http://blog.modsecurity.org/2008/12/fixing-both-missing-httponly-and-secure-cookie-flags.html)- ESAPIWAF[9](http://code.google.com/p/owasp-esapi-java/downloads/list)using *add-http-only-flag*directive[10](http://www.slideshare.net/llamakong/owasp-esapi-waf-appsec-dc-2009)## Browsers Supporting HttpOnlyUsing WebGoat's HttpOnly lesson, the following web browsers have beentested for HttpOnly support. If the browsers enforces HttpOnly, a clientside script will be unable to read or write the session cookie. However,there is currently no prevention of reading or writing the sessioncookie via a XMLHTTPRequest.Note: These results may be out of date as this page is not wellmaintained. A great page that is focused on keeping up with the statusof browsers is at: <http://www.browserscope.org/?category=security>.Just look at the HttpOnly column. The Browserscope site does not provideas much detail on HttpOnly as this page, but provides lots of otherdetails this page does not.Our results as of Feb 2009 are listed below in **table 1**. **Browser** **Version** **Prevents Reads** **Prevents Writes** **Prevents Read within XMLHTTPResponse*** ------------------------------------- -------------- ------------------------------------- -------------- ------------------------------------- ------------------ ------------------------------------- ------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------ Microsoft Internet Explorer align='center' 8 Beta 2 align='center' Yes align='center' Yes align='center' Partially (set-cookie is protected, but not set-cookie2, see [11](http://www.microsoft.com/technet/security/bulletin/ms08-069.mspx)). Fully patched IE8 passes <http://ha.ckers.org/httponly.cgi> Microsoft Internet Explorer align='center' 7 align='center' Yes align='center' Yes align='center' Partially (set-cookie is protected, but not set-cookie2, see [12](http://www.microsoft.com/technet/security/bulletin/ms08-069.mspx)). Fully patched IE7 passes <http://ha.ckers.org/httponly.cgi> Microsoft Internet Explorer align='center' 6 (SP1) align='center' Yes align='center' No align='center' No (Possible that ms08-069 fixed IE 6 too, please verify with <http://ha.ckers.org/httponly.cgi> and update this page!) Microsoft Internet Explorer align='center' 6 (fully patched) align='center' Yes align='center' Unknown align='center' Yes Mozilla Firefox align='center' 3.0.0.6+ align='center' Yes align='center' Yes align='center' Yes (see [13](http://manicode.blogspot.com/2009/02/firefox-3006-httponly-champion.html)) Netscape Navigator align='center' 9.0b3 align='center' Yes align='center' Yes align='center' No Opera align='center' 9.23 align='center' No align='center' No align='center' No Opera align='center' 9.50 align='center' Yes align='center' No align='center' No Opera align='center' 11 align='center' Yes align='center' Unknown align='center' Yes Safari align='center' 3.0 align='center' No align='center' No align='center' No (almost yes, see [14](https://bugs.webkit.org/show_bug.cgi?id=10957)) Safari align='center' 5 align='center' Yes align='center' Yes align='center' Yes iPhone (Safari) align='center' iOS 4 align='center' Yes align='center' Yes align='center' Yes Google's Chrome align='center' Beta (initial public release) align='center' Yes align='center' No align='center' No (almost yes, see [15](https://bugs.webkit.org/show_bug.cgi?id=10957)) Google's Chrome align='center' 12 align='center' Yes align='center' Yes align='center' Yes Android align='center' Android 2.3 align='center' Unknown align='center' Unknown align='center' No **Table 1:** Browsers Supporting HttpOnly* An attacker could still read the session cookie in a response to an**[XmlHttpRequest](http://ha.ckers.org/blog/20070719/firefox-implements-httponly-and-is-vulnerable-to-xmlhttprequest/)**.As of 2011, 99% of browsers and most web application frameworks supportHttpOnly[1].## Using WebGoat to Test for HttpOnly SupportThe goal of this section is to provide a step-by-step example of testingyour browser for HttpOnly support.

WARNING

The OWASP WEBGOAT HttpOnly lab is broken and does not show IE 8 Beta 2with ms08-069 as complete in terms of HttpOnly XMLHTTPRequest headerleakage protection. This error is being tracked via<http://code.google.com/p/webgoat/issues/detail?id=18>.

Getting Started

![Click_link.JPG](Click_link.JPG 'Click_link.JPG')Assuming you have installed and launched WebGoat, begin by navigating tothe **‘HttpOnly Test’ lesson** located within the Cross-Site Scripting(**XSS**) category. After loading the ‘HttpOnly Test’ lesson, as shownin **figure 1**, you are now able to begin testing web browserssupporting HttpOnly.

Lesson Goal

If the *HttpOnly flag* is set, then your browser should not allow aclient-side script to access the session cookie. Unfortunately, sincethe attribute is relatively new, several browsers may neglect to handlethe new attribute properly.The **purpose** of this lesson is to test whether your browser supportsthe **HttpOnly cookie flag**. *Note the value of the* ***unique2ucookie***. If your browser supports HttpOnly, and you *enable* it for acookie, a client-side script should NOT be able to read OR write to thatcookie, but the browser can still send its value to the server. However,some browsers only prevent client side read access, but do not preventwrite access.

Testing Web Browsers for HttpOnly Support

The following test was performed on two browsers, **Internet Explorer7** and **Opera 9.22**, to demonstrate the results when the HttpOnlyflag is enforced properly. As you will see, IE7 properly enforces theHttpOnly flag, whereas Opera does not properly enforce the HttpOnlyflag.
Disabling HttpOnly
`1) Select the option to `**`turn`` ``HttpOnly````off`**` as shown below in `**`figure`` ``2`**`.`![Fig2-Disabling_HTTPOnly.PNG](Fig2-Disabling_HTTPOnly.PNG'Fig2-Disabling_HTTPOnly.PNG')`2) After turning HttpOnly off, select the `**`“Read````Cookie”`**` button. `- An alert dialog box will display on the screen notifying you that*since HttpOnly was not enabled*, the **‘unique2u’ cookie** wassuccessfully read as shown below in **figure 3**.![Fig3-Read_HTTPOnly_Off.PNG](Fig3-Read_HTTPOnly_Off.PNG'Fig3-Read_HTTPOnly_Off.PNG')`3) With HttpOnly remaining disabled, select the ''“Write Cookie” '' button.`- An alert dialog box will display on the screen notifying you that*since HttpOnly was not enabled*, the **‘unique2u’ cookie** wassuccessfully modified on the client side as shown below in **figure4**.![Fig4-Write_HTTPOnly_Off.PNG](Fig4-Write_HTTPOnly_Off.PNG'Fig4-Write_HTTPOnly_Off.PNG')- As you have seen thus far, **browsing without HttpOnly** on is apotential ***threat***. Next, we will **enable HttpOnly** todemonstrate how this flag protects the cookie.
Enabling HttpOnly
`4) Select the `*`radio````button`*` to enable HttpOnly as shown below in `**`figure````5`**`.`![Fig5-Turning_HTTPOnly_On.PNG](Fig5-Turning_HTTPOnly_On.PNG'Fig5-Turning_HTTPOnly_On.PNG')`5) After enabling HttpOnly, select the `**`'Read````Cookie'`**` button.`- If the browser enforces the HttpOnly flag properly, an alert dialogbox will display only the session ID rather than the contents of the**‘unique2u’ cookie** as shown below in **figure 6**.![Fig6-Cookie_Read_Protection.PNG](Fig6-Cookie_Read_Protection.PNG'Fig6-Cookie_Read_Protection.PNG')- However, if the browser does not enforce the HttpOnly flag properly,an alert dialog box will display both the **‘unique2u’ cookie** andsession ID as shown below in **figure 7**.![Fig7-No_Cookie_Read_Protection.PNG](Fig7-No_Cookie_Read_Protection.PNG'Fig7-No_Cookie_Read_Protection.PNG')- Finally, we will test if the browser allows **write access** to thecookie with HttpOnly enabled.`6) Select the `**`'Write`` ``Cookie'`**` button.`- If the browser enforces the HttpOnly flag properly, client sidemodification will be unsuccessful in writing to the **‘unique2u’cookie** and an alert dialog box will display only containing thesession ID as shown below in **figure 8**.![Fig6-Cookie_Read_Protection.PNG](Fig6-Cookie_Read_Protection.PNG'Fig6-Cookie_Read_Protection.PNG')- However, if the browser does not enforce the write protectionproperty of HttpOnly flag for the **‘unique2u’ cookie**, the cookiewill be successfully modified to *HACKED* on the client side asshown below in **figure 9**.![Fig9-No_Cookie_Write_Protection.PNG](Fig9-No_Cookie_Write_Protection.PNG'Fig9-No_Cookie_Write_Protection.PNG')## References1. [CWE-1004: Sensitive Cookie Without 'HttpOnly'Flag](https://cwe.mitre.org/data/definitions/1004.html)2. Wiens, Jordan ['No cookie foryou!'](http://www.networkcomputing.com/careers/no-cookie-you/1270585242)3. [Mitigating Cross-site Scripting with HTTP-OnlyCookies](http://msdn2.microsoft.com/en-us/library/ms533046.aspx)4. Howard, Michael. [Some Bad News and Some GoodNews](http://msdn2.microsoft.com/en-us/library/ms972826.aspx)5. MSDN. [Setting the HttpOnly propery in.NET](http://msdn.microsoft.com/en-us/library/system.web.httpcookie.httponly.aspx)6. [XSS: Gaining access to HttpOnly Cookiein 2012](http://seckb.yehg.net/2012/06/xss-gaining-access-to-httponly-cookie.html)7. [Setting HttpOnly inJava](http://stackoverflow.com/questions/13147113/setting-an-httponly-cookie-with-javax-servlet-2-5)1. [Misunderstandings on HttpOnlyCookie](http://blog.fortify.com/blog/2011/11/02/Misunderstandings-on-HttpOnly-Cookie)

HTTP cookies can be created in two ways: either in the HTTP layer, on in the application layer in the DOM using JavaScript. And after they are created, some cookies can be accessed from either layer, depending on the application requirements.

HTTP cookies can be created in a web browser either by the Set-Cookie header in a HTTP response or using JavaScript using the document.cookie property. An example from JavaScript console:

The same cookie can be set using a HTTP response header:

Cookie

This gives application developers great flexibility in customizing the application behavior to match user preferences — for example, if an user indicated a preference to see the website in Russian language, the application can set a cookie language=russian which the browser will send in all subsequent requests. Upon receiving the cookie, the application will then display content in appropriate language, always returning what the user has chosen to see. The cookie can be read from either the HTTP session (Cookie request header), which is what most server-side applications would do, or client-side using JavaScript, a mode preferred by most AJAX JavaScript-based applications.

Httponly Cookies Apache

The problem with the latter access method is that some types of cookies are never intended to be accessed outside of the HTTP channel — for example, session cookies often contain authentication tokens which, if exposed by a malicious JavaScript code, can be used to impersonate the user on the target website.

This would require a vulnerability such as Cross-Site Scripting to be present on the website but ability to hide the authentication cookie from JavaScript code significantly reduces impact of such attack. The httpOnly cookie flag does exactly that — it instructs the browser that this particular cookie should be never exposed to the JavaScript layer and only sent

The flag is defined in RFC 6265 and should be set on all authentication-related cookies that are no intended to be accessed by JavaScript. An example:

Such cookie will be still sent in the Cookie request header, accessible by the server-side web application code, but never exposed to the client-side browser DOM and not accessible from JavaScript.

Most web application security scanners will check if session cookies are set with the httpOnly flag and will raise an alert if it's not. Some broken security scanners will raise this alert for any cookies set by the website which is definitely an overkill and a false positive.