Careers Post-AI
Security: all chapters

SecurityPart 2: Application security

Chapter 5Web vulnerabilities

30 min read, 1 lab, Intermediate

In 2019 an attacker made one of Capital One's cloud servers fetch a URL it should never have fetched: the cloud metadata service, which handed back temporary credentials. Roughly 100 million customer records followed. This chapter takes the web bugs behind incidents like that one, shows the single mistake underneath each, and shows you the fix in code.

After this chapter you can

  • Explain the same-origin policy, cookie scoping and CORS, and what each one does and does not protect
  • Identify the root cause of SQL injection, command injection, XSS, CSRF, SSRF, path traversal, insecure deserialization and IDOR
  • Fix each one at the root instead of filtering symptoms
  • Map findings to the OWASP Top 10:2025 categories
  • Exploit and explain three classic bugs in OWASP Juice Shop using an intercepting proxy

The browser security model

A web page runs code from strangers. The browser keeps that code apart using the same-origin policy (SOP): a script may only read responses from its own origin, where an origin is the triple of scheme, host and port. https://shop.example and https://api.shop.example are different origins, and so are http:// and https:// versions of the same host.

The catch is that SOP restricts reading, not sending. A page on evil.example can still make your browser submit a form or load an image from bank.example, and the browser attaches the cookies it holds for bank.example. Half of this chapter's bugs live in that gap.

MechanismWhat it controlsWhat it does not do
Same-origin policyWhich origin's scripts can read a response or touch a DOMStop cross-site requests from being sent
CookiesWhich requests carry a credential, scoped by domain and pathRespect origins exactly: cookies ignore port and, by default, scheme
SameSite cookie attributeWhether cookies ride along on cross-site requestsHelp against same-site attackers such as a compromised subdomain
CORSLets a server relax SOP for chosen originsAdd any protection: it only opens doors

CORS (cross-origin resource sharing) confuses people because it sounds like a defence. A server sends Access-Control-Allow-Origin to tell the browser which other origins may read its responses. Misconfigured CORS, such as reflecting whatever Origin header arrives while also sending Access-Control-Allow-Credentials: true, lets any site read authenticated data.

Injection: data that becomes code

Every injection bug has the same shape. The program builds a string in some language (SQL, a shell command, HTML, an LDAP filter), splices untrusted input into it, and hands it to an interpreter. If the input contains that language's syntax, the attacker gets to write part of your program.

The fix is never "strip the dangerous characters". The fix is to keep code and data in separate channels so the interpreter never parses data as syntax. For SQL that channel is the parameterized query.

Vulnerable

login.py
q = ("SELECT * FROM users WHERE email = '"
     + email + "' AND pw_hash = '" + h + "'")
row = db.execute(q).fetchone()

Fixed

login.py
q = ("SELECT * FROM users "
     "WHERE email = ? AND pw_hash = ?")
row = db.execute(q, (email, h)).fetchone()

Send ' OR 1=1-- as the email to the vulnerable version and the query becomes WHERE email = '' OR 1=1--' AND .... The -- comments out the password check, and the first row (often the admin) comes back. In the fixed version the driver sends the query text and the values separately, so the same input is just an odd email address that matches nobody.

Parameters cover values, not identifiers. If users choose a sort column, map their choice through an allowlist such as {"price": "price", "name": "name"} rather than splicing it in.

Command injection

The same bug against a shell. A "ping this host" feature that runs os.system("ping -c 1 " + host) will happily run 8.8.8.8; cat /etc/passwd as two commands.

ping.py
# Vulnerable: the shell parses ; | $() and backticks
os.system("ping -c 1 " + host)
 
# Fixed: no shell, arguments passed as a list, input validated
if not re.fullmatch(r"[A-Za-z0-9.\-]{1,253}", host):
    abort(400)
subprocess.run(["ping", "-c", "1", "--", host], check=True, timeout=5)

Passing an argument list means no shell ever sees the string. The -- stops a value like -f from being read as an option, a variant called argument injection.

Cross-site scripting

XSS is injection into HTML or JavaScript. The attacker's script runs in your origin, so SOP now works for the attacker: the script can read the page, call your APIs with the victim's cookies and change what the victim sees.

TypeWhere the payload livesTypical example
ReflectedIn the request, echoed into the responseA search page that prints You searched for: ... unescaped
StoredIn your database, served to every viewerA product review containing a script tag
DOM-basedNever reaches the server's HTML; client JavaScript writes it into the pageel.innerHTML = location.hash.slice(1)

The root cause is missing contextual output encoding. The same character means different things in HTML body text, an attribute, a URL and a JavaScript string, so the encoding must match the context the data lands in.

Vulnerable

search.js
results.innerHTML =
  "You searched for: " + query;

Fixed

search.js
results.textContent =
  "You searched for: " + query;

On the server, modern template engines (Jinja2, React's JSX, Go's html/template) encode by default. XSS comes back when someone opts out: dangerouslySetInnerHTML, Jinja's |safe, v-html. Grep for those first in any review. If you must render user HTML, sanitize it with a maintained library such as DOMPurify.

