在url中输入`http://localhost:3000/?a=<script>b`
根据express的log, chrome和firefox的URL会自动转义:
GET /?a=%3Cscript%3E 200 15.302 ms - 170
而IE11则不会:
GET /?a=<script>b 200 8.829 ms - 170
URI encode的作用是规范URI (可能有些地区中文乱码, IE11不转义"<"这些符号, 但是会自动转义空格?)
Chrome中: The XSS Auditor refused to execute a script in
'http://localhost:3000/?a=b%3Cscript%3Ealert(document.cookie)%3C/script%3E'
because its source code was found within the request. The auditor was enabled
as the server sent neither an 'X-XSS-Protection' nor 'Content-Security-Policy'
header.
于是在header里设置了"X-XSS-Protection": 0,才允许注入脚本。
脚本注入,document.cookie就取不到了。
xss
浏览器在解析HTML时,是按照一定的格式来编码解析的,为了不扰乱HTML结构,有HTML编码,JS编码,URL编码。
<
:<
;)<
:%3C
, 只需对URL中的参数值进行编码)以express 4.x为例:
URI encode的作用是规范URI (可能有些地区中文乱码, IE11不转义"<"这些符号, 但是会自动转义空格?)
URI decode, 在express\node_modules\express\lib\router\layer.js中,所以req.query就能拿到转码后的参数。
模板引擎ejs, jade都有转义功能:
如果像富文本编辑器里,一定要插入一些标签,做法应该是给信任的标签设白名单。
ejs encode html源码
防XSS途径:
cookie
标记为http only, 这样document.cookie就娶不到cookie了csrf
一般通过xss拿到了cookie之后,就可以进行csrf攻击了。
简易防范
RESTFUL设计
除了GET,其余操作均验证 cookie + token