简体   繁体   中英

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

 <;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

 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. 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. 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:

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

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

There is 3 issues:

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

  2. You need to add the integrity= attribute to allow external script via '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). Therefore use Chrome to observe result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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