If I have a web app that is vulnerable to XSS in the url (reflected XSS), does CSP protect against this type of XSS?
Ex: when I run www.example.com/<script>alert(1);</script>
in the browser, this will trigger a popup message.
If I have a web app that is vulnerable to XSS in the url (reflected XSS), does CSP protect against this type of XSS?
Ex: when I run www.example.com/<script>alert(1);</script>
in the browser, this will trigger a popup message.
Browsers do not magically execute JavaScript code embedded in the URL path. By itself, the path is just data. If the code from your example is executed, there's a fundamental problem either in the server-side or the client-side application code. Some component fetches the path and inserts it into the page in a way that JavaScript code execution is triggered. This part is what you need to find and fix.
The vulnerability is rather unusual, so I strongly recommend you actually investigate the vulnerability and do not rely on CSP as a workaround.
script
elements inserted using innerHTML
do not execute when they are inserted, and other JavaScript methods like setHTML
sanitize the input. So either you're using a very old browser, or the application code is doing extra steps to be vulnerable, e.g., it calls eval
with untrusted data.None of this can be fixed with CSP. CSP is not a replacement for correct code. It's a last-ditch effort in modern browsers to temporarily stop XSS attacks until the vulnerability has been fixed. In this particular case, it would likely catch the attack, but this
The source of the XSS script (e.g. URL or database) does not matter for CSP. A good CSP can protect against most XSS vulnerabilities, but not all. For example, a CSS that does not allow unsafe-inline
would prevent you against reflecting the XSS snippet in the html file or inserting it via innerHTML
. However, you could still be vulnerable if your server e.g. serves a JavaScript file dynamically and somehow includes the XSS script there.