Content Security Policy
Content Security Policy abbreviated as CSP, is an added layer of security to HTML that helps in protecting against XSS and data injection attacks.
CSP is backward compatible. Simply the browsers those do not support CSP, will ignore it and function as usual. When a CSP header is not detected by the browser those support CSP, it will use default same origin policy.
In order to configure CSP, your webserver should be sending the CSP header along with the response. Alternatively a meta tag can be configured as well on page to configure a content policy.
CSP not only can allow only specific domains to load contents/scripts but it can also restrict the protocols those can be used. For example a webserver can set CSP header that states all the contents can only be served using HTTPS only.
A CSP can be configured as shown below with multiple directives separated by ; with directives and their values enclosed in double quotes.
Header always set Content-Security-Policy "default-src 'self'; script-src *; style-src *; font-src *;img-src *"
Below are the different types of directives.
- Fetch Directives
- Document Directives
- Navigation Directives
- Reporting Directives
- Other directives
The directives and their definitions with examples can be found at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
also https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
Content-Security-Policy header can be configured more than once. Adding additional policies can only further restrict the capabilities of the protected resource. So if one CSP configuration says content-src can be self and other says content-src can be some other domain, the one with self will be preferred as it add into the restriction.
One of the usages I came across was related to iframes. We had to restrict how iframes are loaded in the pages. For which there were two options. Either we use x-frame-options CSP. However, in x-frame-options we can not specify multiple domains which can load the frames. Also the option perticular to this configuration is obsolate in x-frame-options. Hence we chose to configure CSP as shown below. Where site1, site2, site3 are the domains from where frames can be loaded.
Header always append Content-Security-Policy "frame-src site1 site2 site3;"
Please check this page for browser compatibility — https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP#browser_compatibility