XSS and CSP review
Goal
Make sure user controlled text can never run as script in another user's browser.
A good result fixes the cause with correct output encoding, and adds a CSP as a second layer.
When to use
- The app displays user content: comments, names, rich text, markdown, search terms.
- A scanner or pentest reported reflected or stored XSS.
- The team wants a CSP deployed without breaking pages.
- For the other response headers, use
use_skillwithsecurity-headers.
Steps
- Find the sinks with
rg:innerHTML,outerHTML,insertAdjacentHTML,document.write,dangerouslySetInnerHTML,v-html,[innerHTML],|safe,raw,eval(,new Function(,setTimeout(". - For each sink read the code with
read_fileand trace the value to its origin. Mark user, database, URL parameter or hardcoded. - Prefer safe APIs:
textContent, framework default escaping, andsetAttributefor known attributes. Replace withedit_file. - If HTML must be rendered (rich text, markdown), sanitise on output with a maintained sanitiser such as DOMPurify configured with an allow list. Check its current docs with
read_url. - Check URL contexts:
hrefandsrcfrom users must be restricted tohttps:,http:andmailto:. Ajavascript:URL runs on click. - Check attribute and script contexts: never place user data inside inline event handlers,
<script>blocks orstylewithout the correct encoding for that context. - Check cookies set
HttpOnlyso script cannot read the session even if XSS occurs. - Draft a CSP:
default-src 'self', explicitscript-srcwith nonces or hashes,object-src 'none',base-uri 'self',frame-ancestors, andform-action. - Remove inline scripts and handlers so the policy needs no
'unsafe-inline'for scripts. Use per-response nonces generated with a secure random source. - Deploy as
Content-Security-Policy-Report-Onlyfirst with a report endpoint, review the violations for a few days, then enforce. - Add a test that stores
<img src=x> style content and asserts it renders as text. - Report each sink as fixed, safe with reason, or open.
Gotchas
- A CSP with
'unsafe-inline'or'unsafe-eval'for scripts gives little protection. It reduces damage only if script execution is controlled. - Encoding must match the context: HTML text, attribute, URL, JavaScript and CSS each need different handling.
- Sanitising on input and trusting it everywhere later breaks when the same data feeds a different context. Encode at output.
- Frameworks escape by default, and the escape hatches (
dangerouslySetInnerHTML,v-html) are the places to search. - DOM XSS reads
location.hashordocument.referrerand never touches the server, so server templates look clean. - Allowing a whole CDN host in
script-srcmay allow attacker-hosted files on the same host. Use nonces or hashes.
Output
- A sink table: location, source, context, fix.
- The proposed CSP header with a one-line reason per directive and the rollout plan in report-only mode.
- Tests added.
