Content Security Policy (CSP) is a whitelisting mechanism that allows you to control what behaviour is allowed in a particular page, mitigating the risk of content injection vulnerabilities such as Cross-site scripting.
Below are the goals that CSP aims to do:
The various options you can use to configure CSP are called directives. CSP directives can be spcified using HTTP response header or HTTP Meta tag. The HTTP headers below are defined by the specs:
Content-Security-Policy : Defined by W3C Specs as standard header, used by Chrome version 25 and later, Firefox version 23 and later, Opera version 19 and later.
X-Content-Security-Policy : Used by Firefox until version 23, and Internet Explorer version 10 (which partially implements Content Security Policy).
X-WebKit-CSP : Used by Chrome until version 25
Content-Security-Policy [directive] <value>;
Content-Security-Policy default-src 'self';
In the above example, the default-src directive with self value instructs that it wants all content to come from the website's own origin (excludes subdomain).
<meta http-equiv="Content-Security-Policy" content="default-src 'self';>
When using CSP in a meta tag, you will need to specify the policy within the head section of the HTML document.
Example Scenario: Developers for Example Inc. want to protect themselves against Cross-site scripting attacks. They can mitigate the risk of script injection by insuring that their trusted CDN is the only origin from which script can load and execute. They also want to ensure that no plugins can execute in their page contexts. Following is the Content Secrity Policy for this scenario:
Content-Security-Policy: script-src https://trusted-cdn.example.com/scripts/; object-src 'none'
Below are examples on how you can configure web servers to configure CSP directive usimg HTTP header.
Add the CSP directive in your VirtualHost section or in an .htaccess file.
Header set Content-Security-Policy "default-src 'self';"
Add the CSP directive in your server block. e.g.
server {
listen 443 ssl http2;
...
location / {
...
add_header Content-Security-Policy "default-src 'self';";
...
}
...
}
Add the CSP directive in your web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Content-Security-Policy" value="default-src 'self';" />
</customHeaders>
</httpProtocol>
</system.webServer>
References:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
https://w3c.github.io/webappsec-csp/
https://www.owasp.org/index.php/Content_Security_Policy