Capstone 2: Findings, CVSS, Fixes and Retest
Capstone 1 ended with a test plan. This lesson carries it out: each planned test becomes a check that proves a finding, each finding gets a CVSS v3.1 score and a fix, and the same checks, run again against the fixed application, become the retest. The trick that makes this work is to write every check so that it passes when the application is secure. Then one script is the evidence (it fails on the vulnerable build), the retest (it passes on the fixed build) and, kept in CI, the regression test.
The checks, against both builds
The code below is the whole Lab Library application from Capstone 1, unchanged, followed by a test harness that calls it directly as a function (WSGI apps are just functions of a request), so it runs in your browser with no network at all. It runs every check against the vulnerable build, then switches FIXED on, rotates the signing key, rebuilds the database and runs them again.
import hashlib, hmac, html, json, posixpath, sqlite3
from http.cookies import SimpleCookie
from urllib.parse import parse_qs
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
FIXED = False # the retest flips this to True
SECRET = b"lab-signing-key-0001" # lab-only; leaked by the debug page
FILES = {"public/help.txt": b"Opening hours: 9-17. Ask at the desk.\n",
"config/app.env": b"SECRET_KEY=lab-signing-key-0001\nDB_PATH=:memory:\n"}
def hash_pw(pw, salt=b"lab-fixed-salt01"): # real code: a new salt per user
if not FIXED:
return hashlib.sha256(pw.encode()).hexdigest() # unsalted, fast
return "scryptquot; + Scrypt(salt=salt, length=32, n=2**14, r=8, p=1).derive(pw.encode()).hex()
def make_db():
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, pw TEXT, role TEXT);
CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT, author TEXT);
CREATE TABLE loans (id INTEGER PRIMARY KEY, user_id INTEGER, book_id INTEGER, due TEXT);
INSERT INTO books VALUES (1, 'Networks', 'Tanaka'), (2, 'Ciphers', 'Okafor'), (3, 'Kernels', 'Lind');
INSERT INTO loans VALUES (1, 1, 2, '2026-02-01'), (2, 2, 1, '2026-02-03'), (3, 2, 3, '2026-02-05');
""")
for uid, name, pw, role in [(1, "alice", "lab-alice-pw", "member"), (2, "bob", "lab-bob-pw", "member"),
(3, "admin", "lab-admin-pw", "librarian")]:
db.execute("INSERT INTO users VALUES (?, ?, ?, ?)", (uid, name, hash_pw(pw), role))
return db
DB = make_db()
def sign(name):
return name + "." + hmac.new(SECRET, name.encode(), "sha256").hexdigest()[:16]
def current_user(environ):
c = SimpleCookie(environ.get("HTTP_COOKIE", "")).get("session")
if not c or "." not in c.value:
return None
name = c.value.rsplit(".", 1)[0]
if not hmac.compare_digest(c.value, sign(name)):
return None
return DB.execute("SELECT id, name, role FROM users WHERE name = ?", (name,)).fetchone()
def app(environ, start_response):
path, method = environ["PATH_INFO"], environ["REQUEST_METHOD"]
query = parse_qs(environ.get("QUERY_STRING", ""))
headers = [("Content-Type", "text/html; charset=utf-8")]
if FIXED:
headers += [("Content-Security-Policy", "default-src 'self'"), ("X-Content-Type-Options", "nosniff")]
def reply(status, body, extra=()):
start_response(status, headers + list(extra))
return [body.encode() if isinstance(body, str) else body]
if path == "/":
return reply("200 OK", "<h1>Lab Library</h1><form action=/search><input name=q></form>")
if path == "/robots.txt":
return reply("200 OK", "User-agent: *\nDisallow: /download\n")
if path == "/search":
q = query.get("q", [""])[0]
try:
if FIXED:
rows = DB.execute("SELECT title, author FROM books WHERE title LIKE ?", (f"%{q}%",)).fetchall()
else:
rows = DB.execute(f"SELECT title, author FROM books WHERE title LIKE '%{q}%'").fetchall()
except sqlite3.Error as e:
return reply("500 Internal Server Error", "error" if FIXED else f"database error: {e}")
shown = html.escape(q) if FIXED else q
items = "".join(f"<li>{html.escape(str(t))} ({html.escape(str(a))})</li>" for t, a in rows)
return reply("200 OK", f"<p>Results for {shown}</p><ul>{items}</ul>")
if path == "/login" and method == "POST":
size = int(environ.get("CONTENT_LENGTH") or 0)
form = parse_qs(environ["wsgi.input"].read(size).decode())
name, pw = form.get("user", [""])[0], form.get("password", [""])[0]
row = DB.execute("SELECT pw FROM users WHERE name = ?", (name,)).fetchone()
if not row or not hmac.compare_digest(row[0], hash_pw(pw)):
return reply("401 Unauthorized", "invalid user name or password")
flags = "; HttpOnly; Secure; SameSite=Lax" if FIXED else ""
return reply("200 OK", f"welcome {name}", [("Set-Cookie", f"session={sign(name)}; Path=/{flags}")])
if path.startswith("/api/loans/"):
user = current_user(environ)
if user is None:
return reply("401 Unauthorized", "sign in first")
loan_id = path.rsplit("/", 1)[1]
sql = "SELECT id, user_id, book_id, due FROM loans WHERE id = ?"
args = (loan_id,)
if FIXED and user[2] != "librarian":
sql, args = sql + " AND user_id = ?", (loan_id, user[0])
row = DB.execute(sql, args).fetchone()
if not row:
return reply("404 Not Found", "no such loan")
return reply("200 OK", json.dumps(dict(zip(("id", "user_id", "book_id", "due"), row))))
if path == "/download":
target = posixpath.normpath("public/" + query.get("file", [""])[0])
if FIXED and not target.startswith("public/"):
return reply("403 Forbidden", "not allowed")
if target in FILES:
return reply("200 OK", FILES[target])
return reply("404 Not Found", "no such file")
return reply("404 Not Found", "not found")
def debug_app(environ, start_response): # the "metrics" port, meant for developers only
if FIXED or environ["PATH_INFO"] != "/debug":
start_response("404 Not Found", [("Content-Type", "text/plain")])
return [b"not found"]
start_response("200 OK", [("Content-Type", "application/json")])
return [json.dumps({"version": "0.9-lab", "secret_key": SECRET.decode(), "db": ":memory:"}).encode()]
# ---------------- the test harness: call the app directly, no network at all ----------------
import io
def call(handler, method, path, query="", body="", cookie=""):
got = {}
def start(status, headers):
got["status"], got["headers"] = int(status[:3]), headers
env = {"REQUEST_METHOD": method, "PATH_INFO": path, "QUERY_STRING": query, "HTTP_COOKIE": cookie,
"CONTENT_LENGTH": str(len(body)), "wsgi.input": io.BytesIO(body.encode())}
text = b"".join(handler(env, start)).decode()
return got["status"], got["headers"], text
def login(name, pw):
status, headers, _ = call(app, "POST", "/login", body=f"user={name}&password={pw}")
cookie = dict(headers).get("Set-Cookie", "")
return cookie.split(";")[0], cookie
def run_checks():
results = []
def check(fid, name, secure, evidence):
results.append(secure)
print(f" [{'PASS' if secure else 'FAIL'}] {fid} {name}: {evidence}")
s, _, body = call(app, "GET", "/search", "q=zzz' UNION SELECT name, pw FROM users--")
check("F1", "search is not injectable", "alice" not in body, f"{s} rows: {body.split('<ul>')[1].removesuffix('</ul>')[:52] or 'none'}")
alice, raw_cookie = login("alice", "lab-alice-pw")
s, _, body = call(app, "GET", "/api/loans/2", cookie=alice)
check("F2", "alice cannot read bob's loan 2", s == 404, f"{s} {body}")
s, _, body = call(app, "GET", "/download", "file=../config/app.env")
check("F3", "no files outside public/", s == 403, f"{s} {body.splitlines()[0]}")
s, _, body = call(app, "GET", "/search", "q=<script>alert(1)</script>")
check("F4", "search output is escaped", "<script>" not in body, body[:50])
stored = DB.execute("SELECT pw FROM users WHERE name = 'alice'").fetchone()[0]
check("F5", "passwords use a slow salted hash", stored.startswith("scryptquot;), stored[:20] + "...")
s, _, body = call(debug_app, "GET", "/debug")
check("F6", "debug endpoint closed", s == 404, f"{s} {body[:44]}")
forged = "session=" + "admin." + hmac.new(b"lab-signing-key-0001", b"admin", "sha256").hexdigest()[:16]
s, _, body = call(app, "GET", "/api/loans/3", cookie=forged)
check("F6", "cookie forged with the leaked key rejected", s == 401, f"{s} {body}")
_, headers, _ = call(app, "GET", "/")
check("F7", "CSP header and HttpOnly cookie", "Content-Security-Policy" in dict(headers)
and "HttpOnly" in raw_cookie, raw_cookie.split(";", 1)[1].strip() or "(no flags)")
s, _, body = call(app, "GET", "/api/loans/1", cookie=alice)
check("REG", "alice still reads her own loan 1", s == 200, f"{s} {body}")
print(f" {sum(results)}/{len(results)} checks secure")
print("=== vulnerable build")
run_checks()
FIXED, SECRET = True, b"rotated-lab-key-0002" # the fixes, plus a new signing key after the leak
DB = make_db()
print("=== fixed build")
run_checks()=== vulnerable build
[FAIL] F1 search is not injectable: 200 rows: <li>admin (9ffdc2b2271a002ce6374fa7f3b76d63ed810e528
[FAIL] F2 alice cannot read bob's loan 2: 200 {"id": 2, "user_id": 2, "book_id": 1, "due": "2026-02-03"}
[FAIL] F3 no files outside public/: 200 SECRET_KEY=lab-signing-key-0001
[FAIL] F4 search output is escaped: <p>Results for <script>alert(1)</script></p><ul></
[FAIL] F5 passwords use a slow salted hash: 3754d9fd330c2a884efc...
[FAIL] F6 debug endpoint closed: 200 {"version": "0.9-lab", "secret_key": "lab-si
[FAIL] F6 cookie forged with the leaked key rejected: 200 {"id": 3, "user_id": 2, "book_id": 3, "due": "2026-02-05"}
[FAIL] F7 CSP header and HttpOnly cookie: Path=/
[PASS] REG alice still reads her own loan 1: 200 {"id": 1, "user_id": 1, "book_id": 2, "due": "2026-02-01"}
1/9 checks secure
=== fixed build
[PASS] F1 search is not injectable: 200 rows: none
[PASS] F2 alice cannot read bob's loan 2: 404 no such loan
[PASS] F3 no files outside public/: 403 not allowed
[PASS] F4 search output is escaped: <p>Results for <script>alert(1)</script&g
[PASS] F5 passwords use a slow salted hash: scrypt$75c9b97bfa16f...
[PASS] F6 debug endpoint closed: 404 not found
[PASS] F6 cookie forged with the leaked key rejected: 401 sign in first
[PASS] F7 CSP header and HttpOnly cookie: Path=/; HttpOnly; Secure; SameSite=Lax
[PASS] REG alice still reads her own loan 1: 200 {"id": 1, "user_id": 1, "book_id": 2, "due": "2026-02-01"}
9/9 checks secure
Against the vulnerable build, eight of nine checks fail, and each failure is the evidence for a finding:
- F1, SQL injection in search. The
UNION SELECT name, pw FROM usersterm returns the user table through the search results: user names and password hashes, without signing in. - F2, IDOR on loans. Signed in as alice,
/api/loans/2returns bob's loan; the query checks the loan id but not its owner. - F3, path traversal.
file=../config/app.envnormalises toconfig/app.env, outsidepublic/, and the file holds the secret key. Note the chain: F3 is a second route to the same key as F6. - F4, reflected XSS. The search term is echoed into the page unescaped, so a link with a script in
qruns in the victim's browser. - F5, weak password storage. Unsalted SHA-256 (found in the code review): with F1's hash dump, an attacker can test billions of guesses per second, and equal passwords have equal hashes.
- F6, debug endpoint leaks the signing key. And the impact is proven, not claimed: a cookie for
adminsigned with the leaked key is accepted and reads loan 3. - F7, missing CSP and cookie flags. No
Content-Security-Policy, and the session cookie lacksHttpOnly,SecureandSameSite, so F4's script could read it.
The regression check passes in both builds: alice can still read her own loan. A fix that breaks the application is not a fix.
Scoring the findings
Each finding gets a CVSS v3.1 base score for the deployment in the rules of engagement (the app on the network). The function below implements the specification's formulas (the same ones as the CVSS lesson and its lab):
W = {"AV": {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2}, "AC": {"L": 0.77, "H": 0.44},
"UI": {"N": 0.85, "R": 0.62}, "CIA": {"H": 0.56, "L": 0.22, "N": 0}}
def roundup(x): # CVSS v3.1 Appendix A
i = round(x * 100000)
return i / 100000 if i % 10000 == 0 else (i // 10000 + 1) / 10
def score(vector):
m = dict(part.split(":") for part in vector.split("/")[1:])
changed = m["S"] == "C"
pr = {"N": 0.85, "L": 0.68 if changed else 0.62, "H": 0.5 if changed else 0.27}[m["PR"]]
iss = 1 - (1 - W["CIA"][m["C"]]) * (1 - W["CIA"][m["I"]]) * (1 - W["CIA"][m["A"]])
impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 if changed else 6.42 * iss
expl = 8.22 * W["AV"][m["AV"]] * W["AC"][m["AC"]] * pr * W["UI"][m["UI"]]
if impact <= 0:
return 0.0
return roundup(min((1.08 if changed else 1) * (impact + expl), 10))
def severity(s):
return "None" if s == 0 else "Low" if s < 4 else "Medium" if s < 7 else "High" if s < 9 else "Critical"
FINDINGS = [
("F1", "SQL injection in book search", "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N"),
("F2", "IDOR: any member reads any loan", "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N"),
("F3", "path traversal in /download", "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N"),
("F4", "reflected XSS in search", "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N"),
("F5", "unsalted SHA-256 password hashes", "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:N/A:N"),
("F6", "debug endpoint leaks the signing key", "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N"),
("F7", "missing CSP, cookie without HttpOnly", "CVSS:3.1/AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:N/A:N"),
]
for fid, title, vector in sorted(FINDINGS, key=lambda f: -score(f[2])):
s = score(vector)
print(f"{fid} {s:4.1f} {severity(s):8} {title:38} {vector[9:]}")F6 9.1 Critical debug endpoint leaks the signing key AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N
F1 7.5 High SQL injection in book search AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N
F3 7.5 High path traversal in /download AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N
F4 6.1 Medium reflected XSS in search AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N
F5 5.9 Medium unsalted SHA-256 password hashes AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:N/A:N
F2 4.3 Medium IDOR: any member reads any loan AV:N/AC:L/PR:L/UI:N/S:U/C:L/I:N/A:N
F7 3.1 Low missing CSP, cookie without HttpOnly AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:N/A:N
Some choices deserve a sentence each in the report, because reviewers will question them:
- F6 is critical (9.1) because the leaked key lets anyone forge any session, so both confidentiality and integrity are high, with no privileges and no user interaction.
- F1 and F3 are high (7.5): unauthenticated reads of sensitive data. F3's file also contains the key; the report describes that chain rather than inflating the base score, and the fix list makes sure both routes are closed.
- F5 has
AC:H(5.9): it only matters once hashes leak, which needs another bug (F1 here). Some testers report it as an informational design issue; scoring it, and saying why, is also defensible. - F4 is
S:C(6.1): the script runs in the user's browser, a different security scope from the server. - F2 is
C:L(4.3): loans reveal what others borrow; there is no write access and no sensitive personal data in the toy schema. In a real library, reading habits can be sensitive, and you might argue forC:H.
The CVSS lab lets you check one of them by hand; it starts at F4's vector:
If the client wants CVSS v4.0, compute each vector with FIRST's calculator and quote the score as CVSS-B with its v4.0 vector, as the v4.0 lesson describes; the ordering of these seven findings does not change much, but the numbers do.
Fixes and detections
Every finding gets a fix (what changed in the code) and a detection (how the client would see it being exploited). Both are in the FIXED branches of the code you just ran:
| Finding | Fix in the code | How it is detected |
|---|---|---|
| F1 SQL injection | parameterised LIKE ? query; generic error message |
500 errors from /search; SQL keywords (UNION, --) in the q parameter in access logs |
| F2 IDOR | AND user_id = ? unless the caller is a librarian |
one session reading many loan ids; 404s on /api/loans/ from one user |
| F3 path traversal | normalise, then require the public/ prefix |
.. or encoded slashes in file=; 403s from /download |
| F4 reflected XSS | html.escape on output; CSP default-src 'self' |
<script or event handlers in q; CSP violation reports (with a report-to directive) |
| F5 password storage | scrypt with a per-user salt (fixed here for stable output), rehash at next login; the lesson's N = 2^14 keeps it fast, production should use at least OWASP's minimum (N = 2^17, r = 8, p = 1) or Argon2id | not detectable as an attack; found by code review and a check on the stored format |
| F6 debug endpoint | removed from the production build; key rotated | any request to port 9090 from outside; sessions signed with the old key |
| F7 headers and cookie | CSP and nosniff headers; HttpOnly; Secure; SameSite=Lax |
header checks in CI; a periodic header scan |
Rotation is the line most often missed. Closing the debug port stops future leaks, but the old key has already leaked (twice, through F6 and F3), so every session signed with it must stop working. The retest checks exactly that: the forged admin cookie is now rejected with 401.
The retest
The second run is the retest: 9 of 9 checks pass, including the regression check. In a real engagement the retest happens after the client has fixed their code, against their new build, and the report's findings table gets a "retest" column: fixed, partly fixed, or not fixed, with the date. Keep the harness: handed to the client, it becomes their regression suite.
Pitfalls
- A check that tests the payload, not the property. "The string
UNIONis rejected" is defeated byunion; "no user data appears in search results" is not. - Fixing F6 but not F3. Two routes to one secret: fix both and rotate.
- Severity by feeling. Write the vector, then the reason for each metric you could argue about.
Practice
1. A colleague proposes fixing F3 by rejecting any file value that contains ../. Why is the lesson's fix better?
Blocklists miss encodings and variants (..%2f, ....//, absolute paths, backslashes on Windows). The lesson's fix normalises the path first and then checks that the result is still inside the allowed directory, which tests the property that matters rather than one spelling of the attack.
2. Score F2 again assuming loans include the borrower's home address. What changes?
Confidentiality becomes high: CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N = 6.5, Medium. Add it to FINDINGS to check.
3. Add a check for a missing rate limit on /login. What would it test, and would it pass on the fixed build?
Send, say, 20 wrong passwords for alice and check that some response is a 429 or a lockout message. It would fail on both builds: neither has a rate limit. That is finding F8 (A07:2025, authentication failures), which the fixed build doesn't address; adding it is part of the mini project.
Test yourself
Why are the checks written to pass when the application is secure?
- It looks better
- So that the same script is the evidence (fails on the vulnerable build), the retest (passes on the fixed one) and a regression test
- Because CVSS requires it
- To hide findings
Which finding scores highest, and why?
- F1, because SQL injection is always critical
- F6, because the leaked key lets anyone forge any session (C:H, I:H, no privileges)
- F4, because scope changes
- F7, because headers matter
Why is closing the debug port not enough to fix F6?
- Ports reopen
- The key has already leaked (via F6 and F3), so it must be rotated and old sessions invalidated
- CVSS says so
- It is enough
What does the REG check protect against?
- SQL injection
- A fix that breaks normal use of the application
- Slow tests
- Missing headers