Content Security Policy in a Nutshell
Content Security Policy(CSP) is a layer of security used to mitigate attacks such as Cross Site Scripting(XSS) and data injection
A web page can interact with different web contents in different manner. Few of them are loading and execution of inline and external JS & CSS files, making AJAX calls, loading resources like images/fonts to the web application. In this manner so many contents are associated with a web application.
There can be attacks such as Cross Site Scripting(XSS) and code injection due to above mentioned content interactions with a web page. In order to prevent these attacks Content Security Policy security layer is added.
CSP can be implemented using two methods
- Using HTTP Response Header (
Content-Security-Policy
) - Using meta element in html file ( <meta></meta> )
When a CSP rule is added to a particular web page using one of aforementioned methods, the web browser check those policies and act according to that.
Below mentioned are some common CSP examples
- All content will be coming from the site’s own origin
Content-Security-Policy: default-src 'self'
2. All content will be coming from the site’s own origin and the subdomains of example.com
Content-Security-Policy: default-src 'self' *.example.com
3. All content will be coming from example.com through TLS secure channel only
Content-Security-Policy: default-src https://example.com
4. All content will be coming from example.com and images can be coming from any location
Content-Security-Policy: default-src https://example.com; img-src *
5. Allow inline script execution (scripts written inside <script> tags)
Content-Security-Policy: script-src 'unsafe-inline'This method allows all the inline scripts, but hash value of a script can be given to enforce more security.Content-Security-Policy: script-src '<HashAlgorithm>-<Base64 encoded hash of the script>'
Test a Sample Policy
In this HTML code CSP is set to default-src ‘self’, therefore browser is not going to load any external resource or execute any inline script.
Open the above HTML code in a browser. Then you will see two error messages in your browser console saying it can not load external jquery file and can not execute the inline script.
After that please replace the meta tag with the below one and reload the browser. Then you will see that everything get loaded/ executed properly.
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src * 'unsafe-inline' ;">
In this manner you can test this Content Security Policy.
References:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy