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:
dangerouslySetInnerHTML,v-html,innerHTML,document.write,eval.- Putting user data in
href/srcwithout checking the scheme (javascript:URLs). - Server-side templates with escaping switched off (
|safe).
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:
SameSite=LaxorStricton the session cookie, which stops cookies on most cross-site requests (the default in current browsers, but set it explicitly).- 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.
- Check the
OriginorRefererheader on state-changing requests, and require a custom header (such asX-Requested-Withor a JSON content type) on APIs, because cross-site forms cannot set it without a CORS pre-flight. - 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.
- IDOR:
GET /invoices/1042returns any invoice because only the login was checked. Fix: authorise on every object access (WHERE id = ? AND owner_id = current_user), not only on the page that links to it. Random ids make guessing harder; they do not replace a check. - Function-level: the admin button is hidden, but
POST /admin/usersworks for anybody. Fix: enforce roles in the server, on each route. - Mass assignment: binding the request body straight to a model lets a user send
"isAdmin": true. Fix: bind to explicit input types with only the permitted fields. - Deny by default: new endpoints should require authorization unless marked public, and the checks should live in one place (middleware, policies) so no route forgets them.
Test it by logging in as user A and replaying user B's requests.
Layers that help against all of them
- Security headers:
Content-Security-Policy,Strict-Transport-Security,X-Content-Type-Options: nosniff,Referrer-Policy, andframe-ancestors(orX-Frame-Options) against clickjacking. - Dependencies: keep libraries updated and watch advisories (
npm audit,pip-audit, Dependabot). - Secrets out of source control and logs; rotate on exposure.
- Logging and alerting for failed logins, authorisation failures and unusual volumes, without writing secrets or personal data into the logs.
- A WAF can buy time, but it does not fix the code.
Review checklist
- Does every database call use parameters?
- Is every dynamic value encoded for its output context, and is there any raw HTML sink?
- Are state-changing requests protected by SameSite plus a token or origin check?
- Can any feature make the server fetch a user-supplied URL?
- Is each object access authorised on the server, and is each route denied by default?
- Are cookies
HttpOnly,SecureandSameSite, and is a CSP in place?
Sources
- OWASP Top 10.
- OWASP Cheat Sheet Series: SQL Injection Prevention, XSS Prevention, CSRF Prevention, SSRF Prevention, Authorization.
- MDN: Content Security Policy.
- MDN: SameSite cookies.
Practise this topic: Security