Table of Contents
Content Security Policy (CSP) is a powerful security feature that helps protect websites from cross-site scripting (XSS) attacks. Using nonces and hashes within CSP policies enhances security by allowing only trusted scripts to execute.
Understanding CSP Nonces and Hashes
Nonces and hashes are two methods to specify which scripts are allowed to run on your website. They help prevent malicious scripts from executing even if an attacker manages to inject code.
What is a CSP Nonce?
A nonce (number used once) is a unique token generated for each page load. You add this token to your CSP header and to each inline script you want to allow. Only scripts with the correct nonce will execute.
What is a CSP Hash?
A hash is a cryptographic checksum of a script’s content. You generate a hash of your trusted scripts and include them in your CSP header. Scripts matching the hash are permitted to run.
Implementing Nonces in Your Website
To use nonces, follow these steps:
- Generate a unique nonce value for each page request.
- Include the nonce in your CSP header, e.g.,
Content-Security-Policy: script-src 'nonce-.' - Add the same nonce attribute to your inline scripts, e.g.,
<script nonce=".">...</script>
This setup ensures only scripts with the correct nonce will execute, blocking unauthorized scripts.
Implementing Hashes in Your Website
To use hashes, follow these steps:
- Calculate the hash of your trusted script content using algorithms like SHA-256.
- Include the hash in your CSP header, e.g.,
script-src 'sha256-.' - Ensure your scripts match the hash exactly; otherwise, they will be blocked.
This method is ideal for static scripts that do not change frequently.
Best Practices for Using Nonces and Hashes
To maximize security:
- Use nonces for inline scripts that change dynamically.
- Use hashes for static scripts that rarely change.
- Regularly update your nonces and hashes to reflect code changes.
- Combine CSP with other security measures like HTTPS and secure headers.
By carefully implementing nonces and hashes, you can significantly reduce the risk of malicious script execution on your website.