Chrome未报告CSP违规

ttisahbt  于 2023-04-27  发布在  Go
关注(0)|答案(1)|浏览(173)

出于某种原因,Chrome(或者至少我的Chrome)没有报告CSP违规。它正确地拒绝显示禁止的内容,但它没有报告违规。通过比较,Firefox报告违规就好了。
Consider this page.您的浏览器不应该在该页面中显示图像,因为该图像来自禁止的URL。Chrome在这方面做得很好。然而,Chrome不遵守report-to或report-uri指令(我有两个)。同样,Firefox遵守这些指令。
我知道浏览器可能会选择不报告冗余的违规行为,但这里不是这样的。I'vetriedusingdifferenturls和它们都不产生报告。
我使用的是Chrome版本75.0.3770.90(Official Build)(64-bit)
任何帮助都很感激。

pobjuy32

pobjuy321#

您可以侦听“securitypolicyviolation”事件并手动报告

if(window.chrome /* and if not setting report-to using HTTP response headers */) {
  document.addEventListener('securitypolicyviolation', (e)=> {
    let reportToUrl='https://example.com/csp-reports'; // change it
    fetch(reportToUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/csp-report'
      },
      body: JSON.stringify({
        'csp-report':{
          'blocked-uri': e.blockedURI,
          'document-uri': e.documentURI,
          'original-policy': e.originalPolicy,
          'referrer': e.referrer,
          'script-sample': e.sample,
          'source-file': e.sourceFile,
          'violated-directive': e.violatedDirective
        }
      }),
      credentials: "omit",
      cache: "no-cache",
      referrerPolicy: "no-referrer"
    });
  });
}

2023年更新

下面的HTTP响应头应该可以工作。
第一:

Report-To: {  "group": "csp-endpoint",
              "max_age": 5,
              "endpoints": [
                { "url": "https://example.com/csp-reports" }
              ] }

然后

Content-Security-Policy: report-to csp-endpoint;

Content-Security-Policy-Report-Only: report-to csp-endpoint;

相关问题