TExcelTAD
Home › Web Application Security: OWASP Top 10, APIs & Authentication › Web Application Security Exercises

Web Application Security Exercises

These exercises cover the whole course. Each one names the lesson it practises; try it before opening the answer. Several give you code to run and change: they build their toy targets themselves, so they are safe to run here. The usual rule applies to everything you learn from them: test only applications you own or are authorised to test (Authorization, Scope and Rules of Engagement).

Exercise 1: origins and sites

For the page https://app.shop.lab.test/cart, classify each URL as same-origin, same-site but cross-origin, or cross-site: (a) https://app.shop.lab.test:443/pay, (b) http://app.shop.lab.test/cart, (c) https://api.shop.lab.test/v1, (d) https://shop-lab.test/. Lesson: trust model.

Answer

(a) same-origin (443 is the default port); (b) cross-origin, and cross-site under the "schemeful" same-site rule browsers use today, because the scheme differs; (c) same-site, cross-origin (registrable domain lab.test, other host); (d) cross-site (another registrable domain).

Exercise 2: read the cookies

A login response contains:

text
Set-Cookie: session=31; Domain=shop.lab.test; Path=/
Set-Cookie: csrf=9c2e7a; Path=/; SameSite=Strict

List every weakness and write the hardened headers. Lessons: cookies, sessions.

Answer

session: guessable value, Domain widens it to all subdomains, no Secure, HttpOnly or SameSite. csrf: no Secure. Hardened: Set-Cookie: __Host-session=<128-bit random>; Path=/; Secure; HttpOnly; SameSite=Lax and Set-Cookie: __Host-csrf=<random>; Path=/; Secure; SameSite=Strict (readable by script on purpose if the front end sends it in a header). Also rotate the session id at login.

Exercise 3: CORS review

An API answers every request with Access-Control-Allow-Origin: <the request's Origin> and Access-Control-Allow-Credentials: true. Explain the impact in two sentences and write the fix. Lesson: CORS.

Answer

Any website a logged-in user visits can read that user's API responses with fetch(…, {credentials: "include"}), so personal data and tokens leak to every origin. Fix: compare Origin with an exact allow-list of full origins, send ACAO and credentials only for those, never allow null, and add Vary: Origin.

Exercise 4: fix the verifier

This JWT check accepts forged tokens. Find three bugs, then fix them in the code and run it until the forged token is rejected. Lessons: JWT, JWT pitfalls.

python · try it yourself
import base64, hashlib, hmac, json

