The Content Security Policy (CSP) feature allows web developers to define a fine-grained set of policies concerning the capability of several components of a web application. It offers a robust defense in depth layer to existing countermeasures in the application, with its primary benefit being the countering of XSS and injection-driven attacks. Since it is a client-side feature, and, moreover, a perpetually evolving one, developers cannot solely rely on its presence. Furthermore, even though it is designed to be backwards compatible, users might still not be using a browser that fully supports it. CSP can be thought of as a last resort safety net when everything else fails.
Having said that, following associated best practices by employing effectively-configured CSP into a web application is an important measure. Indeed, recommendations from standard-setting organizations, such as the World Wide Web Consortium (W3C) from which the CSP emerged, are the culmination of pooled best-practice and lessons learned. I.e. standards and recommendations generally exist for a good reason.
In most cases, instructing the webserver to return one particular header,
Content-Security-Policy, is sufficient when implementing the standard. This header supports quite an elaborate list of directives and can be used to fine-tune the allowed origin for scripts and other resources and a few other aspects of the web page behavior.
Given the fact that XSS is still a highly prevalent vector of compromise after so many years, it is prudent to construct as many layers of defence as possible in its path so long as the measures don’t break the functionality of the web app. To wit, proficient implementation is paramount to any defence in depth approach.
The recommendation is to start with a very tight CSP rule set, and then increasingly relax the restrictions according to what is and isn’t required by the web application. This rule set will incorporate an allowlist, indicating what the client can and can’t accept. As part of this construction, it is important to ascertain which directives are available and what keywords they take, and also to consider harmful input elements (such as
eval() and inline code).
For example, if the web page is not loading any remote resources, then it is advisable to set
This might mean that if the web page is using inline scripts like
<script>...</script>, or handlers like
'unsafe-inline', the CSP rule will block this instance.
CSP can be added either via an HTTP header or
<meta> tag, which, applied to the example above, looks like:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
Finally, notifying the server of instances where untrusted resources have been blocked is a smart way of identifying and halting malicious injection from occurring.
- OWASP ASVS: 14.4.3