Add a Content Security Policy as a second layer. A strict CSP such as script-src 'nonce-r4nd0m' 'strict-dynamic'; object-src 'none'; base-uri 'none' blocks inline scripts that lack the per-response nonce, which turns most XSS bugs into harmless text.

Cross-site request forgery

CSRF abuses the "sending is allowed" gap. A page on evil.example contains an auto-submitting form that posts to bank.example/transfer. The browser attaches the victim's bank cookie, and the bank sees a valid, authenticated request it cannot tell apart from a real one.

evil.example/index.html
<form action="https://bank.example/transfer" method="POST" id="f">
  <input name="to" value="attacker">
  <input name="amount" value="5000">
</form>
<script>document.getElementById("f").submit()</script>

The root cause is that the server authenticates the browser (by ambient cookie) but never checks the intent (that the request came from its own page). Defences, strongest combination first:

  • SameSite=Lax or Strict session cookies. Browsers then omit the cookie on cross-site POSTs. Chromium treats cookies with no SameSite attribute as Lax, but set it explicitly.
  • Anti-CSRF tokens. A random value tied to the session, embedded in each form and checked on every state-changing request. Frameworks such as Django and Rails do this for you; do not disable it.
  • Check Origin or Sec-Fetch-Site headers on state-changing requests and reject cross-site ones.
  • Never change state on GET. A GET can be triggered by an image tag.

APIs that authenticate with an Authorization: Bearer header instead of cookies are not exposed to classic CSRF, because the browser never attaches that header on its own.

Server-side request forgery

SSRF turns your server into the attacker's proxy. Any feature that fetches a user-supplied URL (link previews, webhooks, "import from URL", PDF renderers) can be pointed at addresses only the server can reach: internal admin panels, databases, and the cloud metadata service at 169.254.169.254.

This is the Capital One chain from the opening. Blocklisting 169.254.169.254 fails, because attackers use redirects, decimal IPs like 2852039166, IPv6 forms, or DNS names that resolve to internal addresses after you check them (DNS rebinding).

Robust defences work at several layers:

  • Allowlist destinations when the feature allows it (only hooks.slack.com, say).
  • Resolve, then validate, then connect to the resolved IP, rejecting private, loopback, link-local and metadata ranges, and re-check on every redirect or disable redirects.
  • Use the cloud's hardened metadata service. AWS IMDSv2 requires a session token obtained with a PUT request, which simple SSRF cannot send.
  • Egress-filter the network so the fetcher service cannot reach internal ranges at all.

Files, objects and identifiers

Three more bugs share a theme: the application trusts an input to name something, and never checks whether the caller should get that thing.

Path traversal

download.py
# Vulnerable: name=../../etc/passwd walks out of the directory
return open("/srv/uploads/" + name, "rb").read()
 
# Fixed: resolve the real path and confirm it stays inside the base
base = Path("/srv/uploads").resolve()
target = (base / name).resolve()
if not target.is_relative_to(base):
    abort(404)
return target.read_bytes()

Checking for the literal ../ is the classic broken fix: attackers send URL-encoded, double-encoded or absolute paths. Resolve first, compare second. Better still, store files under random IDs and look the ID up in a database table.

Insecure deserialization

Formats like Python pickle, Java native serialization, PHP unserialize and some YAML loaders can instantiate arbitrary classes while parsing. If an attacker controls the bytes, parsing is code execution: a pickle can tell the loader to call os.system during load.

session.py
# Vulnerable: cookie bytes are attacker-controlled
user = pickle.loads(base64.b64decode(request.cookies["session"]))
 
# Fixed: a data-only format, plus a signature so it cannot be forged
user = json.loads(signer.unsign(request.cookies["session"]))

The fix is to deserialize untrusted input only with data-only formats (JSON, Protocol Buffers) or yaml.safe_load, and to sign anything you hand to a client and later read back.

IDOR

An insecure direct object reference is GET /api/invoices/1042 returning invoice 1042 to anyone logged in. Change the number, get someone else's invoice. Random UUIDs make guessing harder but do not fix it; the fix is an ownership check on every access.

invoices.py
inv = Invoice.query.filter_by(id=invoice_id, owner_id=current_user.id).first_or_404()

IDOR is the most common bug class in bug bounty reports because scanners cannot find it: only a human (or a test) knows that user A must not see user B's invoice. The next chapter, Authentication and authorization, goes deeper into access control design.

Mapping to the OWASP Top 10:2025

The OWASP Top 10 is a ranked list of risk categories, built from contributed testing data plus a community survey. The 2025 edition merged SSRF into Broken Access Control and added two new categories (A03 and A10). Use it as a shared vocabulary in reports, not as a checklist of everything that can go wrong.

