Cross Site Scripting Prevention Cheat Sheet¶
Cross Site Scripting Prevention Cheat Sheet
RULE #3 - JavaScript Encode Before Inserting Untrusted Data into JavaScript Data Values
Rule #3 concerns dynamically generated JavaScript code - both script blocks and event-handler attributes. The only safe place to put untrusted data into this code is inside a quoted "data value." Including untrusted data inside any other JavaScript context is quite dangerous, as it is extremely easy to switch into an execution context with characters including (but not limited to) semi-colon, equals, space, plus, and many more, so use with caution.
Inside a quoted string:
<script>alert('...ENCODE UNTRUSTED DATA BEFORE PUTTING HERE...')</script>
One side of a quoted expression:
<script>x='...ENCODE UNTRUSTED DATA BEFORE PUTTING HERE...'</script>
Inside quoted event handler:
<div onmouseover="x='...ENCODE UNTRUSTED DATA BEFORE PUTTING HERE...'"</div>
Please note there are some JavaScript functions that can never safely use untrusted data as input - EVEN IF JAVASCRIPT ENCODED!
For example:
<script>
window.setInterval('...EVEN IF YOU ENCODE UNTRUSTED DATA YOU ARE XSSED HERE...');
</script>
Except for alphanumeric characters, encode all characters with the \xHH
format to prevent switching out of the data value into the script context or into another attribute. DO NOT use any escaping shortcuts like \"
because the quote character may be matched by the HTML attribute parser which runs first. These escaping shortcuts are also susceptible to escape-the-escape attacks where the attacker sends \"
and the vulnerable code turns that into \\"
which enables the quote.
If an event handler is properly quoted, breaking out requires the corresponding quote. However, we have intentionally made this rule quite broad because event handler attributes are often left unquoted. Unquoted attributes can be broken out of with many characters including [space]
%
*
+
,
-
/
;
<
=
>
^
and |
.
Also, a </script>
closing tag will close a script block even though it is inside a quoted string because the HTML parser runs before the JavaScript parser. Please note this is an aggressive encoding policy that over-encodes. If there is a guarantee that proper quoting is accomplished then a much smaller character set is needed. Please look at the OWASP Java Encoder JavaScript encoding examples for examples of proper JavaScript use that requires minimal encoding.
RULE #3.1 - HTML Encode JSON values in an HTML context and read the data with JSON.parse¶
In a Web 2.0 world, the need for having data dynamically generated by an application in a JavaScript context is common. One strategy is to make an AJAX call to get the values, but this isn't always performant. Often, an initial block of JSON is loaded into the page to act as a single place to store multiple values. This data is tricky, though not impossible, to encode/escape correctly without breaking the format and content of the values.
Ensure returned Content-Type
header is application/json
and not text/html
. This shall instruct the browser not misunderstand the context and execute injected script
Bad HTTP response:
HTTP/1.1 200
Date: Wed, 06 Feb 2013 10:28:54 GMT
Server: Microsoft-IIS/7.5....
Content-Type: text/html; charset=utf-8 <-- bad
....
Content-Length: 373
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
{"Message":"No HTTP resource was found that matches the request URI 'dev.net.ie/api/pay/.html?HouseNumber=9&AddressLine
=The+Gardens<script>alert(1)</script>&AddressLine2=foxlodge+woods&TownName=Meath'.","MessageDetail":"No type was found
that matches the controller named 'pay'."} <-- this script will pop!!
Good HTTP response:
HTTP/1.1 200
Date: Wed, 06 Feb 2013 10:28:54 GMT
Server: Microsoft-IIS/7.5....
Content-Type: application/json; charset=utf-8 <--good
.....
A common anti-pattern one would see:
<script>
// Do NOT do this without encoding the data with one of the techniques listed below.
var initData = <%= data.to_json %>;
</script>
JSON serialization¶
A safe JSON serializer will allow developers to serialize JSON as a string of literal JavaScript which can be embedded in an HTML in the contents of the <script>
tag. HTML characters and JavaScript line terminators need be encoded. Consider the Yahoo JavaScript Serializer for this task.
HTML entity encoding¶
This technique has the advantage that HTML entity encoding is widely supported and helps separate data from server side code without crossing any context boundaries. Consider placing the JSON block on the page as a normal element and then parsing the innerHTML to get the contents. The JavaScript that reads the span can live in an external file, thus making the implementation of CSP enforcement easier.
<div id="init_data" style="display: none">
<%= html_encode(data.to_json) %>
</div>
// external js file
var dataElement = document.getElementById('init_data');
// decode and parse the content of the div
var initData = JSON.parse(dataElement.textContent);
An alternative to encoding and decoding JSON directly in JavaScript, is to normalize JSON server-side by converting <
to \u003c
before delivering it to the browser.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-09-01 ailoop2里面的1个待考察的,在ailoop3里面的操作。(先使用海巨人,不使用英雄技能召唤图腾的问题)
2017-09-01 学习bootstrap
2015-09-01 检查string是否为double
2015-09-01 How to hide TabPage from TabControl
2014-09-01 win7下配置IIS