Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Content-Security-Policy的理解 #1

Open
zhaoqize opened this issue Dec 30, 2016 · 0 comments
Open

Content-Security-Policy的理解 #1

zhaoqize opened this issue Dec 30, 2016 · 0 comments

Comments

@zhaoqize
Copy link
Owner

zhaoqize commented Dec 30, 2016

Content-Security-Policy介绍

Content-Security-Policy 中文的意思是 网页安全政策,主要用来防止XSS攻击。

如何防范XSS攻击的

通过 Content-Security-Policy 网页的开发者可以控制整个页面中 外部资源 的加载和执行。

比如可以控制哪些 域名下的静态资源可以被页面加载,哪些不能被加载。

这样就可以很大程度的防范了 来自 跨站(域名不同) 的脚本攻击。

它还有个非常响亮的称号:XSS攻击的终结者😄

如何使用

对于页面开发者来说,只需要在页面中设置

<meta http-equiv="Content-Security-Policy" content="">

类别

key 作用
default-src 给下面所有的规则设定一个默认值
script-src 外部脚本
style-src 样式表
img-src 图像
media-src 媒体文件(音频和视频)
font-src 字体文件
object-src 插件(比如 Flash)
child-src 框架
frame-ancestors 嵌入的外部资源(比如、<iframe>、和)
connect-src HTTP 连接(通过 XHR、WebSockets、EventSource等)
worker-src worker脚本
manifest-src manifest 文件

script-src

script-src 作用
unsafe-inline 允许执行页面内嵌的<script>标签和事件监听函数
unsafe-eval 允许将字符串当作代码执行,比如使用eval、setTimeout、setInterval和Function等函数
nonce 每次HTTP回应给出一个授权token,页面内嵌脚本必须有这个token,才会执行
hash 列出允许执行的脚本代码的Hash值,页面内嵌脚本的哈希值只有吻合的情况下,才能执行

value 作用
主机名 example.org,https://example.com:443...
路径名 example.org/resources/js/
通配符 .example.org,://.example.com:(表示任意协议、任意子域名、任意端口)
协议名 https:、data:
关键字'self' 当前域名,需要加引号
关键字'none' https:、data:
协议名 禁止加载任何外部资源,需要加引号

下面来个具体的例子:

<meta http-equiv="Content-Security-Policy" content="
default-src http: https:  *.meituan.com 'self' 'unsafe-inline' ;
style-src 'self' 'unsafe-inline' *.meituan.com;
script-src 'self' 'unsafe-inline' 'unsafe-eval' ;
">
  • 默认设置(default-src):信任 http ,https协议资源,信任当前域名资源,信任符合*.meituan.com的域名资源
  • CSS设置(style-src):信任当前域名资源,允许内嵌的CSS资源,信任来自*.meituan.com下的CSS资源
  • JS设置(script-src):信任当前域名资源,允许内嵌的JS执行,允许将字符串当作代码执行

参考

@zhaoqize zhaoqize changed the title test1 zlazyLoad代码 Jan 16, 2017
@zhaoqize zhaoqize changed the title zlazyLoad代码 Content-Security-Policy入门 Nov 24, 2017
@zhaoqize zhaoqize changed the title Content-Security-Policy入门 Content-Security-Policy的理解 Nov 24, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant