HTTP’s Content-Security-Policy (CSP) mechanism provides a means to instruct web browsers to apply various restrictions to the content returned by any given HTTP request. Such content could actually be under the control of a malicious party if a vulnerability such as Cross-Site Scripting (XSS) exists, which allows attackers to insert arbitrary script code into HTML due to improper handling of input.
A CSP policy can instruct browsers to only execute script code from particular sources, not the vulnerable returned content, and thereby providing a secondary layer of protection against XSS attacks.
There are some circumstances under which CSP policies can be evaded, however. This article will examine how to defeat a CSP policy abusing a JSONP endpoint that resides on a site that the CSP policy considers trusted.
A Demonstration of Breaking CSP with JSONP Endpoints
First, let’s take a look at a page on our example website at example.com/csp, which contains a trivial XSS vulnerability.
A request with a XSS payload:
And the response with the payload returned verbatim:
Needless to say, this payload executes in a browser.
Now let’s try mitigating this using CSP. As part of our remediation efforts, we add a Content-Security-Policy response header as a safeguard against any XSS vulnerabilities on our site. We whitelist m.addthis.com because we use AddThis on some other pages on our example.com site.
Here’s the same response to the above request with our CSP:
We can now see that, thanks to CSP, the payload no longer executes in a browser. Furthermore, a violation error message is logged in the console: