Show contents
Chapter 6 of 7 · 25 min
Project: the security audit of a book club
By the end of this chapter, you'll be able to
- Review code looking for known vulnerabilities
- Demonstrate a vulnerability on an authorised target, without going further than necessary
- Fix each vulnerability with the right protection
- Check the fixes with automated tests
The code to audit
import hashlib, sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE members (name TEXT, digest TEXT)")
db.execute("CREATE TABLE comments (id INTEGER PRIMARY KEY, author TEXT, text TEXT)")
def sign_up(name, password):
digest = hashlib.md5(password.encode()).hexdigest() # (1)
db.execute(f"INSERT INTO members VALUES ('{name}', '{digest}')") # (2)
print(f"Sign-up of {name} with password {password}") # (3)
def log_in(name, password):
digest = hashlib.md5(password.encode()).hexdigest()
row = db.execute(f"SELECT name FROM members WHERE name = '{name}' AND digest = '{digest}'").fetchone() # (2)
return row is not None
def show_comments():
rows = db.execute("SELECT author, text FROM comments").fetchall()
return "\n".join(f"<p><b>{a}</b>: {t}</p>" for a, t in rows) # (4)
A careful read reveals four problems:
- passwords are hashed with MD5, unsalted: a fast function, broken long ago;
- queries are built with f-strings: SQL injection;
- the password is written in plain text to the log: anyone who reads the logs (a colleague, a monitoring service, an attacker) sees it;
- comments are inserted into the HTML without escaping: stored XSS.
Demonstrate, and go no further
An audit demonstrates each vulnerability on the authorised copy, with the minimum needed to convince: no question of dumping the database or keeping data. For the injection, it is enough to show that you can log in without a password:
import hashlib, sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE members (name TEXT, digest TEXT)")
db.execute("INSERT INTO members VALUES ('awa', ?)", (hashlib.md5(b"reading-2026").hexdigest(),))
def log_in(name, password):
digest = hashlib.md5(password.encode()).hexdigest()
row = db.execute(f"SELECT name FROM members WHERE name = '{name}' AND digest = '{digest}'").fetchone()
return row is not None
print("right password:", log_in("awa", "reading-2026"))
print("wrong password:", log_in("awa", "guess"))
print("injection:", log_in("awa' --", "anything"))
right password: True
wrong password: False
injection: True
-- starts a comment in SQL: everything after it, including the digest check, is ignored. With just a member's name, you get into their account.
The report describes each vulnerability, its impact, its fix and the test that covers it.
Text description of the animation
- Each vulnerability has a recognisable signature in the code.
- A minimal demonstration is enough: it proves the risk without damaging anything.
- Each vulnerability gets its protection, not a cobbled-together filter.
- The demonstration's attacks become tests that must fail… for the attacker.
- The report describes each vulnerability, its impact, its fix and the test that covers it.
The fixed version
import hashlib, hmac, html, sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE members (name TEXT UNIQUE, salt TEXT, digest TEXT)")
db.execute("CREATE TABLE comments (id INTEGER PRIMARY KEY, author TEXT, text TEXT)")
log = []
def pbkdf2(password, salt, iterations=10_000):
u = hmac.new(password, salt + b"\x00\x00\x00\x01", "sha256").digest()
result = int.from_bytes(u, "big")
for _ in range(iterations - 1):
u = hmac.new(password, u, "sha256").digest()
result ^= int.from_bytes(u, "big")
return result.to_bytes(32, "big").hex()
def sign_up(name, password, salt):
db.execute("INSERT INTO members VALUES (?, ?, ?)", (name, salt.hex(), pbkdf2(password.encode(), salt)))
log.append(f"sign-up of {name}")
def log_in(name, password):
row = db.execute("SELECT salt, digest FROM members WHERE name = ?", (name,)).fetchone()
if row is None:
return False
computed = pbkdf2(password.encode(), bytes.fromhex(row[0]))
return hmac.compare_digest(computed, row[1])
def comment(author, text):
db.execute("INSERT INTO comments (author, text) VALUES (?, ?)", (author, text))
def show_comments():
rows = db.execute("SELECT author, text FROM comments ORDER BY id").fetchall()
return "\n".join(f"<p><b>{html.escape(a)}</b>: {html.escape(t)}</p>" for a, t in rows)
sign_up("awa", "reading-2026", bytes.fromhex("a1b2c3d4e5f60718"))
sign_up("kofi", "reading-2026", bytes.fromhex("0f1e2d3c4b5a6978"))
comment("kofi", "<script>steal()</script>")
tests = {
"right password accepted": log_in("awa", "reading-2026"),
"wrong password rejected": not log_in("awa", "guess"),
"injection rejected": not log_in("awa' --", "anything"),
"different digests for the same password": len({d for (d,) in db.execute("SELECT digest FROM members")}) == 2,
"no secret in the log": not any("reading-2026" in line for line in log),
"comment neutralised": "<script>" not in show_comments(),
}
for name, ok in tests.items():
print("✓" if ok else "✗", name)
✓ right password accepted
✓ wrong password rejected
✓ injection rejected
✓ different digests for the same password
✓ no secret in the log
✓ comment neutralised
Each attack from the audit has become a test. If a future developer reintroduces an f-string into a query, the “injection rejected” test will flag it before going live. In the real site, the salt would be drawn at random (secrets.token_bytes(16)), the number of iterations much higher, or better, hashing would be handed over to Argon2id.
Mini-lab: add your own attack testPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: the forgotten vulnerability
The club adds a delete(user, comment_id) function. The volunteer wrote it like this: it deletes the comment with the given id. Problem: any member can delete someone else's comment, simply by changing the id in the request sent. This is broken access control, the most widespread vulnerability in the OWASP Top 10 ranking. Fix the function so that a member can only delete their own comments, and return the number of deleted rows.
def delete(user, comment_id):
db.execute("DELETE FROM comments WHERE id = ?", (comment_id,))
Hint 1
Hint 2
cursor.rowcount tells how many rows the query changed.Show the solution and common mistakes
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE comments (id INTEGER PRIMARY KEY, author TEXT, text TEXT)")
db.executemany("INSERT INTO comments (author, text) VALUES (?, ?)", [("awa", "Good book"), ("kofi", "Too long")])
def delete(user, comment_id):
cursor = db.execute("DELETE FROM comments WHERE id = ? AND author = ?", (comment_id, user))
return cursor.rowcount
print("kofi deletes awa's comment:", delete("kofi", 1))
print("kofi deletes a comment by kofi:", delete("kofi", 2))
print(db.execute("SELECT author, text FROM comments").fetchall())
kofi deletes awa's comment: 0
kofi deletes a comment by kofi: 1
[('awa', 'Good book')]
The user must come from the session on the server, never from a field sent by the browser: otherwise, it would be enough to claim to be “awa”.
Common mistakes:
- Hiding the “Delete” button on other people's comments and stopping there: the interface is not a protection, the request can be sent without it.
- Checking permissions with a first query, then deleting with a second one: in between, the situation can change. A single query with both conditions is safer.
Summary
- 1An audit starts with reading: MD5, SQL f-strings, logged secrets and unescaped HTML are quick to spot.
- 2Each vulnerability is demonstrated on an authorised target, with the bare minimum.
- 3Each vulnerability has its protection: salted slow hashing, parameterised queries, logs without secrets, escaping.
- 4The audit's attacks become automated tests that protect the future.
- 5Permissions are checked on the server, for every action: hiding a button protects nothing.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.