2025 categoryBugs from this chapter
A01 Broken Access ControlIDOR, path traversal, CSRF, SSRF, permissive CORS
A02 Security MisconfigurationMissing security headers, verbose errors, default credentials
A03 Software Supply Chain FailuresCovered in Software supply chain security
A04 Cryptographic FailuresCovered in Applied cryptography
A05 InjectionSQL injection, command injection, XSS
A06 Insecure DesignFeatures with no abuse case considered, such as unlimited fetch-any-URL
A07 Authentication FailuresCovered in Authentication and authorization
A08 Software or Data Integrity FailuresInsecure deserialization, unsigned client-side state
A09 Security Logging and Alerting FailuresAttacks that go unnoticed (see Logging and telemetry)
A10 Mishandling of Exceptional ConditionsErrors that fail open or leak internals

Key terms

Origin
The combination of scheme, host and port that the browser uses as its security boundary.
Same-origin policy
The browser rule that a script may read only responses and DOM content from its own origin.
CORS
A set of response headers that lets a server permit specific other origins to read its responses.
Parameterized query
A database call where the query text and the values travel separately, so values are never parsed as SQL.
Contextual output encoding
Escaping data according to where it lands (HTML body, attribute, URL, script) so it is displayed rather than executed.
SameSite
A cookie attribute that controls whether the browser sends the cookie on requests initiated by other sites.
SSRF
Server-side request forgery: making a server send requests to destinations the attacker chooses.
IDOR
Insecure direct object reference: accessing an object by its identifier without an ownership or permission check.
Deserialization
Turning bytes back into in-memory objects; dangerous when the format can instantiate arbitrary types.
Lab

Break OWASP Juice Shop through an intercepting proxy

Intermediate, 75 min

Goal: run a deliberately vulnerable shop locally, exploit SQL injection, DOM XSS and an IDOR through a proxy, and write up the root cause and fix for each.

You need: Docker, and either Burp Suite Community Edition (free download from PortSwigger) or ZAP (free from zaproxy.org). Only attack this local container. Juice Shop is built to be attacked; your employer's or anyone else's site is not.

  1. Start Juice Shop bound to your own machine only:

    docker run --rm -p 127.0.0.1:3000:3000 bkimminich/juice-shop

    Wait for a log line saying the server is listening on port 3000, then open http://localhost:3000.

  2. Set up the proxy. In Burp, go to Proxy, Intercept, Open browser; this Chromium is already wired through Burp. In ZAP, use Manual Explore with your browser of choice. Browse the shop and confirm requests appear in Proxy, HTTP history (Burp) or the History tab (ZAP).

  3. Find the score board. Juice Shop hides it, but its route is in the front-end JavaScript. Search the main JS file in the proxy history for score, or simply try http://localhost:3000/#/score-board. Finding it solves your first challenge.

  4. SQL injection. Open the login page and enter this as the email, with any password:

    ' OR 1=1--

    You should be logged in as the first user in the table, the administrator. Find the login POST in proxy history and look at the JSON body and the error responses when you send just a single quote. The error response leaks database details, a strong hint that the query is built by string concatenation.

  5. DOM XSS. In the search box, enter:

    <iframe src="javascript:alert(`xss`)">

    An alert box appears. Look at the URL: the payload sits in the q parameter after the #. The Angular front end writes the search term into the page with its built-in sanitizer explicitly bypassed, the client-side twin of Jinja's |safe.

  6. IDOR. Log in as a normal user you register yourself. Add an item to your basket, then find the request GET /rest/basket/N in proxy history. Send it to Repeater (Burp) or Open/Resend (ZAP), change N to a different number and send it. You now see another user's basket, and the score board marks the challenge solved.

  7. For each bug, write three lines in a juice-shop-notes.md: root cause, OWASP 2025 category, and the code-level fix you would make.

Check your work: the score board at /#/score-board shows at least four solved challenges (score board, admin login, DOM XSS, view basket), and your notes name a root-cause fix for each rather than a filter.

Stretch: use the proxy to find the API request behind the product search and try an injection there instead of in the login form. Then run ZAP's active scan against http://localhost:3000 and compare what it found automatically with what you found by hand; note which bug classes the scanner missed and why.

Check yourself

A page on another site submits a hidden form to your app, and the user's session cookie is attached. Which statement is true?

A developer fixes SQL injection by removing single quotes from input. Why is this weaker than a parameterized query?

An app fetches a user-supplied URL for link previews and blocks the literal string 169.254.169.254. What is the most robust fix?

Every invoice URL now uses a random UUID instead of a sequential number. Is the IDOR fixed?

Your React app is free of string-built HTML, but a code search finds dangerouslySetInnerHTML rendering a user bio. What should you do first?

Recap

  • The same-origin policy stops cross-origin reading, not sending, and CORS only ever relaxes it.
  • Injection of every kind (SQL, shell, HTML) is data being parsed as code; fix it by separating the channels.
  • XSS is fixed by contextual output encoding and safe DOM APIs, with a strict CSP as a second layer.
  • CSRF is fixed with SameSite cookies, anti-CSRF tokens and origin checks on state-changing requests.
  • SSRF, path traversal and IDOR all trust an input to name a resource; validate the resolved target and check permission every time.
  • The OWASP Top 10:2025 is shared vocabulary for findings, with Broken Access Control still first.

Go deeper