def b64(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def unb64(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
KEY = b"lab-only-key-0123456789abcdef0123"

def verify(token, now=1_790_000_000):
    h, p, s = token.split(".")
    header = json.loads(unb64(h))
    if header["alg"] == "none":
        return json.loads(unb64(p))
    good = hmac.new(KEY, f"{h}.{p}".encode(), hashlib.sha256).digest()
    if good[:4] != unb64(s)[:4]:
        raise ValueError("bad signature")
    return json.loads(unb64(p))

forged = b64(b'{"alg":"none"}') + "." + b64(b'{"sub":"admin","aud":"other-api","exp":1}') + "."
print(verify(forged))
{'sub': 'admin', 'aud': 'other-api', 'exp': 1}
Answer

(1) alg taken from the token, none accepted; (2) only the first 4 bytes of the signature compared, and not in constant time; (3) no exp, aud or iss check. Fixed core: if header.get("alg") != "HS256": raise ValueError(...); if not hmac.compare_digest(good, unb64(s)): raise ...; then claims = json.loads(unb64(p)) and check claims["aud"] == "orders-api", claims["iss"], and isinstance(claims.get("exp"), int) and claims["exp"] > now.

Exercise 5: OAuth callback

A single-page app's callback reads code from the URL and exchanges it; it never sent state, uses no PKCE, and its registered redirect URI is https://app.lab.test/ matched as a prefix. Name two attacks and the fixes. Lessons: OAuth flaws, PKCE.

Answer

Login CSRF (the attacker's code forced into the victim's browser, because there is no state), and code theft through a redirect URI the attacker can steer to an open redirect or user content under the prefix. Fixes: random state (and nonce) checked on return, PKCE S256, exact redirect URI registration, and checking iss, as ExcelTAD's own client does.

Exercise 6: injection, blind

Extend the boolean-blind example so it extracts the e-mail of user 1 instead of the token, and count the requests. Then fix product_page so the same loop extracts nothing. Lesson: blind SQL injection.

Answer

Replace reset_token by email in both the length query and the substr query. The fix: db.execute("SELECT name FROM products WHERE id = ?", (id_param,)) (and int(id_param) validation); the condition 7 AND (…) is then not an integer id, every ask() returns false, and the loop finds length "none" (the next() raises StopIteration, which you can catch and report as "not injectable").

Exercise 7: which context?

For each line, name the output context and the correct way to insert v safely. Lessons: DOM XSS, XSS defences.

  1. el.innerHTML = "<p>" + v + "</p>"
  2. html = `<a href="${v}">site</a>`
  3. `<script>const user = "${v}";</script>` in a server template
  4. `<div title="${v}">`
Answer
  1. HTML text: p.textContent = v. 2. URL attribute: parse with new URL(), allow http:/https:, set a.href through the DOM. 3. JavaScript string inside HTML: don't; put the data in <script type="application/json" id="user"> (JSON-encoded, with < escaped as \u003c so a </script> in the data can't end the element) and read it with JSON.parse. 4. Attribute: setAttribute('title', v), or attribute-encode including quotes in the template.

Exercise 8: authorization matrix

An API has GET /api/projects/{id}, PUT /api/projects/{id}, DELETE /api/projects/{id} and GET /api/admin/audit. Roles: member (own projects: read, update), owner (own projects: everything), admin (audit only). Write the test matrix you would run with two members, one owner and one admin. Lessons: IDOR, function-level.

Answer

For each endpoint × caller × target project (own / someone else's): member A on A's project: GET 200, PUT 200, DELETE 403; member A on B's project: all 404 (or 403); owner on own: all 200; owner on another's: 404; admin on projects: 403/404 unless the policy says otherwise; GET /api/admin/audit: 200 for admin, 403 for everyone else; and every endpoint without a session: 401. Automate it from the policy table.

Exercise 9: SSRF review

A webhook feature lets customers enter a URL that the server calls on each order. List the checks it needs. Lesson: SSRF.

Answer

https only; resolve the host, reject if any address is private, loopback, link-local (169.254.0.0/16, including metadata), multicast or reserved, and connect to the checked address (no re-resolution: DNS rebinding); no redirects (or re-check each hop); short timeouts and small response limits; run from an isolated egress segment or through an egress proxy; log destinations; IMDSv2 on the host.

Exercise 10: race it

The example below sells the last ticket. Run it, explain the result, then fix buy with an atomic conditional update (UPDATE … WHERE stock > 0 and check rowcount). Lesson: race conditions.

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE tickets (id INTEGER PRIMARY KEY, stock INTEGER)")
db.execute("INSERT INTO tickets VALUES (1, 1)")

def check(buyer):                      # step 1 of each request: read the stock
    return db.execute("SELECT stock FROM tickets WHERE id = 1").fetchone()[0] > 0

def act(buyer):                        # step 2: write
    db.execute("UPDATE tickets SET stock = stock - 1 WHERE id = 1")
    return f"{buyer} got a ticket"

# Two requests interleaved the way concurrent servers interleave them:
ok_a, ok_b = check("ana"), check("ben")
print(act("ana") if ok_a else "ana: sold out")
print(act("ben") if ok_b else "ben: sold out")
print("stock now:", db.execute("SELECT stock FROM tickets WHERE id = 1").fetchone()[0])
ana got a ticket
ben got a ticket
stock now: -1
Answer

Both requests checked before either wrote, so both passed: one ticket sold twice and stock at −1. Fix: def buy(b): cur = db.execute("UPDATE tickets SET stock = stock - 1 WHERE id = 1 AND stock > 0"); return f"{b} got a ticket" if cur.rowcount == 1 else f"{b}: sold out". However the two calls interleave, only one UPDATE matches. A CHECK (stock >= 0) constraint is a good extra guard.

Exercise 11: write the finding

Write the finding for the race in exercise 10 using the template of Writing Findings: title, severity with a one-sentence justification, impact, reproduction, remediation, detection.

Answer (outline)

F-xx Last ticket can be sold several times (race condition, CWE-362, A06:2025). Severity: Medium/High depending on business impact (oversold events, refunds). Impact: concurrent purchases of the last tickets all succeed. Reproduction: with stock 1, send 10 purchase requests in parallel (Burp group send / curl … &), observe several successes and negative stock. Remediation: atomic conditional update with row-count check, CHECK (stock >= 0), idempotency keys on purchase. Detection: negative stock alerts; reconciliation of tickets sold vs capacity.

Practice problems for this course, with tests in 21 languages: Read a JWT Claim (Without Trusting It), Resolve a Request Path Safely.

Test yourself

Which single control stops both alg-none and HS/RS confusion?

  1. Longer keys
  2. The verifier fixes the allowed algorithm and key type itself
  3. Base64url
  4. Short expiry

In exercise 10, why did both buyers get a ticket?

  1. SQL injection
  2. Both checks ran before either update: check-then-act on shared state
  3. The stock was 2
  4. A typo

Which context is a.href = v?

  1. HTML text
  2. URL: allow-list schemes after parsing
  3. CSS
  4. JavaScript string

For a webhook feature, which SSRF check is essential when an allow-list is impossible?

  1. Block the word localhost
  2. Resolve the host, reject private/loopback/link-local addresses, connect to the checked address, no redirects
  3. Use POST
  4. Add a CSP