一、Content-Security-Policy——内容安全策略
HTTP 响应头 Content-Security-Policy 允许站点管理者在指定的页面控制用户代理的资源。除了少数例外,这条政策将极大地指定服务源 以及脚本端点。这将帮助防止跨站脚本攻击(Cross-Site Script) (XSS).
二、限制方式
Content-Security-Policy:<policy-directive>; <policy-directive>
<policy-directive>
常用指令
default-src:为其他指令提供备用服务
default-src无法限制form表单的提交
另需 form-action 'self' 来进行限制
connect-src:限制能通过脚本接口加载的URL。
font-src:限制通过@font-face加载的字体源。
frame-src: 限制通过类似<frame> 和<iframe> 标签加载的内嵌内容源。
img-src: 限制图片和图标源
media-src:限制通过<audio> 或<video> 标签加载的媒体文件源。
object-src:限制通过 <object>, <embed> ,<applet> 标签加载源。
script-src:限制javascript 源。
style-src:限制层叠样式表文件源。
其他指令参考:Content-Security-Policy
三、快速入门案例
csp.js
const http = require("http")
const config = require("./config/config")
const fs = require("fs");
const server = http.createServer((requestMsg, response) => {
if(requestMsg.url === "/") {
fs.readFile("./test.js", (err, data) => {
//问题:Chrome Content-type:"application/x-javascript——》document
response.writeHead(200, "ok", {
"Content-type": "application/x-javascript",
"Content-Security-Policy": "script-src 'self';form-action 'self'"
})
response.end(data);
})
}else{ //
response.writeHead(200,"ok",{
"Content-type":"application/x-javascript"
})
response.end("console.log(123)");
}
})
server.listen(config.port, config.host, () => {
console.log(`server starting at ${config.host}:${config.port}`)
})
test.js
console.log('abc')
csp.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
img{
width: 100px;
}
</style>
</head>
<body>
<form action="https://cdn.bootcss.com/jquery/3.3.1/jquery.slim.min.js">
<input type="submit" value="提交">
</form>
<img src="https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3012445745,1904104267&fm=27&gp=0.jpg" alt="">
</body>
<script>
console.log("我是内联脚本");
</script>
<script src="/dhakdhaskj"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.slim.min.js"></script>
</html>
测试结果:
点击提交后:
表示default-src
无法限制form表单的提交