CSP, or Content Security Policy, is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. In short, you can add this policy using either a <meta> tag or by setting additional headers in your HTTP response, and using the policy you’ll limit the origins for resources for that HTTP request. For example:
- script-src ‘self’ allows loading scripts from the current domain
- child-src https://youtube.com allows the use of <iframe> tags pointing towards YouTube
- style-src ‘self’ https://maxcdn.bootstrapcdn.com allows loading CSS files from the current source and from a CDN.
If you want to read up on CSP, I suggest heading over to http://www.html5rocks.com/en/tutorials/security/content-security-policy/
Now, I was trying out some things concerning CSP and inline scripts. You could add ‘unsafe-inline’ to the script-src source list to allow all inline scripting (except eval and other bad stuff, you need ‘unsafe-eval’ in that case), but that is exactly what you would want to avoid. Instead, you can opt to do one of these things:
- Generate a nonce for each inline script. A nonce means: a unique and hard to predict stream of bytes, different for each script, each page and each request!
A nonce could be base64 encoded and look like RJ6bGjm5EO/X8pImZjvjeAexFVei9IvzNFCGw5lQUa0=
You would need to add that nonce to the script using the nonce attribute, and also to the script-src source list using ‘nonce-RJ6bGjm5EO/X8pImZjvjeAexFVei9IvzNFCGw5lQUa0=’
- Calculate the SHA256, SHA384 or SHA512 digest of each inline script (including all whitespace, but excluding the opening and closing script tags). Like the nonce, you’d need to add these digests to the script-src source list using ‘sha256-0ZMofb7eMqkB9IFHnGVZ6Z4chjplAavgi09shinNehs=’ for example.