CSP-内容安全策略

Content-Security-Policy

服务端可通过设置响应头CSP来实现:1.限制资源获取;2.报告资源获取越权

格式

[资源1][空格][关键字1];[资源2] [关键字2];…
如:

'Content-Security-Policy': 'script-src \'self\'; form-action \'self\'; report-uri /report'

ps: \表转义,避免node.js中因引号使字符串被分割

一、限制资源获取

资源

1.所有资源(default-src)
2.指定资源类型限制(connect-src/img-src/script-src/style-src/media-src…)
3.其他

关键字

  1. 'self':代表和文档同源,包括相同的 URL 协议和端口号。两侧单引号是必须的。
  2. http: https::代表仅允许加载通过http或https协议引入的资源
  3. http://www.baidu.com:允许引入资源的指定域名

常用限制

1.限制inline-script(html行内js):script-src http: https:
2.限制其他域script的引入:script-src \'self\'
3.限制指定网站资源引入:default-src \'self\' https://cdn.bootcss.com/
4.限制form表单的外部地址跳转:form-action \'self\'

此处不做展开,详见 MDN CSP内容安全策略
XSS:往web页面插入恶意script代码,达到攻击用户的目的

二、触发限制时向服务端汇报

  1. 限制并发送报告:Content-Security-policy: report-uri /report
  2. 不限制并发送报告:Content-Security-policy-Report-Only:default-src \'self\' report-uri /report

web页面设置CSP

通过meta设置:

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

猜你喜欢

转载自blog.csdn.net/qq_31393401/article/details/81239413