Content-Security-Policy (CSP) is a browser security mechanism that helps mitigate web attacks such as cross-site scripting (XSS) and clickjacking. It does so by
Note: To know more about XSS, please refer to this answer.
There are several ways CSP can be used to prevent script execution, as listed below:
Block all script execution
Use script hashes
Use script nonces
To exploit vulnerabilities in an application, an attacker could use several payloads such as in-line code, code block, and remote code files. CSP limits what code can be executed through an HTTP response header with a minimal policy configuration to prevent this. The policy can consist of more than one directive. A sample header is shown below:
The header above only allows scripts to be loaded and executed from the same origin as itself. This prevents the execution of any malicious code regardless of its payload. Consider the following in-line code:
<img src="picture.png" onerror="evilFunction()">
Although this code is present on the page, the browser cannot verify its origin. The browser also knows that it was not loaded from the same origin as itself. Hence, it will not be executed.
While this is a relatively straightforward method, the prevention of all potentially harmful Javascript code can be incompatible with many applications, especially those that rely on in-line event handlers, such as onclick
.
This method allows the execution of specified Javascript code. The CSP policy header enables the addition of the hash of a script block, as shown below:
Content-Security-Policy: script-src 'sha256-hashValue'
On the first page load, the browser calculates the hash of the script block and compares it to the hash in the CSP header. If it matches, the code is allowed to be executed. This is a safe way to ensure that legitimate code is loaded. However, it only approves a single block of code. Moreover, this method only works for in-line code and code blocks, not remote code files.
Similar to the previous method, this method includes the use of nonces, a random value, to allow the execution of a certain code, as shown below
Content-Security-Policy: script-src 'rand0mNumber123'
The CSP policy header is configured with a nonce attribute, which should match the nonce specified in the script block.
<script nonce="rand0mNumber123">// insert code here</script>
Script nonces can be used for remote code files as well. However, to be effective, the nonce must be regenerated on each page load to prevent guessing by the attacker.
It is possible to bypass CSP by allowing the execution of all in-line code. We do so by including the unsafe-inline
value in the header, as shown below:
Content-Security-Policy: script-src 'self' 'unsafe-inline'
As a result, all in-line code, including malicious code, will be loaded and executed.
Free Resources