XSS应对与防御
XSS的防范
1. 必须明确:一切输入都是有害的,不要信任一切输入的数据。
2. 对输入的数据进行转义保存,在输出时再进行还原; 对输入的数据进行过滤,确保输入数据符合我们的期望(数据类型、长度、过滤空格/特殊字符、判断唯一性等)。
替换危险字符,如:"&", "<", ">", ""","'", "/", "?",";", ":", "%", "<SPACE>", "=", "+"。
def escape(s, quote=None): '''Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true, the quotation mark character (") is also translated.''' s = s.replace("&", "&") # Must be done first! s = s.replace("<", "<") s = s.replace(">", ">") if quote: s = s.replace('"', """) return s
String TestString = "This is a <Test String>."; String EncodedString = Server.HtmlEncode(TestString); Server.UrlEncode(Request.Url.ToString());
<?php $new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES); echo $new; // <a href='test'>Test</a> ?>
String mytext = java.net.URLEncoder.encode("中国", "utf-8");
3. 使用IE6.0SP1的cookie选项HttpOnly,注意,HttpOnly只能阻止恶意脚本读取cookie,并不能阻止XSS攻击。比如在ASP.NET中:
HttpCookie cookie = new HttpCookie("Name", "ZhangChangrong"); cookie.Path = "/; HttpOnly"; Response.Cookies.Add(cookie);
4. 使用IE的<IFrame>的Security属性,设置为restricted后,frame中的脚本将不能执行(仅限于IE)。如:
<iframe security="restricted" src="http://www.somesite.com/somepage.htm"></frame>
5. 在一些必须使用到HTML标签的地方,比如公告栏,可以使用其他格式的标示代替,比如论坛中广泛使用的BBCode,用[i]...["i]来表示斜体。
6. Cookie防盗:
利用XSS攻击,攻击者可以很方便地窃取到合法用户的Cookie信息。因此,对于网站来说,不能在Cookie信息中存放太多敏感信息,也不能将Cookie作为身份认证的唯一标识,等等。因此,对于Cookie,我们可以采取以下的措施。首先,我们要尽可能地避免在Cookie中泄露隐私,如用户名、密码等;其次,我们可以将Cookie信息用MD5等Hash算法进行多次散列后存放;再次,为了防止重放攻击,我们也可以将Cookie和IP进行绑定,这样也可以阻止攻击者冒充正常用户的身份。
7. 限制URL访问:
攻击者使用XSS攻击,通常都要借助于自己指定的网站页面,比如用它来记录敏感信息、在该页面上“挂马”等等。因此,在页面的脚本代码执行过程中,只要我们严格限制其访问的URL,比如只允许脚本代码访问本网站的URL等方式,就可以避免脚本的执行链接到其它可能是攻击者指定的页面上。同源策略。
黑客应对
1. 改变大小写。例如:<ScRiPt>
2. 能够避开过滤、但仍被浏览器接受的字符:【<script/src=...】【<scr%00ipt>】【expr/*****/ession】
3. 通过URL编码或双重编码被过滤的表达式,避开过滤,并对漏洞进行利用。
%3cscript%3e(一次encode) %253cscript%253e(2次encode)
4. 对攻击代码进行HTML编码以避开服务器的输入确认,受害者的浏览器将会再次解析攻击代码:
【<img src=javascri&0000112;t:..】【<img src=javascript:.】
Filtering for XSS
Own filter (RE), or prefer to use libruary.
Escape
To prevent injecting up, you must escape the characters that would allow you to close the current context and start a new one. To prevent attacks that jump up several levels in the DOM hierarchy, you must also escape all the characters that are significant in all enclosing contexts. To prevent injecting down, you must escape any characters that can be used to introduce a new sub-context within the current context.
But HTML entity encoding doesn't work if you're putting untrusted data inside a
<script> tag anywhere, or an event handler attribute like onmouseover, or
inside CSS, or in a URL. So even if you use an HTML entity encoding method
everywhere, you are still most likely vulnerable to XSS. You MUST use the
escape syntax for the part of the HTML document you're putting untrusted data
into. That's what the rules below are all about.
[This is the primary means to disable an XSS attack. When performing Escaping you are effectively telling the browser that the data you are sending should be treated as data and should not be interpreted in any other way. If an attacker manages to put a script on your page, the victim will not be affected because the browser will not execute the script if it is properly escaped.]
RULE #1 - HTML Escape
<body>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</body>
& --> &
< --> <
> --> >
" --> "
' --> ' ' is not recommended
/ --> / forward slash is included as it helps end
an HTML entity
String safe = ESAPI.encoder().encodeForHTML( request.getParameter(
"input" ) );
RULE #2 - Attribute Escape
<div attr=...ESCAPE UNTRUSTED DATA BEFORE PUTTING
HERE...>content</div>
String safe = ESAPI.encoder().encodeForHTMLAttribute( request.getParameter(
"input" ) );
RULE #3 - JavaScript Escape
<script>alert('...ESCAPE UNTRUSTED DATA BEFORE PUTTING
HERE...')</script>
String safe = ESAPI.encoder().encodeForJavaScript( request.getParameter(
"input" ) );
but:
<script>
window.setInterval('...EVEN IF YOU ESCAPE
UNTRUSTED DATA YOU ARE XSSED HERE...');
</script>
RULE #4 - CSS Escape And Strictly Validate
<style>selector { property : ...ESCAPE UNTRUSTED DATA BEFORE PUTTING
HERE...; } </style>
but:
You will have to ensure that URLs only start with "http" not
"javascript" and that properties never start with
"expression".
String safe = ESAPI.encoder().encodeForCSS( request.getParameter(
"input" ) );
RULE #5 - URL Escape
<a href="http://www.somesite.com?test=...ESCAPE UNTRUSTED DATA BEFORE
PUTTING HERE...">link</a >
String safe = ESAPI.encoder().encodeForURL( request.getParameter(
"input" ) );
Do not encode complete or relative URL's with URL encoding, it should be
validated to make sure it does not point to an unexpected protocol, especially
Javascript links.
When to Escape
You cannot just simply escape everything, or else your own scripts and HTML markup will not work, rendering your page useless.
There are several places on your web page which you need to ensure are properly escaped. You can use your own escaping functions (not recommended) and you can use the existing ESAPI and AntiXSS libraries.
Use HTML Escaping when...
Untrusted data is inserted in between HTML opening and closing tags. These are standards tags such as <BODY>, <DIV>, <TABLE> etc...
For example:
<DIV> IF THIS DATA IS UNTRUSTED IT MUST BE HTML ESCAPED </DIV>
Use JavaScript Escaping when...
Untrusted data is inserted inside one of your scripts, or in a place where JavaScript can be present. This includes certain attributes such as STYLE and all event handlers such as ONMOUSEOVER and ONLOAD
For example:
<SCRIPT>alert('IF THIS DATA IS UNTRUSTED IT MUST BE JAVASCRIPT ESCAPED')</SCRIPT>
<BODY ONLOAD=”IF THIS DATA IS UNTRUSTED IT MUST BE JAVASCRIPT ESCAPED">
Use CSS Escaping when...
Untrusted data is inserted inside your CSS styles. As you saw in the Attack Vectors examples, many CSS styles can be used to smuggle a script into your page.
For example:
<DIV STYLE="background-image: IF THIS DATA IS UNTRUSTED IT MUST BE CSS ESCAPED">
Above is a diagram visually representing the internet boundary and where filtering and escaping must happen to ensure XSS protection.
https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet
Reference:
http://www.cnblogs.com/coderzh/archive/2008/09/06/1285500.html
http://www.51testing.com/?uid-316693-action-viewspace-itemid-814910
http://www.hackbase.com/tech/2012-05-07/66397.html
http://hi.baidu.com/cuttinger/item/c0fe214a3e585f0ec01613cd
http://www.51testing.com/?uid-352747-action-viewspace-itemid-814838
http://www.acunetix.com/blog/web-security-zone/articles/preventing-xss-attacks/