高级前端
http
【Q267】CSP 是干什么用的了

CSP 是干什么用的了

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 269 (opens in a new tab)

Author 回答者: rex-ll (opens in a new tab)

http://www.ruanyifeng.com/blog/2016/09/csp.html (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

CSP 只允许加载指定的脚本及样式最大限度地防止 XSS 攻击,是解决 XSS 的最优解。CSP 的设置根据加载页面时 http 的响应头 Content Security Policy 在服务器端控制。

  1. 外部脚本可以通过指定域名来限制:Content-Security-Policy: script-src 'self'self 代表只加载当前域名
  2. 如果网站必须加载内联脚本 (inline script) ,则可以提供一个 nonce 才能执行脚本,攻击者则无法注入脚本进行攻击。Content-Security-Policy: script-src 'nonce-xxxxxxxxxxxxxxxxxx'

通过 devtools -> network 可见 github 的 CSP 配置如下:

Content-Security-Policy: default-src 'none';
  base-uri 'self';
  block-all-mixed-content;
  connect-src 'self' uploads.github.com www.githubstatus.com collector.githubapp.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com cdn.optimizely.com logx.optimizely.com/v1/events wss://alive.github.com;
  font-src github.githubassets.com;
  form-action 'self' github.com gist.github.com;
  frame-ancestors 'none';
  frame-src render.githubusercontent.com;
  img-src 'self' data: github.githubassets.com identicons.github.com collector.githubapp.com github-cloud.s3.amazonaws.com *.githubusercontent.com;
  manifest-src 'self';
  media-src 'none';
  script-src github.githubassets.com;
  style-src 'unsafe-inline' github.githubassets.com;
  worker-src github.com/socket-worker.js gist.github.com/socket-worker.js

相关链接

Author 回答者: zzetao (opens in a new tab)

Content Security Policy (CSP)

介绍:

  1. 解决 XSS 最优办法
  2. 可以设置信任域名才可以访问 script / audio / video / image ...

防止 XSS 例子: 攻击者通过 恶意脚本(假设有执行外部脚本) 注入到系统内,显示给访问用户,以此来获取用户信息 我们可以通过 CSP 来设置信任域名才可以执行 .js 脚本。

如何设置:

  1. HTTP 请求头
  2. Meta 标签

MDN:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CSP (opens in a new tab)

兼容性:IE >= 10