Why use random nonces in your Content Security Policy

Why use random nonces in your Content Security Policy

A Content Security Policy (CSP) is a security standard introduced to prevent Cross-Site Scripting (XSS), clickjacking, and other code injection attacks resulting from execution of malicious content in the trusted web context.

CSPs allow web developers to declare approved sources of content that browsers should be allowed to load on that webpage, thereby enhancing security. However, the mere presence of a CSP is not sufficient, and even when configured it may still leave room for exploitation, given the right circumstances.

It is therefore important to use all supported mechanisms to reduce the above risks, even if we may not be able to completely eliminate them.

One of the most effective mechanisms to address these risks is to use random nonces in your CSPs.

Nonces are random and unique strings generated for each HTTP response which can serve as a one-time password for specifying which scripts are allowed to execute, thereby protecting against various types of attacks, most notably Cross-Site Scripting (XSS) which involves an attacker injecting malicious JavaScript code into web pages viewed by other users, without the knowledge or permission of the website owners.

These scripts can steal cookies, session tokens, or other sensitive information that the browser handles, in some cases potentially completely compromising the target application and its users.

To stop the execution of these scripts the browser enforces the CSP by checking the nonce value specified in the CSP header against the nonce value in each inline script tag:

<script nonce="f7dhj4d63j">
	yourjavascripthere();
</script>         

The above script will only execute if the Content Security Policy had a corresponding entry such as the following one:

script-src 'nonce-f7dhj4d63j';        

Only scripts that have a matching nonce attribute are executed; the nonce serving, as mentioned earlier, as a kind of one-time password.

Any other scripts, including those injected by an attacker, will not have the correct nonce and thus will be blocked from execution: since a new nonce must be generated for each response, the allowed scripts are effectively validated on a per-request basis.

This dynamic nature helps to ensure that even if an attacker could somehow predict or intercept a nonce, it would likely be useless for future requests, preventing the execution of malicious or unauthorised code.

To check if your CSP is valid you can use one of the many tools, such as csp-evaluator.withgoogle.com.

要查看或添加评论,请登录

Edgar ter Danielyan的更多文章

社区洞察

其他会员也浏览了