Cross-site scripting (XSS) lets an attacker make a victim's browser run their JavaScript on your site. That script can read what the user sees, act as the user and steal session data that is not protected.
Kinds of XSS
- Stored: the malicious input is saved, for example in a comment, and shown to every visitor.
- Reflected: input in a URL or form is echoed straight back in the response.
- DOM-based: client-side code writes untrusted data into the page, for example through
innerHTML.
The main defence: encode on output
Treat data as text unless you explicitly decided otherwise. Encode it for the place where it is inserted: HTML body, HTML attribute, JavaScript string, URL. Modern template engines escape HTML by default, so the danger is in the escape hatches such as raw, html_safe or dangerouslySetInnerHTML.
require "cgi"
comment = "<script>alert(1)</script>"
puts CGI.escapeHTML(comment) # <script>alert(1)</script>In the browser
// Safe: the value is treated as text.
element.textContent = userInput;
// Dangerous: the value is parsed as HTML.
// element.innerHTML = userInput;If you must allow some HTML, such as rich comments, pass it through a well-maintained sanitiser with an allow-list of tags.
Content Security Policy
A CSP header tells the browser which sources of scripts, styles and other content are allowed. A strict policy blocks inline scripts and scripts from unknown origins, so an injected script often fails to run.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-RANDOM'; object-src 'none'; frame-ancestors 'none'A nonce is a random value generated for each response and added to your own script tags. CSP is a second line of defence. It does not replace encoding.
Cookie hardening
Mark session cookies HttpOnly so scripts cannot read them, Secure so they travel only over HTTPS, and set SameSite.
Takeaway
Escape by context, avoid raw HTML insertion, sanitise rich input with an allow-list, and deploy a strict CSP and hardened cookies to limit the damage if something slips through.
Comments