Mini Project: Break, Fix, Retest and Report a Login App
This project is the whole course in one loop, the loop a web security engineer runs every week: take a small application, find its vulnerabilities with the techniques of the course, fix them in the code, retest to prove the fix and that nothing else broke, and report the result so someone else can act on it. The target is a deliberately vulnerable notes app with a login form and a notes API, which you start yourself in your sandbox on 127.0.0.1. It contains (at least) a SQL injection in the login and an IDOR in the notes API; finding anything else is a bonus. Everything stays inside the sandbox: the app binds loopback, serves only its own in-memory database, and the tests talk only to it.
The scope (write it down even for a lab)
| Item | Value |
|---|---|
| Target | the notes app from the session below, http://127.0.0.1:8000, in your sandbox |
| Test accounts | alice / lab-alice-pw (note 1), bob / lab-bob-pw (notes 2, 3) |
| In scope | login, /api/notes/{id}, /api/me; all techniques of this course |
| Out of scope | everything else; no denial of service |
| Data | synthetic only |
Step 1: the app and an automated test
The app has a vulnerable and a fixed mode, so the same test suite can show the difference. Read app.py before running it: spotting the bugs in code review first is part of the exercise. The test script retest.py is the reusable part: it encodes each finding as a check that passes when the application is secure, so running it after the fix is the retest, and keeping it in CI makes it a regression test.
cat > app.py <<'PY'
import json, secrets, sqlite3, sys
from http.cookies import SimpleCookie
from urllib.parse import parse_qs
from wsgiref.simple_server import make_server, WSGIRequestHandler
FIXED = sys.argv[1] == "fixed"
db = sqlite3.connect(":memory:", check_same_thread=False)
db.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT UNIQUE, pw TEXT);
CREATE TABLE notes (id INTEGER PRIMARY KEY, owner INTEGER, text TEXT);
INSERT INTO users VALUES (1, 'alice', 'lab-alice-pw'), (2, 'bob', 'lab-bob-pw');
INSERT INTO notes VALUES (1, 1, 'alice: dentist on friday'), (2, 2, 'bob: wifi password is lab-wifi'), (3, 2, 'bob: buy milk');
""")
# (Plaintext passwords keep the toy small. They are finding F-03 below; real apps store Argon2id hashes.)
SESSIONS = {}
class Quiet(WSGIRequestHandler):
def log_message(self, *args):
pass
def login(name, pw):
if FIXED:
row = db.execute("SELECT id, name FROM users WHERE name = ? AND pw = ?", (name, pw)).fetchone()
else:
row = db.execute(f"SELECT id, name FROM users WHERE name = '{name}' AND pw = '{pw}'").fetchone()
return row
def note(note_id, user_id):
if FIXED:
return db.execute("SELECT id, text FROM notes WHERE id = ? AND owner = ?", (note_id, user_id)).fetchone()
return db.execute("SELECT id, text FROM notes WHERE id = ?", (note_id,)).fetchone()
def app(environ, start_response):
def reply(status, obj, headers=()):
start_response(status, [("Content-Type", "application/json"), *headers])
return [json.dumps(obj).encode() + b"\n"]
sid = SimpleCookie(environ.get("HTTP_COOKIE", "")).get("sid")
user = SESSIONS.get(sid.value) if sid else None
path, method = environ["PATH_INFO"], environ["REQUEST_METHOD"]
if path == "/login" and method == "POST":
form = parse_qs(environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH") or 0)).decode())
try:
row = login(form.get("user", [""])[0], form.get("password", [""])[0])
except sqlite3.Error as e:
return reply("500 Internal Server Error", {"error": str(e) if not FIXED else "internal error"})
if not row:
return reply("401 Unauthorized", {"error": "invalid username or password"})
token = secrets.token_urlsafe(16)
SESSIONS[token] = {"id": row[0], "name": row[1]}
return reply("200 OK", {"welcome": row[1]}, [("Set-Cookie", f"sid={token}; Path=/; HttpOnly; SameSite=Lax")])
if user is None:
return reply("401 Unauthorized", {"error": "login"})
if path == "/api/me":
return reply("200 OK", user)
if path.startswith("/api/notes/") and path.rsplit("/", 1)[1].isdigit():
row = note(int(path.rsplit("/", 1)[1]), user["id"])
return reply("200 OK", {"id": row[0], "text": row[1]}) if row else reply("404 Not Found", {"error": "not found"})
return reply("404 Not Found", {"error": "not found"})
make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
cat > retest.py <<'PY'
import http.cookiejar, json, urllib.error, urllib.parse, urllib.request
BASE = "http://127.0.0.1:8000"
def client():
return urllib.request.build_opener(urllib.request.ProxyHandler({}),
urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
def call(c, path, form=None):
data = urllib.parse.urlencode(form).encode() if form else None
try:
with c.open(BASE + path, data=data, timeout=5) as r:
return r.status, json.loads(r.read())
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read())
results = []
def check(fid, name, secure, detail):
results.append(secure)
print(f" [{'PASS' if secure else 'FAIL'}] {fid} {name}: {detail}")
# F-01 SQL injection in login (A05:2025, CWE-89)
c = client()
st, body = call(c, "/login", {"user": "alice' --", "password": "x"})
check("F-01", "login rejects SQL in user name", st == 401, f"{st} {body}")
st, body = call(client(), "/login", {"user": "'", "password": "x"})
check("F-01", "no database error leaked", "error" in body and "sql" not in body["error"].lower()
and "unrecognized" not in body["error"], f"{st} {body}")
# F-02 IDOR on notes (A01:2025, CWE-639)
alice = client()
call(alice, "/login", {"user": "alice", "password": "lab-alice-pw"})
st, body = call(alice, "/api/notes/1")
check("F-02", "owner reads own note", st == 200, f"{st} {body}")
leaked = [n for n in (2, 3) if call(alice, f"/api/notes/{n}")[0] == 200]
check("F-02", "alice cannot read bob's notes", not leaked, f"readable: {leaked or 'none'}")
# Regression: the app still works for legitimate users
bob = client()
st, body = call(bob, "/login", {"user": "bob", "password": "lab-bob-pw"})
check("REG", "bob logs in and reads note 2", st == 200 and call(bob, "/api/notes/2")[0] == 200, f"{st} {body}")
print(f" {sum(results)}/{len(results)} checks secure")
PY
for mode in vulnerable fixed; do
python3 app.py $mode &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/api/me && break; sleep 0.1; done
echo "=== $mode"
python3 retest.py
kill %1; wait 2>/dev/null
done=== vulnerable
[FAIL] F-01 login rejects SQL in user name: 200 {'welcome': 'alice'}
[FAIL] F-01 no database error leaked: 500 {'error': 'unrecognized token: "x\'"'}
[PASS] F-02 owner reads own note: 200 {'id': 1, 'text': 'alice: dentist on friday'}
[FAIL] F-02 alice cannot read bob's notes: readable: [2, 3]
[PASS] REG bob logs in and reads note 2: 200 {'welcome': 'bob'}
2/5 checks secure
=== fixed
[PASS] F-01 login rejects SQL in user name: 401 {'error': 'invalid username or password'}
[PASS] F-01 no database error leaked: 401 {'error': 'invalid username or password'}
[PASS] F-02 owner reads own note: 200 {'id': 1, 'text': 'alice: dentist on friday'}
[PASS] F-02 alice cannot read bob's notes: readable: none
[PASS] REG bob logs in and reads note 2: 200 {'welcome': 'bob'}
5/5 checks secure
Against the vulnerable mode, the suite reproduces both findings: the quote-and-comment user name logs in as alice without her password, a single quote returns SQLite's error text, and alice reads both of bob's notes, including his Wi-Fi password. Against the fixed mode (parameterised queries, a generic error, and the ownership condition in the notes query), every check passes, including the regression check that legitimate users still work.
Step 2: do it yourself
The fixed mode is the answer key. To practise properly, work on a copy of the vulnerable code paths:
- Find: before reading the fixes, review
login()andnote()and write down the two bugs with their CWE ids. Then confirm each from the outside withcurl(the SQLi and IDOR lessons show the requests). - Look for more: the plaintext passwords; the error message in vulnerable mode; is there rate limiting on
/login(password login)? Is the session cookieSecure(cookies)? Does logout exist? Each is a finding at its own severity. - Fix: change only what is needed; keep the fix minimal and reviewable.
- Retest: run
retest.py; add a check for every additional finding you fixed (a rate-limit check: the sixth wrong password in a minute gets 429). - Detect: write one log rule per finding that would catch exploitation (quotes and
--in login names; one session requesting many note ids) as in the lessons' detection sections.
Step 3: the report
Write the report with this template (Markdown is fine). Severity uses CVSS v3.1 vectors you can compute with the function in Writing Findings, or v4.0 with FIRST's calculator.
# Security assessment: Lab Notes app (build: <commit or date>)
## 1. Summary
One paragraph for a manager: what was tested, when, the two or three most important results, overall risk,
and whether the fixes were verified.
## 2. Scope and method
Target, test accounts, in/out of scope, dates, tools (curl, retest.py), methodology (OWASP WSTG categories
covered: ATHN, ATHZ, INPV, SESS, ERRH).
## 3. Findings overview
| Id | Title | Severity (CVSS) | Category | Status |
|------|-----------------------------------------|----------------------|---------------------|-------------------|
| F-01 | SQL injection in login (user field) | Critical (9.8) | A05:2025, CWE-89 | Fixed, retested |
| F-02 | Notes of other users readable (IDOR) | Medium (6.5) | A01:2025, CWE-639 | Fixed, retested |
| F-03 | Passwords stored in plaintext | <your rating> | A06:2025, CWE-256 | Open |
| F-04 | Database errors returned to the client | <your rating> | A10:2025, CWE-209 | Fixed, retested |
## 4. Finding details (one block per finding)
### F-01 SQL injection in login
Severity / Affected / Classification / Status
Description (2-4 sentences)
Impact (in this app)
Reproduction (numbered steps, exact requests, test accounts only)
Evidence (redacted request/response excerpt, timestamp)
Remediation (the specific code change) and defence in depth
Detection (the log query or rule that would catch exploitation)
Retest (date, result, retest.py output line)
## 5. Recommendations beyond the findings
e.g. Argon2id password hashing, login rate limiting, an authorization helper used by every handler,
retest.py in CI.Two scores in the table come from the vectors of this lab: an unauthenticated login bypass that gives full access to any account is AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H (9.8), and the IDOR is AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N (6.5). Rate the others yourself and justify them in one sentence each. The categories follow the 2025 CWE mappings: plaintext password storage (CWE-256) is listed under A06 Insecure Design, while a weak password hash (CWE-916) would be A04 Cryptographic Failures.
Checklist before you hand it in
- Every finding reproducible from its steps alone, by someone who hasn't seen your screen.
- No real data, no secrets in evidence (the test passwords are lab-only, say so).
- Each remediation names the code location and the change.
- Each finding has a detection idea.
- The retest output is included, with the date.
- The safety line held: the app ran only on
127.0.0.1in your sandbox, and nothing else was tested.
Test yourself
Why does retest.py express each finding as a check that passes when the app is secure?
- It looks nicer
- So the same script proves the vulnerability before the fix, proves the fix after, and catches regressions in CI
- Tests can't fail
- It is required by CVSS
Which single change fixed the IDOR in the fixed mode?
- A longer session token
- Adding
AND owner = ?with the caller's id to the notes query - HTTPS
- Hiding note ids
Why does the suite include a regression check for bob's legitimate login?
- Bob is an attacker
- A fix that breaks normal use isn't a fix; the check shows the app still works
- To test SQL injection
- To fill the report
Which part of the report is written for a manager?
- Reproduction steps
- The summary: what was tested, the most important results, overall risk and fix status
- Evidence
- CVSS vectors