Content Security Policy(CSP) is an incremental layer of security which can be used to mitigate XSS and data injection attack. Note that CSP only provides added security. It is not the primary way to defend against XSS. Using CSP , server admin can specify valid sources of executable scripts. and hence reducing the risk of XSS attack.
How to enable CSP
- The webserver must return the Content-Security-Policy HTTP header.
- For example Content-Security-Policy: script-src https://clariyforme.com/ will allow scripts to be downloaded only from clarifyforme.com and will block
-
<script src="https://not-clarifyforme.com/jslib.js"></script>
- inline scripts within scrip tag, for instance
<script> let j = 0; //javascript code </script>
- inline event handlers , for instance
<img id="img1"onclick="someAction()">
- If unsafe-eval is not specified with script-src then following methods will be blocked
- eval() and similar methods that provide string -> code interpretation are disabled by default when CSP is enabled.
- passing string literal to methods like
- setTimeout("alert(\"This will be blocked!\");", 1000);
- setInterval
-
Note that since inline event scripts and inline event handlers are blocked the script code has to be placed in js files and inline event handlers should be replaced with addEventLisnter in the js file. eg
document.getElementById("img1").addEventListener('click', someAction());
Since inline scripts can be blocked with CSP hence there is no question of a variable with user input being present in scripts.