HttpOnly
Contents
Overview
The goal of this section is to introduce, discuss, and provide language specific mitigation techniques for HttpOnly.
Who developed HttpOnly? When?
According to a daily blog article by Jordan Wiens, “No cookie for you!,” HttpOnly cookies were first implemented in 2002 by Microsoft Internet Explorer developers for Internet Explorer 6 SP1. Wiens, [1]
What is HttpOnly?
According to the Microsoft Developer Network, HttpOnly is an additional flag included in a Set-Cookie HTTP response header. Using the HttpOnly flag when generating a cookie helps mitigate the risk of client side script accessing the protected cookie (if the browser supports it).
- The example below shows the syntax used within the HTTP response header:
Set-Cookie: <name>=<value>[; <Max-Age>=<age>]
[; expires=<date>][; domain=<domain_name>]
[; path=<some_path>][; secure][; HttpOnly]
If the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client side script (again if the browser supports this flag). As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits this flaw, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.
If a browser does not support HttpOnly and a website attempts to set an HttpOnly cookie, the HttpOnly flag will be ignored by the browser, thus creating a traditional, script accessible cookie. As a result, the cookie (typically your session cookie) becomes vulnerable to theft of modification by malicious script. Mitigating, [2]
Mitigating the Most Common XSS attack using HttpOnly
According to Michael Howard, Senior Security Program Manager in the Secure Windows Initiative group at Microsoft, the majority of XSS attacks target theft of session cookies. A server could help mitigate this issue by setting the HTTPOnly flag on a cookie it creates, indicating the cookie should not be accessible on the client.
If a browser that supports HttpOnly detects a cookie containing the HttpOnly flag, and client side script code attempts to read the cookie, the browser returns an empty string as the result. This causes the attack to fail by preventing the malicious (usually XSS) code from sending the data to an attacker's website. Howard, [3]
Using Java to Set HttpOnly
Since Sun Java Enterprise Edition 6 (JEE 6), that adopted Java Servlet 3.0 technology, it's programmatically easy setting HttpOnly flag in a cookie.
In fact setHttpOnly
and isHttpOnly
methods are available in the Cookie
interface [4], and also for session cookies (JSESSIONID) [5]:
Cookie cookie = getMyCookie("myCookieName");
cookie.setHttpOnly(true);
Moreover since JEE 6 it's also declaratively easy setting HttpOnly
flag in session cookie, by applying the following configuration in the deployment descriptor WEB-INF/web.xml
:
<session-config>
<cookie-config>
<http-only>true</http-only>
</cookie-config>
</session-config>
For Java Enterprise Edition versions prior to JEE 6 a common workaround is to overwrite the SET-COOKIE
http response header with 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 flags
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");
In this context overwriting, despite appropriate for the HttpOnly
flag, is discouraged because JSESSIONID may have been set with other flags. So a better workaround is taking care of the previously set flags or using the ESAPI#Java_EE library: in fact the addCookie
method of the SecurityWrapperResponse
[6] takes care of previously set falgs for us. So we could write a servlet filter 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 implements JEE 5, and servlet container that implements Java Servlet 2.5 (part of the JEE 5), also allow creating HttpOnly session cookies:
- Tomcat 6 In
context.xml
set thecontext
tag's attributeuseHttpOnly
[7] as follow:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/myWebApplicationPath" useHttpOnly="true">
- JBoss 5.0.1 and JBOSS EAP 5.0.1 In
\server\<myJBossServerInstance>\deploy\jbossweb.sar\context.xml
set theSessionCookie
tag [8] as follow:
<Context cookies="true" crossContext="true">
<SessionCookie secure="true" httpOnly="true" />
Using .NET to Set HttpOnly
- By default, .NET 2.0 sets the HttpOnly attribute for
- Session ID
- Forms Authentication cookie
In .NET 2.0, HttpOnly can also be set via the HttpCookie object for all custom 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 following line in your configuration file:
tools.sessions.httponly = True
If you use SLL you can also make your cookies secure (encrypted) to avoid "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 (November 2006).
For session cookies managed by PHP, the flag is set either permanently in php.iniPHP manual on HttpOnly through the parameter:
session.cookie_httponly = True
or in and during a script via the function[9]:
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 HttpOnly flag[10]:
bool setcookie ( string $name [, string $value [, int $expire= 0 [, string $path
[, string $domain [, bool $secure= false [, bool $httponly= false ]]]]]] )
Web Application Firewalls
If code changes are infeasible, web application firewalls can be used to add HttpOnly to session cookies:
- Mod_security - using SecRule and Header directives[11]
- ESAPI WAF[12] using add-http-only-flag directive[13]
Browsers Supporting HttpOnly
Using WebGoat's HttpOnly lesson, the following web browsers have been tested for HttpOnly support. If the browsers enforces HttpOnly, a client side script will be unable to read or write the session cookie. However, there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest.
Note: These results may be out of date as this page is not well maintained. A great site that is focused on keeping up with the status of browsers is at: http://www.browserscope.org/. For the most recent security status of various browsers, including many details beyond just HttpOnly, go to the browserscope site, and then click on the Security Tab on the table at the bottom of the page. The Browserscope site does not provide as much detail on HttpOnly as this page, but provides lots of other details 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 | 8 Beta 2 | Yes | Yes | Partially (set-cookie is protected, but not set-cookie2, see [14]). Fully patched IE8 passes http://ha.ckers.org/httponly.cgi |
Microsoft Internet Explorer | 7 | Yes | Yes | Partially (set-cookie is protected, but not set-cookie2, see [15]). Fully patched IE7 passes http://ha.ckers.org/httponly.cgi |
Microsoft Internet Explorer | 6 (SP1) | Yes | No | 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 | 6 (fully patched) | Yes | Unknown | Yes |
Mozilla Firefox | 3.0.0.6+ | Yes | Yes | Yes (see [16]) |
Netscape Navigator | 9.0b3 | Yes | Yes | No |
Opera | 9.23 | No | No | No |
Opera | 9.50 | Yes | No | No |
Opera | 11 | Yes | Unknown | Yes |
Safari | 3.0 | No | No | No (almost yes, see [17]) |
Safari | 5 | Yes | Yes | Yes |
iPhone (Safari) | iOS 4 | Yes | Yes | Yes |
Google's Chrome | Beta (initial public release) | Yes | No | No (almost yes, see [18]) |
Google's Chrome | 12 | Yes | Yes | Yes |
Android | Android 2.3 | Unknown | Unknown | No |
* An attacker could still read the session cookie in a response to an XmlHttpRequest.
As of 2011, 99% of browsers and most web application frameworks do support httpOnly<ref>Misunderstandings on HttpOnly Cookie</ref>.
Using WebGoat to Test for HttpOnly Support
The goal of this section is to provide a step-by-step example of testing your browser for HttpOnly support.
WARNING
The OWASP WEBGOAT HttpOnly lab is broken and does not show IE 8 Beta 2 with ms08-069 as complete in terms of HttpOnly XMLHTTPRequest header leakage protection. This error is being tracked via http://code.google.com/p/webgoat/issues/detail?id=18.
Getting Started
Assuming you have installed and launched WebGoat, begin by navigating to the ‘HttpOnly Test’ lesson located within the Cross-Site Scripting (XSS) category. After loading the ‘HttpOnly Test’ lesson, as shown in figure 1, you are now able to begin testing web browsers supporting HTTPOnly.
Lesson Goal
If the HttpOnly flag is set, then your browser should not allow a client-side script to access the session cookie. Unfortunately, since the attribute is relatively new, several browsers may neglect to handle the new attribute properly.
The purpose of this lesson is to test whether your browser supports the HttpOnly cookie flag. Note the value of the unique2u cookie. If your browser supports HTTPOnly, and you enable it for a cookie, a client-side script should NOT be able to read OR write to that cookie, but the browser can still send its value to the server. However, some browsers only prevent client side read access, but do not prevent write access.
Testing Web Browsers for HttpOnly Support
The following test was performed on two browsers, Internet Explorer 7 and Opera 9.22, to demonstrate the results when the HttpOnly flag is enforced properly. As you will see, IE7 properly enforces the HttpOnly flag, whereas Opera does not properly enforce the HttpOnly flag.
Disabling HttpOnly
1) Select the option to turn HttpOnly off as shown below in figure 2.
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 was successfully read as shown below in figure 3.
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 was successfully modified on the client side as shown below in figure 4.
- As you have seen thus far, browsing without HttpOnly on is a potential threat. Next, we will enable HttpOnly to demonstrate how this flag protects the cookie.
Enabling HttpOnly
4) Select the radio button to enable HttpOnly as shown below in figure 5.
5) After enabling HttpOnly, select the "Read Cookie" button.
- If the browser enforces the HttpOnly flag properly, an alert dialog box will display only the session ID rather than the contents of the ‘unique2u’ cookie as shown below in figure 6.
- However, if the browser does not enforce the HttpOnly flag properly, an alert dialog box will display both the ‘unique2u’ cookie and session ID as shown below in figure 7.
- Finally, we will test if the browser allows write access to the cookie with HttpOnly enabled.
6) Select the "Write Cookie" button.
- If the browser enforces the HttpOnly flag properly, client side modification will be unsuccessful in writing to the ‘unique2u’ cookie and an alert dialog box will display only containing the session ID as shown below in figure 8.
- However, if the browser does not enforce the write protection property of HttpOnly flag for the ‘unique2u’ cookie, the cookie will be successfully modified to HACKED on the client side as shown below in figure 9.
References
[1] Wiens, Jordan. No cookie for you!"
[2] Mitigating Cross-site Scripting with HTTP-Only Cookies
[3] Howard, Michael. Some Bad News and Some Good News
[4] MSDN. Setting the HttpOnly propery in .NET
[5] XSS: Gaining access to HttpOnly Cookie in 2012
HttpOnly的更多相关文章
- C#如何通过Socket的方式获取httponly cookie
正常情况下C#可以使用HttpWebRequest.HttpWebResponse和CookieContainer类来获取Cookie,但是当Cookie设置为httponly,我们就不能用上面的方法 ...
- cookie httponly属性
Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be a ...
- web.config中的HttpCookie.HttpOnly属性
Abstract: The program does not set the HttpCookie.HttpOnly property to true. Explanation: The defaul ...
- HostOnly Cookie和HttpOnly Cookie
怎么使用Cookie? 通常我们有两种方式给浏览器设置或获取Cookie,分别是HTTP Response Headers中的Set-Cookie Header和HTTP Request Header ...
- cookie工具类,解决servlet3.0以前不能添加httpOnly属性的问题
最近在解决XSS注入的问题,由于使用的servlet版本是2.5,不支持httpOnly的属性,故做了个工具类来实现cookie的httpOnly的功能.全类如下: /** * cookie工具类,解 ...
- Http-Only Cookie
设置Cookie的时候,如果服务器加上了HttpOnly属性,则这个Cookie无法被JavaScript读取(即document.cookie不会返回这个Cookie的值),只用于向服务器发送. S ...
- 利用Httponly提升web应用程序安全性
随着www服务的兴起,越来越多的应用程序转向了B/S结构,这样只需要一个浏览器就可以访问各种各样的web服务,但是这样也越来越导致了越来越 多的web安全问题.www服务依赖于Http协议实现,Htt ...
- 使用HttpOnly提升Cookie安全性
在介绍HttpOnly之前,我想跟大家聊聊Cookie及XSS. 随着B/S的普及,我们平时上网都是依赖于http协议完成,而Http是无状态的,即同一个会话的连续两个请求互相不了解,他们由最 ...
- 【转】HTTP-only Cookie 脚本获取JSESSIONID的方法
彻底避免xss攻击的方法. 别人可以通过注入js脚本获取你的session cookie,如果幸运的话还可以获取通过js遍历你的dom树获取你的用户的用户名和密码. 如果只是通过正则表达式验证输入的话 ...
- 什么是HttpOnly
1.什么是HttpOnly? 如果您在cookie中设置了HttpOnly属性,那么通过js脚本将无法读取到cookie信息,这样能有效的防止XSS攻击,具体一点的介绍请google进行搜索 2.ja ...
随机推荐
- [转]Spring数据库读写分离
数据库的读写分离简单的说是把对数据库的读和写操作分开对应不同的数据库服务器,这样能有效地减轻数据库压力,也能减轻io压力. 主(master)数据库提供写操作,从(slave)数据库提供读操作,其实在 ...
- 昨天冲动的搬到外面住了,oh yeah
昨天我纠结了一天,我是否应该搬到外面去住.我骑着我的自行车,在外面闲逛,我心里想的是,我现在没有钱,可以节约一些生活费,租房的日子,我以后始终都是需要面对的,在目前没有那么多钱的情况下,可以不出去外面 ...
- php 首页定时生成静态页面
往往首页的js,商务通代码加的太多,导致页面访问速度变慢,可以把首页有动态变为静态进行访问,访问速度会有所提升,不过如果更新首页数据,并不能及时更新,而是你规定的时间内固定更新一次 代码如下: < ...
- ubuntu 16.04 chrome flash player 过期
今天手贱更新了系统,发现chrome flash插件过期了 解决方法: 使用全局代理打开 chrome $: google-chrome --proxy-server="socks5://1 ...
- HW-IP合法性_Java
描述 现在IPV4下用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4个部分,每个部分为8位,表示成一个无符号整数(因此不需要用正号出现),如10.137.17.1,是我们非常熟悉 ...
- unity3d环境安装指南: Unity 4.5.5 + Visual Studio 2010
1. UnitySetup-4.5.5.exe 官网下载最新版本4.X 安装exe文件 2. Unity 4.x Pro Patch.exe 复制exe到安装目录下 C:\Program Files ...
- ERROR ITMS-90049错误解决
检查一下项目有集成友盟,shareSDK这种第三方包,里面有个腾讯bundle,包含了一个Info.plist. 去掉,就可以了.类似有其他第三方的bundle,可能也会出现这个问题. 原因估计是Ap ...
- 12_ServletConfig对象
[ServletConfig对象简述] 在Servlet的配置文件中,可以使用一个或多个<init-param>标签为Servlet配置一些初始化参数. 当Servlet配置了初始化参数后 ...
- Thrift原理与使用实例
一 Thrift框架介绍 1 前言 Thrift是一个跨语言的服务部署框架,最初由Faceboo开发并进入Apache开源项目. Thrift特征如下: 1)Thrift有自己的跨机器通信框架,并提供 ...
- Java Web开发中的名词解释
1.JVM Java虚拟机,class文件的运行时环境,就好比软件运行在操作系统一样,java要运行在JVM中才行,这也是Java之所以支持扩平台的基础. 2.Servlet/JSP 是满足一定接口需 ...