跳到主要内容
uencoder

如何Use Content Security Policy 级别 3

Configure strict Content Security Policy (CSP3) 具有 nonces 和 hashes 到 prevent XSS, 数据 exfiltration, 和代码 injection attacks.

问题

你的 web 应用是 vulnerable 到 Cross-Site Scripting (XSS) because inline scripts 和外部 resources 能够是 injected 通过 attackers. 你需要implement strict Content Security Policy (CSP 级别 3) 该 whitelists 仅 trusted 源.

前置条件

  • Understanding 的 XSS attacks 和 injection vectors
  • 熟悉HTTP headers 和 browser 安全 policies
  • Knowledge 的脚本 nonces 和 subresource 完整性

步骤

  1. 1. Start with a restrictive default policy

    Begin with the most restrictive policy: default-src 'none'. This blocks everything by default. Then explicitly allow only what each resource type needs. This deny-by-default approach is more secure than allow-by-default. Use the HTML sanitizer to understand what content needs to be allowed. Start with: Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'

    输入
    default-src 'none'; script-src 'self'; style-src 'self'
    输出
    all external and inline resources blocked except same-origin scripts and styles
  2. 2. Use nonces or hashes for inline scripts

    CSP3 supports nonces (number used once) for inline scripts. Generate a unique random nonce per request, add it to the CSP header (script-src 'self' 'nonce-<random>'), and add the same nonce attribute to each inline script tag: <script nonce='<random>'. This is more secure than 'unsafe-inline'. Alternatively, use hashes: compute SHA256 of the inline script content and add 'sha256-<hash>' to script-src. Use the hash and base64 tools to compute script hashes.

    输入
    inline script: console.log('hello')
    输出
    nonce: rAnd0mN0nc3 | CSP: script-src 'self' 'nonce-rAnd0mN0nc3'
  3. 3. Add strict-dynamic and reporting

    CSP3 'strict-dynamic' allows scripts loaded by trusted (nonced or hashed) scripts to also execute, simplifying third-party library support. Add a reporting directive: report-uri /csp-report or report-to endpoint. The browser sends violation reports to this endpoint without blocking, useful for monitoring before enforcing. Use Report-Only mode first (Content-Security-Policy-Report-Only) to identify violations without breaking the page.

    输入
    script-src 'nonce-rAnd0mN0nc3' 'strict-dynamic'
    输出
    trusted scripts can load dependencies | violations reported to /csp-report
  4. 4. Enforce and test the policy

    Switch from Report-Only to enforcing mode once all violations are resolved. Test with XSS payloads to confirm they are blocked. Add frame-ancestors 'none' to prevent clickjacking (equivalent to X-Frame-Options: DENY). Add upgrade-insecure-requests to force HTTPS. Add require-trusted-types-for 'script' (CSP3 Trusted Types) to prevent DOM XSS via dangerous sinks. Use the HTML escape tool to verify proper output encoding complements CSP.

    输入
    XSS payload: <script>alert(1)</script>
    输出
    blocked by CSP | report: violated script-src 'nonce-...' directive

预期结果

strict CSP 级别 3 策略该 prevents XSS, clickjacking, mixed 内容, 和数据 exfiltration, 具有 violation 监控.

常见错误

Using 'unsafe-inline' for scripts
'unsafe-inline' defeats CSP's XSS protection. Use nonces or hashes (CSP3) instead. If using nonces, 'unsafe-inline' is ignored by browsers anyway.
Using 'unsafe-eval' for dynamic code
'unsafe-eval' allows eval() and new Function(), reintroducing XSS risk. Refactor to avoid dynamic evaluation, or use CSP3 'strict-dynamic' with trusted scripts.
Deploying CSP in enforce mode without testing
Start with Content-Security-Policy-Report-Only, collect violation reports, fix all violations, then switch to enforcing mode. Enforcing immediately can break the application.

排障指引

  • If third-party scripts are blocked, either add their domains to script-src or use 'strict-dynamic' with a nonced loader script that loads them.
  • If inline styles break, use nonces for style-src as well, or move styles to external stylesheets.
  • For single-page applications, ensure the CSP applies to all routes and that dynamic imports are covered by the script-src policy.

安全限制

  • CSP is defense-in-depth — it does not replace proper output encoding and input validation. Both are needed.
  • CSP does not protect against CSS-based data exfiltration in all cases — use 'style-src' restrictions carefully.
  • All policy generation and nonce generation happen server-side; the browser enforces the policy locally.

相关工具

HTML 净化器
基于标签/属性/URI 白名单净化 HTML(移除脚本、事件处理器与不安全 URI)。
工具
HTML 转义器
在线转义或反转义 HTML 特殊字符。免费、隐私本地化、100% 客户端运行。将 & < > " ' 转义为 HTML 实体(&amp; &lt; &gt; &quot; &#39;),防止 XSS 和 HTML 结构破坏,适合用户输入嵌入、模板渲染和代码展示场景。
工具
HTML 属性编码器
编码文本以安全用于 HTML 属性。
工具
HTML 属性解码器
解码 HTML 属性实体。
工具
哈希计算器
计算 MD5、SHA-1、SHA-256 或 SHA-512 哈希,支持十六进制或 Base64 输出。免费、隐私、100% 客户端运行。SHA-256/512 基于 Web Crypto API,MD5 基于 spark-md5,适用于校验和、完整性验证、指纹识别等场景。MD5 与 SHA-1 已不适用于安全场景。
工具
SHA-3 / Keccak 哈希计算器
计算 SHA-3(224/256/384/512)和 Keccak-256 哈希。免费、隐私、100% 客户端运行。
工具
Base64 编码器
将文本或二进制数据编码为 Base64。免费、隐私优先、100% 纯客户端运行。支持 UTF-8、ASCII、Latin1、UTF-16LE 字符集,可处理多语言文本与二进制内容,结果可直接用于 Data URI、邮件附件、JWT 等场景。
工具
随机字节生成器
生成密码学安全的随机字节或整数。免费、隐私优先、100% 纯客户端运行。
工具
HTTP 状态码参考
常见 HTTP 状态码(1xx-5xx)参考表,包含名称、类别和描述。免费、隐私、100% 客户端运行。
工具

相关词条

参考链接