Web Application Security
Web applications are the most exposed surface most organizations own: they accept attacker-controlled input by design, run on infrastructure you share with other tenants, and are reachable from anywhere on earth. The encouraging news is that the dominant classes of web attack are old, well documented, and almost entirely preventable with patterns that frameworks already provide. This lesson walks the failure modes you will meet first â injection, cross-site scripting, broken access control and request forgery â and shows the vulnerable and fixed versions of each so the contrast is unmistakable.
Reading the OWASP Top 10 as a set of lessons
The OWASP Top 10 is a consensus survey of the risks seen in real applications, refreshed roughly every four years. The 2021 edition grouped decades of individual bugs into broader categories: broken access control, cryptographic failures, injection, insecure design, security misconfiguration, vulnerable and outdated components, identification and authentication failures, software and data integrity failures, security logging and monitoring failures, and server-side request forgery.
| OWASP 2021 category | Typical root cause | First control to add |
|---|---|---|
| Broken access control | Checks enforced only in the UI | Server-side authorization on every request |
| Cryptographic failures | Plaintext storage, weak algorithms | Modern authenticated encryption, key management |
| Injection | String-built queries and commands | Parameterization and typed APIs |
| Insecure design | Missing control at the architecture stage | Threat modeling before building |
| Security misconfiguration | Default credentials, open buckets | Hardened baselines and config scanning |
| Vulnerable components | Unpatched libraries | Software composition analysis in CI |
| Authentication failures | Credential stuffing, weak MFA | Phishing-resistant MFA, rate limiting |
| Integrity failures | Unsigned updates, untrusted CI | Signed artifacts, protected pipelines |
| Logging failures | Logs nobody reads, no alerting | Centralized monitoring with ownership |
| SSRF | Unvalidated URLs server-side allowlists | Egress controls and metadata blocking |
The pattern across the list: vulnerabilities are rarely exotic. They come from trusting input, trusting the client, or shipping a default configuration that somebody never changed.
Injection: when data becomes code
Injection happens whenever the application blurs the line between the data a user supplies and the instructions the interpreter runs. In SQL, the classic version concatenates a username into a query, so a crafted value closes the quote and appends a statement of the attacker's choosing. The same confusion appears in OS command shells, LDAP filters, template engines and NoSQL queries.
import sqlite3
conn = sqlite3.connect("app.db")
cur = conn.cursor()
# VULNERABLE: the string is parsed as SQL, so quotes in input change its meaning
username = "admin' OR '1'='1' --"
try:
cur.execute(f"SELECT * FROM users WHERE username = '{username}'")
print("attacker returned:", cur.fetchall()) # every row, not one
except sqlite3.Error as err:
print("error:", err)
# SAFE: the driver sends the SQL template and the value separately;
# the value can never be re-parsed as syntax
cur.execute("SELECT * FROM users WHERE username = ?", (username,))
print("parameterized returned:", cur.fetchall()) # no match for the crafted string
# SAFE: identifiers cannot be parameterized, so validate them against a list
table = "users"
assert table in {"users", "orders", "sessions"}
cur.execute(f"SELECT count(*) FROM {table}")
Two rules follow. Values are bound, never interpolated â parameters, prepared statements, or an ORM query builder with value binding. Identifiers such as table and column names cannot be parameterized, so they must come from a fixed allowlist; that distinction is where most "we use an ORM but still got injected" reports come from. Escaping and filtering are a second line of defense at best: blacklists miss encodings, and no filter understands every context the value will be placed in.
Cross-site scripting: the same bug on the client
Cross-site scripting is injection into the page itself. Reflected XSS puts attacker input straight into a response, typically through a search parameter or an error message. Stored XSS saves it â a comment, a ticket description, a profile field â and serves it to everyone who views the record, which is why stored XSS routinely outranks reflected variants in blast radius. DOM-based XSS never touches the server: client-side JavaScript reads a value such as location.hash and writes it into the DOM with an unsafe sink like innerHTML.
The reliable defense is context-aware output encoding â escaping the characters that are meaningful in the context where the value lands, at the moment it lands there. Escaping for HTML text differs from escaping for an attribute, which differs from escaping for a URL or for a JavaScript string. Frameworks do this automatically when you use their templating: React's JSX escapes text by default; a raw innerHTML assignment or the dangerouslySetInnerHTML prop opts out of that protection.
// A DOM XSS sink: hash value flows straight into the markup
function renderLegacyComment(raw) {
const box = document.getElementById("comment");
box.innerHTML = raw; // unsafe sink
}
// Safe by construction: text nodes only, no parser involvement
function renderComment(raw) {
const box = document.getElementById("comment");
box.replaceChildren(document.createTextNode(raw));
}
// When HTML is genuinely required, sanitize with a vetted allowlist library
import DOMPurify from "dompurify";
document.getElementById("comment").innerHTML =
DOMPurify.sanitize(raw, { ALLOWED_TAGS: ["b", "i", "em", "a"], ALLOWED_ATTR: ["href"] });
// Belt and braces: a policy that makes injected script fail to execute anyway
// Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'
A strict Content-Security-Policy is worth the header alone: with script-src limited to your own origins and no unsafe-inline, most injected payloads stop running even if a sink slips through. Combine it with X-Content-Type-Options: nosniff to stop MIME sniffing, frame-ancestors 'none' to block clickjacking, and HttpOnly cookies so script cannot read session tokens.
Broken access control: the quiet one
Injection is loud; broken access control is quiet and pervasive. The bug is nearly always the same shape: the UI hides a button, but the server trusts that hiding was enforcement. A user changes id=1042 to id=1043 in a URL and reads another customer's invoice. A moderator-only endpoint accepts any authenticated token. A bulk export forgets the row-level filter that the list view applies.
Fix it with server-side authorization close to the data: a middleware or query scope that derives the allowed set from the session, plus object-level checks on every read and write of a specific record. Test it the way an attacker would â replay each request with another user's identifier and confirm a 403 or an empty result. Deny by default: a route with no explicit policy should fail closed, not open.
CSRF: making the browser do the work
Cross-site request forgery exploits the fact that browsers attach cookies to every request to a domain, including one initiated by a third-party page. If your session lives in a cookie with no additional protection, a hidden form on an attacker's site can submit a state-changing request to yours and it will look authenticated.
import secrets
from flask import Flask, session, request, abort
app = Flask(__name__)
@app.before_request
def require_csrf():
if request.method in {"POST", "PUT", "PATCH", "DELETE"}:
sent = request.form.get("csrf_token") or request.headers.get("X-CSRF-Token")
if not sent or not secrets.compare_digest(sent, session.get("csrf_token", "")):
abort(403, "CSRF token missing or invalid")
@app.route("/transfer", methods=["POST"])
def transfer():
session["csrf_token"] = session.get("csrf_token") or secrets.token_urlsafe(32)
# ... perform the transfer using session-bound identity ...
return {"status": "ok"}
Modern alternatives to the synchronizer token: the SameSite cookie attribute (set sessions to Lax or Strict), which stops the browser from attaching cookies to cross-site form posts at all, and checking the Origin or Sec-Fetch-Site header server-side. Use SameSite plus a token; either one alone has had bypasses published.
Design notes that prevent the next class
Not every vulnerability is a missing escape. Insecure design means the feature never had a control to omit â password reset flows that leak account existence, unlimited retry on login, an export that returns every row the schema knows about. Mitigations belong in the design: rate limits, step-up authentication for sensitive actions, pagination with explicit scopes, and rejecting dangerous functionality outright rather than defending it.
Server-side request forgery closes the list: a URL field the server fetches becomes a proxy into your internal network and cloud metadata services. Block it with egress allowlists, resolve and check addresses before connecting, and deny link-local metadata ranges by default.
Common Mistakes
Validating input with a blacklist of dangerous words
Fix: Bind values as parameters and encode on output for the exact context; validation is for business rules, not for security.
Escaping once in the controller before rendering
Fix: Encode at the point of output, because a value can pass through several templates and each context needs its own escaping.
Enforcing authorization only in the frontend
Fix: Check every request on the server against the session's permissions, including object-level ownership of each record.
Relying on a WAF as your primary defense
Fix: Treat a WAF as temporary shielding while you fix the underlying code; rules are bypassed, parameters are not.
Disabling CSP because it broke a script
Fix: Fix the inline script or move it to a nonce; an origin allowlist is one of the cheapest defenses you can deploy.
Best Practices
- Use your framework's parameterized queries and templating defaults; opt out of safety deliberately, never by accident.
- Ship security headers â CSP, HSTS, nosniff, frame-ancestors â as code in your reverse proxy configuration.
- Run dependency scanning and secret scanning in CI so vulnerable components fail the build, not the postmortem.
- Write authorization tests alongside feature tests: for every route, assert the deny case for an unrelated user.
- Log authentication, authorization failures and data exports, and alert on the patterns that matter.
Key Takeaways
- Injection, XSS and CSRF are the same mistake in three places: data crossing into code â SQL, the DOM, or a forged request.
- Parameterization and context-aware output encoding are the durable fixes; input blacklists are not.
- Broken access control is the most common serious web flaw because the UI hides controls the server never re-checks.
- Content-Security-Policy, SameSite cookies and modern security headers turn residual bugs into non-events.
- Threat modeling early catches insecure design, which no amount of later escaping can repair.