简体   繁体   English

在普通 html 文件中对 script-src 和 style-src 使用 CSP 元标记

[英]Using CSP meta tag for script-src and style-src in normal html file

Here is my demo.html file where I am using CSP meta tag and external js and css files.这是我的 demo.html 文件,其中我使用 CSP 元标记和外部 js 以及 css 文件。

demo.html演示.html

 <;DOCTYPE html> <html> <head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; object-src 'none'; style-src 'self'; script-src 'sha256-Ql3n7tC/2D6wSTlQY8RcOKXhq02zfdaSDviOhpvbYWw='. " > <script src="scripts.js"></script> </head> <body> <p>Hello World</p> <h2>JavaScript Alert</h2> <button>Try it</button> </body> </html>

Here is my js file这是我的js文件

 console.log("Hello");

Now I have used CSP meta tag and which accept sha256 hashcode to pass the js file ie script-src and I have calculated the sha256 hashcode ie 'sha256-Ql3n7tC/2D6wSTlQY8RcOKXhq02zfdaSDviOhpvbYWw=' which I have written in script-src.现在我使用了 CSP 元标记,它接受 sha256 哈希码来传递 js 文件,即 script-src,我已经计算了 sha256 哈希码,即我在 script-src 中编写的 'sha256-Ql3n7tC/2D6wSTlQY8RcOKXhq02zfdaSDviOhpvbYWw=' But still it is not accepted by the console.但是控制台仍然不接受它。 What can be the problem?可能是什么问题?

SHA is a checksum computed for a specific script and should be loaded with it. SHA 是为特定脚本计算的校验和,应与它一起加载。 Take a look at how it is used in well-known libraries.看看它是如何在知名库中使用的。 eg bootstrap例如引导

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

That what you try is nonce (128 bit) and can look like this:您尝试的是随机数(128 位),看起来像这样:

// Content-Security-Policy: script-src 'dsd14e314df23e2d32r' 

<script nonce="dsd14e314df23e2d32r" src="https://app.domain.com/app.js"></script>

There is 3 issues:有3个问题:

  1. The right hash for console.log("Hello");右边 hash 为console.log("Hello"); is 'sha256-efGKf8oWIWhXl5BsggWDZ+M7Bf5AirxrKOCBujdLAWg=''sha256-efGKf8oWIWhXl5BsggWDZ+M7Bf5AirxrKOCBujdLAWg='

  2. You need to add the integrity= attribute to allow external script via 'hash-value' :您需要添加integrity=属性以通过'hash-value'允许外部脚本:
    <script src="script.js" integrity='sha256-efGKf8oWIWhXl5BsggWDZ+M7Bf5AirxrKOCBujdLAWg='></script>

  3. Firefox browser still does not support 'hash-value' to allow external scripts (Safari - too). Firefox 浏览器仍然不支持'hash-value'以允许外部脚本(Safari 也是如此)。 Therefore use Chrome to observe result.因此使用 Chrome 来观察结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM