Cross-Site Scripting and Content Security Policy
Cross-site scripting (XSS) lets an attacker run JavaScript in other users' browsers: stealing data from the page, performing actions as the user or defacing the site.
Types
| Type | How it happens |
|---|---|
| Stored | malicious content saved (a comment, a profile name) and shown to others |
| Reflected | input from the URL echoed back in the response |
| DOM-based | client-side JavaScript writes untrusted data into the page |
Prevention: encode on output
- Server templates: Jinja2 and React escape by default. Never mark user content
|safeor pass it todangerouslySetInnerHTML. - JavaScript: use
textContent, notinnerHTML, for untrusted data. - Markdown: render with an escaping renderer, or sanitise the resulting HTML with an allowlist (bleach, DOMPurify).
- URLs: allow only
http(s)links;javascript:URLs inhrefexecute code. - Attributes: always quote them; the template engine escapes quotes.
Content Security Policy
CSP tells browsers which sources may load scripts, styles and other resources. Even if XSS slips through, a strict CSP can stop it running.
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.jsdelivr.net;
style-src 'self' https://fonts.googleapis.com; img-src 'self' data:;
object-src 'none'; base-uri 'self'; frame-ancestors 'none'
- Move inline scripts into files (or use nonces) so you can drop
'unsafe-inline'. - Start with
Content-Security-Policy-Report-Onlyto see what would break, then enforce. frame-ancestors 'none'also prevents clickjacking.
Cookies
Session cookies should be HttpOnly (JavaScript cannot read them), Secure and SameSite=Lax or Strict. That limits what an XSS payload can steal.
Testing for XSS
Submit harmless markers like "><svg onload=alert(1)> into every input you are authorised to test, then view every place that data appears (including admin pages and emails). Scanners automate this for reflected cases; stored and DOM XSS often need manual review.
Exercise
In a local practice app, find a stored XSS in comments, fix it with escaping and sanitised Markdown, then add a CSP that would have blocked the payload even before the fix. Confirm in the browser console.
Check yourself
- What is the difference between stored and reflected XSS?
- Why are
HttpOnlycookies important? - How does CSP reduce XSS impact?
I tuoi progressi sono salvati solo in questo browser.
Invia per la revisione (10 punti)