Cybersecurity Exercises
Time to practise building defences. Each exercise has a starter playground that runs as-is and prints placeholder results, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. Open the solution only after you've had a real try.
| # | Exercise | Lesson |
|---|---|---|
| 1 | IP allow-list | IP Addresses & Subnets |
| 2 | First-match firewall | Network Threats & Defences |
| 3 | Download integrity check | Hashing & Integrity |
| 4 | Signed messages with HMAC | HMAC |
| 5 | Naive entropy estimate | Password Policy |
| 6 | Fix an injectable query | SQL Injection |
| 7 | Escape a comment | XSS |
| 8 | Contain a file path | Input Validation |
| 9 | Count failed logins | Logging & Detection |
1. IP allow-list
Write allowed(addr) that returns True only if addr is inside 10.8.0.0/16 or 192.168.50.0/24. Invalid input must return False, not crash. Use ipaddress, never string prefixes.
Expected: True False True False False for the five test addresses.
import ipaddress
ALLOWED = ["10.8.0.0/16", "192.168.50.0/24"]
def allowed(addr):
# TODO: parse addr (catch ValueError) and test membership in each network
return False
for a in ["10.8.200.1", "10.9.0.1", "192.168.50.77", "192.168.5.77", "not-an-ip"]:
print(a, allowed(a))10.8.200.1 False
10.9.0.1 False
192.168.50.77 False
192.168.5.77 False
not-an-ip False
Show solution
import ipaddress
ALLOWED = [ipaddress.ip_network(n) for n in ["10.8.0.0/16", "192.168.50.0/24"]]
def allowed(addr):
try:
ip = ipaddress.ip_address(addr)
except ValueError:
return False
return any(ip in net for net in ALLOWED)2. First-match firewall
RULES is an ordered list of (action, port) pairs. Write decide(port) that returns the action of the first matching rule, or "deny" if none matches (default deny).
Expected: ['allow', 'deny', 'deny', 'allow'].
RULES = [("deny", 23), ("allow", 22), ("allow", 443)]
def decide(port):
# TODO: return the first matching rule's action, else the default
return "allow"
print([decide(p) for p in [22, 23, 80, 443]])['allow', 'allow', 'allow', 'allow']
Show solution
def decide(port):
for action, rule_port in RULES:
if rule_port == port:
return action
return "deny"3. Download integrity check
Write verify_download(data, expected_hex) that hashes data with SHA-256 and compares it with the published hex digest. Accept upper- or lower-case hex, and compare with hmac.compare_digest.
Expected: True False.
import hashlib
import hmac
def verify_download(data, expected_hex):
# TODO: hash data and compare with expected_hex (case-insensitive)
return None
published = hashlib.sha256(b"tool-v1.0").hexdigest().upper()
print(verify_download(b"tool-v1.0", published), verify_download(b"tool-v1.1", published))None None
Show solution
def verify_download(data, expected_hex):
actual = hashlib.sha256(data).hexdigest()
return hmac.compare_digest(actual, expected_hex.lower())4. Signed messages with HMAC
Complete sign (HMAC-SHA256 hex digest with KEY) and verify (constant-time comparison). A message whose role was changed must fail.
Expected: 32da065afa1b58cc True False.
import hashlib
import hmac
KEY = b"exercise-key"
def sign(msg):
# TODO: return the HMAC-SHA256 hex digest of msg
return "0" * 64
def verify(msg, tag):
# TODO: compare sign(msg) with tag in constant time
return False
tag = sign(b"user=ana&role=user")
print(tag[:16], verify(b"user=ana&role=user", tag), verify(b"user=ana&role=admin", tag))0000000000000000 False False
Show solution
def sign(msg):
return hmac.new(KEY, msg, hashlib.sha256).hexdigest()
def verify(msg, tag):
return hmac.compare_digest(sign(msg), tag)5. Naive entropy estimate
Write entropy(pw) that estimates bits as len(pw) × log2(pool), where the pool adds 26 if there's a lowercase letter, 26 for uppercase, 10 for digits and 33 for anything else (symbols, spaces). Round to 1 decimal; return 0.0 for an empty password.
Expected: abc 14.1, Tr0ub4dor&3 72.3, correct horse battery staple 164.7.
Then think about it: why does this formula overrate Tr0ub4dor&3? (Answer in the solution.)
import math
def entropy(pw):
pool = 0
# TODO: add 26 / 26 / 10 / 33 depending on which character classes appear
return round(len(pw) * math.log2(pool), 1) if pool else 0.0
for pw in ["abc", "Tr0ub4dor&3", "correct horse battery staple"]:
print(pw, entropy(pw))abc 0.0
Tr0ub4dor&3 0.0
correct horse battery staple 0.0
Show solution
def entropy(pw):
pool = 0
if any(c.islower() for c in pw): pool += 26
if any(c.isupper() for c in pw): pool += 26
if any(c.isdigit() for c in pw): pool += 10
if any(not c.isalnum() for c in pw): pool += 33
return round(len(pw) * math.log2(pool), 1) if pool else 0.0The formula assumes every character was chosen at random. Tr0ub4dor&3 is a dictionary word with predictable substitutions (o→0, a→4) and a common suffix, so guessing tools try it early; its real strength is far below 72 bits. The passphrase's estimate is also too high (it's four words, not 28 random characters), but four randomly chosen words still give about 52 bits. Estimates like this are only meaningful for randomly generated secrets.
6. Fix an injectable query
orders_for builds SQL with an f-string. Rewrite it with a parameter so the second call returns no rows.
Expected: [(1, 20.0), (3, 12.25)] then [].
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER, customer TEXT, total REAL)")
db.executemany("INSERT INTO orders VALUES (?, ?, ?)",
[(1, "ana", 20.0), (2, "ben", 35.5), (3, "ana", 12.25)])
def orders_for(customer):
# TODO: use a ? placeholder instead of the f-string
sql = f"SELECT id, total FROM orders WHERE customer = '{customer}' ORDER BY id"
return db.execute(sql).fetchall()
print(orders_for("ana"))
print(orders_for("ana' OR '1'='1"))[(1, 20.0), (3, 12.25)]
[(1, 20.0), (2, 35.5), (3, 12.25)]
Show solution
def orders_for(customer):
return db.execute(
"SELECT id, total FROM orders WHERE customer = ? ORDER BY id", (customer,)
).fetchall()7. Escape a comment
render_comment inserts the author and text into HTML. Make both safe with html.escape.
Expected: <div class="c"><b><i>eve</i></b>: nice "shop" & <script>x()</script></div>
import html
def render_comment(author, text):
# TODO: escape author and text
return f'<div class="c"><b>{author}</b>: {text}</div>'
print(render_comment("<i>eve</i>", 'nice "shop" & <script>x()</script>'))<div class="c"><b><i>eve</i></b>: nice "shop" & <script>x()</script></div>
Show solution
def render_comment(author, text):
return f'<div class="c"><b>{html.escape(author)}</b>: {html.escape(text)}</div>'8. Contain a file path
Write safe(name) that joins name to /var/data, normalises it, and returns the path as a string only if it is still inside /var/data; otherwise None.
Expected: ['/var/data/a.txt', '/var/data/sub/b.txt', None, None, None].
import posixpath
from pathlib import PurePosixPath
BASE = PurePosixPath("/var/data")
def safe(name):
# TODO: join, normpath, then check BASE is one of the parents
return posixpath.join(str(BASE), name)
print([safe(n) for n in ["a.txt", "sub/b.txt", "../etc/shadow", "/etc/shadow", "sub/../../x"]])['/var/data/a.txt', '/var/data/sub/b.txt', '/var/data/../etc/shadow', '/etc/shadow', '/var/data/sub/../../x']
Show solution
def safe(name):
p = PurePosixPath(posixpath.normpath(posixpath.join(str(BASE), name)))
return str(p) if BASE in p.parents else NoneThe starter's output shows exactly why the check is needed: an absolute name replaces the base completely, and .. segments climb out of it.
9. Count failed logins
Count FAIL lines per IP address, then list the IPs with 3 or more failures.
Expected: {'203.0.113.9': 4, '192.0.2.1': 1} then ['203.0.113.9'].
LOG = """\
FAIL 203.0.113.9 root
FAIL 203.0.113.9 admin
OK 198.51.100.4 ana
FAIL 203.0.113.9 root
FAIL 192.0.2.1 ben
FAIL 203.0.113.9 test
OK 192.0.2.1 ben"""
counts = {}
for line in LOG.splitlines():
status, ip, user = line.split()
# TODO: count failures per ip
print(counts)
print([]) # TODO: IPs with 3 or more failures{}
[]
Show solution
counts = {}
for line in LOG.splitlines():
status, ip, user = line.split()
if status == "FAIL":
counts[ip] = counts.get(ip, 0) + 1
print(counts)
print([ip for ip, n in counts.items() if n >= 3])Go further: Every course in the Cybersecurity track ends with its own exercises; Security Foundations Exercises is the place to continue.
Test yourself
In exercise 8, why does posixpath.join("/var/data", "/etc/shadow") give /etc/shadow?
- It's a bug in Python
- An absolute second argument replaces everything before it
- normpath removed /var/data
- Because shadow is a system file
In exercise 3, why lower-case the expected digest before comparing?
- SHA-256 only works on lower case
- Hex digits can be published in either case;
hexdigest()returns lower case - To make it constant time
- It's not needed