Content Security Policy (CSP)

控制页面可以使用哪些资源

外部静态资源

css, js, 预加载, 强制使用https

页面内功能

<script>, <style>, 弹窗

页面内嵌页面

<iframe> <embed> <object>

互相嵌套

用响应header 和<meta> 都可配置

# header
Content-Security-Policy: default-src 'self'; img-src https://*; child-src 'none';

# <meta>
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src https://*; child-src 'none';">

Content-Security-Policy 的策略值(响应头的值)

worker-src, child-src 的细分

frame-src, child-src 的细分

script-src-elem, script-src 的细分

script-src-attr, script-src 的细分

style-src-elem, style-src 的细分

style-src-attr, style-src 的细分

form-action, 限制<form> 的action 属性的值

report-uri, 废除, 请使用report-to

require-sri-for, 列表页显示实验中, 详细页显示已过时, 我太难了

require-trusted-types-for, 实验, 无文档

trusted-types, 实验, 无浏览器支持

Worker 不受当前文档的CSP 约束, 要对其资源的单独设置

设置多种安全策略时, 执行最严格那个

更多示例

只允许通过 https加载这些资源 (images, fonts, scripts, etc.)

// header
Content-Security-Policy: default-src https:

// meta tag
<meta http-equiv="Content-Security-Policy" content="default-src https:">

允许内联但是只能使用https 加载资源, 并且禁止插件

Content-Security-Policy: default-src https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'

违反策略时只收集报告不真正实时

Content-Security-Policy-Report-Only: default-src https:; report-uri /csp-violation-report-endpoint/

caddy 使用过的

a.com {
    root /var/www
    header / {
        # Enable HTTP Strict Transport Security (HSTS) to force clients to always
        # connect via HTTPS (do not use if only testing)
        Strict-Transport-Security "max-age=31536000;"
        # Enable cross-site filter (XSS) and tell browser to block detected attacks
        X-XSS-Protection "1; mode=block"
        # Prevent some browsers from MIME-sniffing a response away from the declared Content-Type
        X-Content-Type-Options "nosniff"
        # Disallow the site to be rendered within a frame (clickjacking protection)
        X-Frame-Options "DENY"

        Content-Security-Policy: "default-src 'none'; font-src '<https://fonts.googleapis.com>'; img-src 'self'; object-src 'none'; script-src 'self'; style-src 'self';"
    }
}

参考

CORS & CSP笔记

https://www.cnblogs.com/xiaoxiaoleo/p/12016735.html

What is the difference between CORS and CSPs?

https://stackoverflow.com/questions/39488241/what-is-the-difference-between-cors-and-csps

Content Security Policy 入门教程

http://www.ruanyifeng.com/blog/2016/09/csp.html

8.3. Usage of "'unsafe-hashes'"

https://www.w3.org/TR/CSP3/#unsafe-hashes-usage

Web App Manifest(渐进式程序的manifest.json 文件)

https://developer.mozilla.org/zh-CN/docs/Web/Manifest

Sandboxing, IFrame, and allow-same-origin

https://stackoverflow.com/questions/31184505/sandboxing-iframe-and-allow-same-origin

What's the difference between frame-ancestors and child-src?

https://security.stackexchange.com/questions/143964/whats-the-difference-between-frame-ancestors-and-child-src/144186

How to Implement CSP frame-ancestors in Apache, Nginx and WordPress?

https://geekflare.com/csp-frame-ancestors-configuration/