DML School of Technology
Menu

Open to everyone Reading, lesson 55 of 100, 2 min read

Cross-site scripting and request forgery

Cross-site scripting (XSS)

XSS happens when a website includes untrusted input in a page without making it safe, so a visitor's browser runs it as JavaScript. Imagine a comment box: if someone posts text containing a script and the site shows it to every visitor as-is, the script runs in all their browsers, with access to the page as they see it.

Kinds:

  • Stored: the script is saved (in a comment, a profile) and served to everyone who views it.
  • Reflected: the script is in a link; it runs when a victim opens the crafted link.
  • DOM-based: the page's own JavaScript writes untrusted data into the page unsafely.

Defences against XSS

  1. Output encoding: when putting text into HTML, convert special characters (<, >, ", ', &) into harmless forms. Modern templating systems do this by default; the danger comes from switching it off.
  2. Content Security Policy (CSP): a response header that tells the browser which scripts may run. A strict CSP that forbids inline scripts stops most XSS even when a mistake slips through. This platform uses one.
  3. HttpOnly cookies, so a script cannot read the session cookie.
  4. Sanitise rich text with a well-tested library when users may enter formatting.

Cross-site request forgery (CSRF)

CSRF tricks a signed-in user's browser into sending a request they did not intend. A malicious page could contain a hidden form that posts to school.example/account/email to change the victim's email address. The browser attaches the victim's cookie automatically.

Defences:

  • CSRF tokens: each form includes a secret value tied to the session; the server rejects requests without it.
  • SameSite cookies, which browsers do not send on most cross-site requests.
  • Requiring re-entry of the password for sensitive changes.

Clickjacking

A site loads yours in an invisible frame and tricks users into clicking buttons. Prevent it with the frame-ancestors CSP rule or the X-Frame-Options header.

Note

Notice the pattern: the browser is powerful and trusting, so servers must tell it exactly what is allowed.