防御修复
XSS 防御与修复
Content Security Policy
// index.html
<!DOCTYPE html>
<html>
<head>
<meta
http-equiv="Content-Security-Policy"
content="default-src * atom://*; img-src blob: data: * atom://*; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src blob: data: mediastream: * atom://*;"
/>
<script src="index.js"></script>
</head>
<body tabindex="-1"></body>
</html>
The script-src ‘self’ ‘unsafe-eval’, means that JavaScript from the same origin as well as code created using an eval like construct will by be executed. However, any inline JavaScript is forbidden.
In a nutshell, the JavaScript from “index.js” would be executed in the following sample, the alert(1) however not, since it is inline JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src * atom://*; img-src blob: data: * atom://*; script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src blob: data: mediastream: * atom://*;">
</head>
<!-- Following line will be executed since it is JS embedded from the same origin -->
<script src="index.js"></script>
<!-- Following line will not be executed since it is inline JavaScript -->
<script>alert(1)</script>
</html>
React
笔者一直是坚定地
不过如果有安全背景的朋友肯定已经能够察觉到问题了,直接将数据不经过滤地放到页面上势必会带来潜在的安全问题,譬如我们最常用的同构页面的代码:
export default (html, initialState = {}, scripts = [], styles = []) => {
return `
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
${styleMapper(styles)}
</head>
<body>
<div id="root">${html}</div>
</body>
${scriptMapper(scripts)}
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
</html>
`;
};
我们直接使用JSON.stringfy
将
{
"user": {
"username": "NodeSecurity",
"bio": "as</script><script>alert('You have an XSS vulnerability!')</script>"
}
}
你就会很开心的看到你得到了某个弹窗。关于
对于
-
所有的用户输入都需要经过
HTML 实体编码,这里React 已经帮我们做了很多,它会在运行时动态创建DOM 节点然后填入文本内容( 你也可以强制设置HTML 内容,不过这样比较危险) -
当你打算序列化某些状态并且传给客户端的时候,你同样需要进行
HTML 实体编码
npm install --save serialize-javascript
导入该模块,然后使用serialize
方法替代内置的JSON.stringify
方法: