Skip to content

Chapter 11: Web Application Security Fundamentals

Web applications are the dominant attack surface for external threats. This chapter surveys the most critical vulnerability classes, their underlying causes, and proven mitigations. All code examples reflect patterns observed in bug bounty programmes and penetration tests.

11.1 OWASP Top 10 (2021) Overview

Table 11.1. OWASP Top 10 2021
ID Category Representative CWEs
A01 Broken Access Control CWE-200, 201, 284
A02 Cryptographic Failures CWE-259, 327, 331
A03 Injection CWE-89, 77, 79
A04 Insecure Design CWE-209, 256, 501
A05 Security Misconfiguration CWE-16, 611
A06 Vulnerable Components CWE-1035, 937
A07 Auth & Session Failures CWE-287, 384
A08 Software & Data Integrity CWE-494, 829
A09 Security Logging Failures CWE-117, 778
A10 SSRF CWE-918

11.2 SQL Injection

SQL injection remains one of the most impactful vulnerability classes. When user-supplied input is concatenated into a SQL query, an attacker can alter the query’s logic, extract arbitrary data, or in some configurations execute OS commands. The root cause is a failure to separate data from code: the database parser can’t distinguish between the SQL the developer intended and the SQL the attacker smuggled in through the input.

A subtler variant called second-order injection trips up developers who correctly escape input on the way in but then re-use that stored data in a subsequent query without re-escaping. An attacker registers a username of admin’--, which is stored safely. Later, a password-reset routine reads the username from the database—trusting it as “already sanitised”—and drops it directly into a new query. The stored payload fires at that second use. This is why the fix must be parameterised queries everywhere, not just at the input boundary.

ORMs (Object-Relational Mappers like SQLAlchemy, Django ORM, or Hibernate) give a false sense of security if developers drop into raw SQL for complex queries. Calling session.execute(f"SELECT * FROM users WHERE name=’name’") inside Django is just as dangerous as doing it in raw Python—the ORM doesn’t magically sanitise strings you interpolate yourself. The safe path is always to use the ORM’s parameterised query helpers (filter(), raw() with bound parameters) rather than string formatting.

11.2.1 Detection and Manual Testing

A single quote ’ is the canonical probe. A syntax error response indicates potential injection. Boolean-based detection uses pairs such as:

  • ’ OR ’1’=’1 (always true)

  • ’ OR ’1’=’2 (always false)

If the two responses differ in content or size, SQL injection is likely.

11.2.2 Blind SQL Injection

When the application doesn’t return query results, attackers use time-based or boolean-based blind techniques:

-- If the first character of the database name is 'a', sleep 5 seconds
' AND IF(SUBSTRING(database(),1,1)='a', SLEEP(5), 0) -- -

-- Extract version character by character (boolean)
' AND (SELECT SUBSTRING(@@version,1,1))='5' -- -
# Basic detection and dump
sqlmap -u "https://target.example/item?id=1" --dbs

# Dump a specific table, tamper script for WAF evasion
sqlmap -u "https://target.example/item?id=1" \
       -D shopdb -T users --dump \
       --tamper=space2comment,between \
       --level=5 --risk=3

11.2.3 Prepared Statements in Python

import psycopg2

def get_user(username: str) -> dict | None:
    conn = psycopg2.connect(dsn="dbname=shop")
    cur  = conn.cursor()
    # NEVER do: cur.execute(f"SELECT * FROM users WHERE name='{username}'")
    cur.execute(
        "SELECT id, email, role FROM users WHERE username =
        (username,)          # <-- tuple prevents injection
    )
    row = cur.fetchone()
    cur.close()
    conn.close()
    return {"id": row[0], "email": row[1], "role": row[2]} if row else None

11.3 Cross-Site Scripting (XSS)

XSS lets an attacker execute JavaScript in a victim’s browser, leading to session hijacking, credential theft, or malware delivery. All three XSS variants share the same root cause—unescaped user-controlled data ends up being interpreted as code—but they differ sharply in how they’re delivered, who they affect, and how hard they are to detect.

11.3.1 Reflected XSS

The payload is embedded in a URL parameter and reflected immediately in the response. Example: https://example.com/search?q=<script>... Reflected XSS requires the victim to click a crafted link, so the attacker must combine it with phishing or URL shorteners to get delivery. The impact is limited to users who click that specific link, which makes it easier to contain but also harder to detect—the payload never touches the server’s database, so log-based detection often misses it. Real-world examples include the 2014 eBay XSS campaign where crafted auction listing URLs redirected buyers to phishing sites, and a 2011 Twitter worm that triggered XSS via malformed onmouseover attributes in tweets.

11.3.2 Stored XSS

The payload is persisted (in a database, log viewer, or similar store) and served to every visitor. This is the highest-impact category because it requires no victim interaction beyond a normal page visit. A single injected payload can silently compromise every user who views the affected page—account takeover at scale. The 2005 Samy worm on MySpace is the canonical example: a stored XSS payload added the attacker as a friend and reproduced itself to each visitor’s profile, infecting over a million accounts in 20 hours. Log viewers and admin dashboards are particularly dangerous targets because stored XSS there directly attacks privileged sessions.

11.3.3 DOM-based XSS

The payload never reaches the server; it’s written into the DOM via unsafe sinks (innerHTML, document.write, eval) reading from attacker-controlled sources (location.hash, postMessage). Because the server only ever sees a benign URL or POST body, server-side scanners and WAFs are blind to DOM XSS entirely. The entire exploit lives in JavaScript. Single-page applications built with Angular, React, or Vue are common targets because their heavy reliance on client-side routing and dynamic content creation multiplies the number of potential sinks. Bypassing DOM XSS requires auditing client-side JavaScript directly, not just HTTP responses.

// VULNERABLE: attacker controls location.hash
document.getElementById('out').innerHTML = location.hash.slice(1);

// FIXED: use textContent; never innerHTML for untrusted data
document.getElementById('out').textContent = location.hash.slice(1);

11.3.4 Content Security Policy

Content-Security-Policy:
  default-src 'none';
  script-src  'self' 'nonce-{RANDOM_PER_REQUEST}';
  style-src   'self';
  img-src     'self' data:;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri    'none';
  form-action 'self';

A nonce-based CSP invalidates all inline scripts that don’t carry the server-generated nonce, eliminating most XSS impact even when injection is present.

The nonce must be a fresh cryptographically random value (minimum 128 bits) generated per request—not per session or per deployment. If you reuse nonces, an attacker who can observe any prior response can replay the nonce value. Each script tag the server generates gets the matching nonce="..." attribute; any injected script the attacker inserts lacks it and the browser refuses to execute it.

Hashes are the alternative: instead of a nonce, you compute SHA-256( script_content), base64-encode it, and include ’sha256- <hash>’ in the CSP header. Hashes work for truly static inline scripts where the content doesn’t change per request. They don’t work well for scripts that embed per-request data (like a CSRF token embedded in JavaScript), which is why nonces are generally more practical for dynamic applications.

unsafe-inline completely defeats the inline-script protection that is the entire point of having a CSP. Adding it to script-src—often done as a quick fix when a script suddenly stops working—means an attacker’s injected <script> tag executes just as before. Any CSP containing unsafe-inline in script-src provides virtually no XSS protection; a scanner reporting “CSP present” on such a policy is giving a misleading green tick. Similarly, unsafe-eval must be absent; it re-enables eval(), setTimeout with a string argument, and new Function(), all common XSS escalation paths.

11.4 Cross-Site Request Forgery (CSRF)

CSRF forces an authenticated user’s browser to submit a state-changing request to a target site by exploiting the browser’s automatic inclusion of session cookies. The attacker doesn’t need to read the response—they just need the side effect of the request to happen (transferring funds, changing an email address, adding an admin account). That asymmetry is what makes CSRF powerful: the same-origin policy prevents the attacker from reading cross-origin responses, but it doesn’t prevent cross-origin form submissions or image requests from being sent.

11.4.1 Synchronizer Token Pattern

The server generates a cryptographically random token per session, embeds it in forms, and validates it on submission. Tokens must be bound to the session:

import secrets, hashlib

def generate_csrf_token(session_id: str) -> str:
    secret = app.config["SECRET_KEY"].encode()
    return hashlib.sha256(secret + session_id.encode()).hexdigest()

SameSite=Strict prevents cookies from being sent on any cross-site request. SameSite=Lax (the modern browser default) permits GET navigation but blocks cross-site POSTs—sufficient to defend most CSRF scenarios.

SameSite=None opts the cookie back in to cross-site delivery and must be paired with Secure or browsers reject it. Developers reach for it when they need cookies sent in embedded iframes or cross-origin API calls from a browser. Any endpoint that receives a SameSite=None session cookie remains fully exposed to CSRF, so those endpoints still need CSRF tokens or the double-submit pattern. OAuth callbacks and payment redirect flows are common cases where SameSite=None is genuinely required, and they’re also the flows that attackers target specifically because developers often forget to add CSRF protection back in once SameSite stops providing it. Don’t treat SameSite as a complete CSRF defence—treat it as a useful defence-in-depth layer that happens to be free.

An alternative for stateless APIs: the server sets a random cookie; JavaScript reads it and sends it in a custom header (e.g., X-CSRF-Token). The server checks that header and cookie match. A cross-site attacker can’t read the cookie (SOP prevents it), so can’t replicate the header value.

11.5 Server-Side Request Forgery (SSRF)

SSRF causes the server to make HTTP requests to attacker-specified URLs, providing access to internal services, cloud metadata endpoints, and RFC 1918 address space. The server is the unwitting proxy: it has privileged network access that the attacker lacks directly, and SSRF turns that access into a weapon. Features that commonly introduce SSRF include webhook configuration (“enter a URL we’ll POST events to”), URL-based image imports, PDF generators that fetch remote CSS or images, and any “preview this link” functionality.

Cloud Metadata Abuse via SSRF

AWS EC2 instance metadata is available at http://169.254.169.254/latest/ meta-data/. An SSRF against this endpoint can retrieve IAM role credentials:

GET http://169.254.169.254/latest/meta-data/
    iam/security-credentials/webapp-role

The response contains AccessKeyId, SecretAccessKey, and Token, giving the attacker full access to any AWS API the role permits. IMDSv2 (requiring a PUT request to obtain a session token first) mitigates this—but only if IMDSv1 is disabled.

SSRF bypass techniques: DNS rebinding, http://[::1]/, http://0.0.0.0/, decimal IP http://2130706433/ (=127.0.0.1), URL redirect chains, IPv6 scope IDs.

Defense: allowlist outbound hosts; resolve the hostname server-side and validate the resolved IP against a blocklist of private/link-local/loopback ranges before connecting; use a dedicated egress proxy.

11.6 XML External Entity Injection (XXE)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
  <!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<data><user>&xxe;</user></data>

Blind OOB XXE uses an external DTD hosted on an attacker server to exfiltrate file contents via DNS or HTTP:

<!DOCTYPE foo [
  <!ENTITY


]>

XXE vulnerabilities also appear inside SVG images, DOCX/XLSX containers (ZIP archives containing XML), and SAML assertions.

Mitigation: disable external entity processing in the XML parser. In Python lxml: use XMLParser(resolve_entities=False). In Java: set FEATURE_SECURE_PROCESSING and disable LOAD_EXTERNAL_DTD.

11.7 Path Traversal and Command Injection

# VULNERABLE
@app.route('/download')
def download():
    filename = request.args.get('file')
    return open(f'/var/app/files/{filename}', 'rb').read()

# Payload: /download?file=../../etc/shadow

# FIXED: resolve and validate against allowed base directory
import os, pathlib
BASE = pathlib.Path('/var/app/files').resolve()

@app.route('/download')
def download():
    filename = request.args.get('file', '')
    path = (BASE / filename).resolve()
    if not str(path).startswith(str(BASE)):
        abort(400)
    return open(path, 'rb').read()

Command injection occurs when user input is interpolated into shell commands. Always use subprocess with a list (no shell=True):

import subprocess
# NEVER: subprocess.run(f"ping {host}", shell=True)
result = subprocess.run(
    ["ping", "-c", "4", host],   # host is passed as argument, not shell-expanded
    capture_output=True, timeout=10
)

11.8 HTTP Security Headers

Table 11.2. Essential HTTP Security Response Headers
Header Recommended Value / Purpose
Strict-Transport-Security max-age=63072000; includeSubDomains; preload — forces HTTPS for 2 years
X-Frame-Options DENY — prevents clickjacking (legacy; prefer CSP frame-ancestors)
X-Content-Type-Options nosniff — prevents MIME-type confusion
Content-Security-Policy See §11.3.4 above; use nonce-based policy
Permissions-Policy camera=(), microphone=(), geolocation=() — restricts APIs
Referrer-Policy strict-origin-when-cross-origin — limits referrer leakage
Cross-Origin-Opener-Policy same-origin — isolates browsing context for Spectre
Cross-Origin-Resource-Policy same-origin — prevents cross-origin reads

11.9 Exercises

Exercise 11.1

The following Python Flask route is used for a product search feature. Identify every security vulnerability, explain the impact of each, and rewrite the route securely.

@app.route('/search')
def search():
    q = request.args.get('q')
    sql = "SELECT name,price FROM products WHERE name LIKE '
    results = db.execute(sql).fetchall()
    return f"<html><body>Results for {q}: {results}</body></html>"

Exercise 11.2

A web application accepts SVG image uploads and renders them in an <img> tag. Construct a proof-of-concept payload that would exfiltrate the contents of /etc/hostname to an out-of-band HTTP server, and describe two mitigations the developer should implement.

Exercise 11.3

Explain why SameSite=Lax alone is insufficient CSRF protection for an application that uses GET requests to perform state-changing actions (e.g., /admin/delete?id=5). What additional controls are required?

Exercise 11.4

You find a URL parameter redirect=https:// example.com/ dashboard that the server fetches before returning a 302. Describe a methodology for testing whether this is an SSRF vulnerability, including five payloads you would try and the evidence that would confirm the finding.

Exercise 11.5

A web security scanner reports a missing Content-Security-Policy header. The developer responds that they use output encoding everywhere and there is no XSS risk, so CSP is unnecessary. Write a 200-word technical response either supporting or refuting this claim, citing specific attack scenarios that CSP would or would not prevent.