Browser Security: Content Security Policy (CSP)
What is Content Security Policy?
It is a security standard implemented in HTTP response headers to protect websites against XSS attacks or any attempts to bypass same-origin policy.
To understand this, let us first understand what iFrame injection is.
Understand iFrame Injection
iframe is a HTML tag that enables a web page to be redirected to a different web address at any given time.
That being said, this allows attacker to inject iframe into your website and redirect your visitors to his/her malicious site. Here is an example of the attack:

How to Exploit iFrame Vulnerability
We can always check if a certain website is vulnerable by exploiting the search bar.
Websites that allow the user to modify iframe will most likely be vulnerable to XSS.
The easiest way is to input this into the search bar and see if it triggers the alert.
<iframe src=”javascript:alert(`xss`)”>
Content Security Policy Configuration
The main purpose of CSP is then to restrict web content sources by rejecting any content from sources that are not explicitly whitelisted using any of the directives specified.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src provides a very detailed guidelines and explanations on how CSP should be configured:
Given this CSP header:
Content-Security-Policy: script-src https://example.com/
the following script is blocked and won’t be loaded or executed:
<script src="https://not-example.com/js/library.js"></script>
Note that inline event handlers are blocked as well:
<button id="btn" onclick="doSomething()">
You should replace them with addEventListener
calls:
document.getElementById("btn").addEventListener('click', doSomething);
Note: Disallowing inline styles and inline scripts is one of the biggest security wins CSP provides. To allow inline scripts and inline event handlers, 'unsafe-inline'
, a nonce-source or a hash-source that matches the inline block can be specified.
Content-Security-Policy: script-src 'unsafe-inline';
The above Content Security Policy will allow inline <script>
elements
<script>
var inline = 1;
</script>
You can use a nonce-source to only allow specific inline script blocks:
Content-Security-Policy: script-src 'nonce-2726c7f26c'
You will have to set the same nonce on the <script>
element:
<script nonce="2726c7f26c">
var inline = 1;
</script>
Note: Best practice in configuring CSP is always removing any instances of “unsafe-” directives and “blob, data, filesystem” sources.
You can also specify data schemes (not recommended).
data:
Allowsdata:
URIs to be used as a content source. This is insecure; an attacker can also inject arbitrary data: URIs. Use this sparingly and definitely not for scripts.mediastream:
Allowsmediastream:
URIs to be used as a content source.blob:
Allowsblob:
URIs to be used as a content source.filesystem:
Allowsfilesystem:
URIs to be used as a content source.