CS Fundamentals Trainer · Guides

Web application attacks and their defences: injection, XSS, CSRF, SSRF and broken access control

How the five most common web vulnerability classes work, with the one defence for each that actually fixes the cause (parameterized queries, contextual output encoding, SameSite and tokens, outbound allowlists, server-side authorization checks), plus the defence-in-depth layers (CSP, headers, least privilege) and a short review checklist.

5 min read

Most web vulnerabilities share one cause: data is treated as instructions, or a check that the server must make is left to the client. The attacks have different names because they happen in different interpreters (a database, a browser, an HTTP client), but the fix is the same idea each time: keep data and code separate, and enforce rules on the server.

1. Injection (SQL, command, template, LDAP…)

User input becomes part of a command that an interpreter then parses.

# vulnerable: the input is parsed as SQL
cur.execute(f"SELECT * FROM users WHERE name = '{name}'")
# name = "x' OR '1'='1"  returns every user; with more effort it reads or changes anything

# fixed: the value travels separately from the statement
cur.execute("SELECT * FROM users WHERE name = %s", (name,))

The fix is parameterized queries (prepared statements, or an ORM's bound parameters). Escaping by hand is fragile, and filtering "bad characters" fails. Table and column names cannot be parameters: choose them from a fixed allowlist. The same principle covers the others: pass arguments to a process as an array and never through a shell string (subprocess.run([...]), not shell=True with user text), avoid building templates from input, and use safe XML parsers (disable external entities). Add least privilege: the application's database account should not own the schema or be able to read other applications' data, which limits the damage when a bug slips through.

2. Cross-site scripting (XSS)

An attacker gets their script to run in another user's browser, on your site. It can read the page, call your API as the user and, if it can see them, steal tokens. Three kinds: stored (saved in your database and shown to others), reflected (echoed from the URL) and DOM-based (client-side code writes input into the page).

The fix is contextual output encoding: encode data for where it lands (HTML body, attribute, JavaScript string, URL, CSS), which modern frameworks do by default (React, Angular, Vue and template engines escape by default). XSS then appears where you step around the framework:

If you must render user HTML (a rich-text field), sanitise it with a maintained library (DOMPurify) with an allowlist. Defence in depth: a strict Content-Security-Policy (no inline script, scripts only from known sources, a nonce or hash for the ones you need), HttpOnly session cookies, and Trusted Types in browsers that support them.

3. Cross-site request forgery (CSRF)

A malicious page makes the victim's browser send a request to your site, and the browser attaches the victim's cookies. If your endpoint changes state on a plain POST (or a GET!), the attacker can make it happen.

Defences, in order of preference:

  1. SameSite=Lax or Strict on the session cookie, which stops cookies on most cross-site requests (the default in current browsers, but set it explicitly).
  2. Anti-CSRF tokens: a random, per-session value in a form field or header that a cross-site page cannot read; the server rejects requests without it.
  3. Check the Origin or Referer header on state-changing requests, and require a custom header (such as X-Requested-With or a JSON content type) on APIs, because cross-site forms cannot set it without a CORS pre-flight.
  4. Never change state with GET.

APIs authenticated by an Authorization header (not cookies) are not CSRF-prone, since the browser does not add the header by itself.

4. Server-side request forgery (SSRF)

The application fetches a URL that the user supplies (webhook, avatar import, link preview). The attacker points it at something only the server can reach: an internal admin service, localhost, or a cloud metadata endpoint (169.254.169.254) that returns credentials.

Defences: allowlist destinations where you can; otherwise resolve the host and reject private, loopback and link-local addresses, check again after redirects (or do not follow them), connect to the address you checked (to defeat DNS rebinding), restrict schemes to https, apply timeouts and size limits, and put the fetcher in a network segment that cannot reach internal services. On cloud platforms, use the metadata service's token-based version (IMDSv2) and give the workload minimal roles.

5. Broken access control

The server serves data without checking that this user may have this object, or lets a normal user reach an admin function. It is the top item in the OWASP Top 10, and no scanner finds it reliably because the application's rules are the only specification.

Test it by logging in as user A and replaying user B's requests.

Layers that help against all of them

Review checklist

  1. Does every database call use parameters?
  2. Is every dynamic value encoded for its output context, and is there any raw HTML sink?
  3. Are state-changing requests protected by SameSite plus a token or origin check?
  4. Can any feature make the server fetch a user-supplied URL?
  5. Is each object access authorised on the server, and is each route denied by default?
  6. Are cookies HttpOnly, Secure and SameSite, and is a CSP in place?

Sources

Practise this topic: Security

More guides