Web Security & VulnHawk Mastery

Cross-Site Scripting and Content Security Policy

35 мин

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 |safe or pass it to dangerouslySetInnerHTML.
  • JavaScript: use textContent, not innerHTML, 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 in href execute 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-Only to 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 HttpOnly cookies important?
  • How does CSP reduce XSS impact?

Ваш прогресс сохраняется только в этом браузере.

Отправить на проверку (10 баллов)