HTTP协议原理+实践

3-10 CSP

2018-12-06  本文已影响0人  伯纳乌的追风少年

Content-Security-Policy:内容安全策略

作用
限制方式
资源类型
内容安全策略文档:https://developer.mozilla.org/zh-CN/docs/Web/Security/CSP

总结

'Content-Security-Policy':'default-src http: https:'  //只加载外链资源
'Content-Security-Policy':'default-src \'self\'' //只加载同域下的外链资源(包括图片等所有资源)
'Content-Security-Policy':'script-src \'self\'' //只加载同域下的script资源
'Content-Security-Policy':'default-src \'self\' https://cdn.bootcss.com'  //只加载同域或指定域名下的外链资源
'Content-Security-Policy':'default-src \'self\'; form-action \'self\''   //只加载同域下的外链资源,form表单只能提交到本地
'Content-Security-Policy':'acript-src \'self\'; form-action \'self\'; report-uri /report' //将不符合条件的资源请求提交报告给服务器/report地址下(资源请求被block掉)
'Content-Security-Policy-Report-Only':'acript-src \'self\'; form-action \'self\'; report-uri /report' //将不符合条件的资源提交报告给服务器/report地址下(资源请求不被block掉)

资源加载被block掉 内链script和非本域下外链的script被block掉
report内容

内容安全策略也可写在html的meta标签里:

<meta http-equiv="Content-Security-Policy" content="connect-src 'self'; form-action 'self'">

report-uri不可写在meta标签里


demo

//html
<html>
<head>
  <title>3-10 CSP</title>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
  <meta http-equiv="Content-Security-Policy" content="connect-src 'self'; form-action 'self';">
</head>
<body>
  <div>this is content</div>
  <form action='https://www.baidu.com/' id="form" method="POST" enctype='multipart/form-data'>
    <input type="submit">
  </form>
  <img src="http://www.baidu.com/img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png?qua=high&where=super">
</body>
<script>
  console.log("this is a inline script")
  fetch('http://baidu.com')
</script>
<script src="/test.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/core.js"></script>
</html>


//server.js
const http=require('http');
const fs=require('fs')
const zlib=require('zlib')

http.createServer(function(request,response){
    const html=fs.readFileSync('test.html')
    if (request.url==='/') {
      response.writeHead(200,{
        'Content-Type':'text/html',
        // 'Content-Security-Policy':'default-src http: https:'
        // 'Content-Security-Policy':'default-src \'self\''
        // 'Content-Security-Policy':'default-src \'self\' https://cdn.bootcss.com'
        // 'Content-Security-Policy':'default-src \'self\'; form-action \'self\''
        // 'Content-Security-Policy':'acript-src \'self\'; form-action \'self\';'
        // 'Content-Security-Policy':'acript-src \'self\'; form-action \'self\'; report-uri /report'
        'Content-Security-Policy-Report-Only':'acript-src \'self\'; form-action \'self\'; report-uri /report'
      })
      response.end(html) 
    }else{
      response.writeHead(200,{
        'Content-Type':'application/javascript'
      })
      response.end('console.log("loaded script")') 
    };
}).listen(8888)
console.log('server listening on 8888')
上一篇 下一篇

猜你喜欢

热点阅读