Programming for Security Exercises
Eighteen exercises across the whole course. Most can be done on paper or in a few lines of code; try each one before opening the answer. The program at the end checks the numeric answers, and you can edit it to test your own.
| # | Exercise | Practises |
|---|---|---|
| 1 | Pick the language | Introduction |
| 2 | Exit codes and streams | Designing a Small Security Tool |
| 3 | Decode the layers | Bytes, Encodings, Hex and Base64 |
| 4 | A length that lies | Binary Formats with struct |
| 5 | Anchor the pattern | Regular Expressions for Log Parsing |
| 6 | Hash, MAC or token? | hashlib, hmac and secrets |
| 7 | Buckets and windows | pandas for Log Analysis |
| 8 | Fix the wrapper | Running Commands Safely, argparse |
| 9 | Boundary tests | Writing Testable Security Tools |
| 10 | Quote it | Safe Bash, Pipelines |
| 11 | Objects, not text | PowerShell Objects, Event Exports |
| 12 | Review the C | C Buffers, C Integers |
| 13 | Signed or unsigned jump | Reading Compiler Output |
| 14 | Find the sinks | DOM Sinks, SQL |
| 15 | What safety buys | Go and Rust |
| 16 | Open, closed, filtered | TCP Checker, Packet Analyser, HTTP Proxy |
| 17 | Bits and guesses | Password-Strength Estimator |
| 18 | Read the configuration the program's way | Log Analyser, File Integrity, TLS Inspector, Config Checker |
Exercise 1: Pick the language
Which language would you reach for first, and why: (a) count failed SSH logins per address on a Linux server during an incident; (b) list the local administrators on 200 Windows machines; (c) review a patch to a network daemon's packet parser; (d) parse 5 GB of JSON proxy logs and plot requests per hour; (e) write a new, long-lived agent that parses untrusted network input.
Answer
(a) Bash (grep/awk pipeline): already installed, fast to write. (b) PowerShell (objects from remote sessions or AD). (c) C (the daemon's language): read lengths, bounds and integer types. (d) Python with pandas (or a SIEM). (e) Rust or Go: memory-safe, single binary.
Exercise 2: Exit codes and streams
A checker prints ERROR: cannot read /var/log/auth.log to stdout and exits 0. A cron job pipes its output to grep FINDING and mails results only when there are any. What goes wrong, and what are the three fixes?
Answer
The error line contains no FINDING, so grep drops it, nobody is mailed, and the exit status 0 says "clean": a monitoring blind spot. Fix: errors to stderr, exit 2 when the tool can't do its job, and have the cron wrapper alert on non-zero status (and on stderr output).
Exercise 3: Decode the layers
A web log contains GET /files?name=%252e%252e%252fetc%252fpasswd. Decode it once and twice. Which check would a filter that decodes once and looks for ../ miss, and what is the fix?
Answer
Once: %2e%2e%2fetc%2fpasswd. Twice: ../etc/passwd. A single-decode filter sees no ../; if the application decodes twice, traversal happens. Fix: decode to a fixed point (or reject any % remaining after one decode), normalise the path, and check that it stays inside the allowed directory.
Exercise 4: A length that lies
A TLV record is 01 00 08 61 6c 69 63 65 (type 1, length 8, then alice). What does the safe parser report? What would a C parser that trusts the length do?
Answer
The header claims 8 bytes but only 5 remain: record type 1 claims 8 bytes, only 5 left. A C parser that copies length bytes would read 3 bytes past the end of the buffer: an out-of-bounds read, the Heartbleed pattern.
Exercise 5: Anchor the pattern
The pattern Failed password for (\S+) from (\S+) is used with re.search. Give a log line it handles wrongly, and fix the pattern.
Answer
Failed password for invalid user admin from 203.0.113.7 port 40024 ssh2 does not match at all: \S+ can't span invalid user admin, and invalid is not followed by from, so the failed login is silently dropped (a shorter pattern without from (\S+) would capture invalid as the user). Fix: Failed password for (?:invalid user )?(\S+) from (\S+) port \d+, and anchor the rest of the line so unexpected shapes are counted as unparsed.
Exercise 6: Hash, MAC or token?
Which primitive for each: (a) a download page's integrity check against corruption; (b) a webhook signature between two services that share a secret; (c) a password-reset link; (d) storing user passwords.
Answer
(a) SHA-256 hash (published separately, or a signature against tampering). (b) HMAC-SHA256 with hmac.compare_digest. (c) secrets.token_urlsafe(32), single-use, short expiry, stored hashed. (d) A slow, salted password hash: Argon2id, scrypt, bcrypt or PBKDF2.
Exercise 7: Buckets and windows
Failures from one source at 10:04:30, 10:04:40, 10:04:50, 10:05:00, 10:05:10, 10:05:20. The rule is "6 or more in 5 minutes". Does a fixed 5-minute bucket rule fire? Does a rolling 5-minute window?
Answer
Fixed buckets 10:00–10:05 and 10:05–10:10 get 3 each: no alert. The rolling window ending at 10:05:20 contains all 6: alert. This is why the course's detectors use sliding windows.
Exercise 8: Fix the wrapper
Rewrite safely: os.system("dig +short " + domain), where domain comes from a web form. Add the validation you would do.
Answer
subprocess.run(["dig", "+short", "-q", domain], capture_output=True, text=True, timeout=5) (dig does not accept -- and answers Invalid option: --; -q marks the next argument as the query name) after checking re.fullmatch(r"(?=.{1,253}$)([a-z0-9-]{1,63}\.)*[a-z0-9-]{1,63}", domain.lower()). Better still: use a DNS library, and only for resolvers and names you are allowed to query.
Exercise 9: Boundary tests
List the test inputs you would write for a rule "alert when a source has 5 or more failures within 60 seconds".
Answer
4 failures in 60 s (no alert), exactly 5 within 59 s (alert), 5 spread with first and last exactly 60 s apart (decide and document: the course's code says no alert), successes mixed in (not counted), two sources interleaved (independent), empty input, unsorted input (sort or reject), and a truncated line (counted as unparsed).
Exercise 10: Quote it
Find three bugs: for f in $(find /srv/upload -name *.pdf); do cp $f /archive/; done.
Answer
*.pdf unquoted may be expanded by the shell in the current directory before find sees it; $(find …) splits names with spaces and globs them; cp $f globs each piece again, and a piece that starts with - after splitting (from a name like x -r y.pdf) becomes an option. Safe: find /srv/upload -name '*.pdf' -exec cp -t /archive/ -- {} + (GNU cp; with + the {} must come last), or -exec cp -- {} /archive/ \; anywhere.
Exercise 11: Objects, not text
In PowerShell, list the SHA-256 and path of every .ps1 file under C:\Scripts whose hash is not in a baseline JSON file baseline.json (an array of objects with Path and SHA256).
Answer
$base = Get-Content baseline.json -Raw | ConvertFrom-Json
$now = Get-ChildItem C:\Scripts -Recurse -Filter *.ps1 | Get-FileHash -Algorithm SHA256 |
Select-Object Path, @{n='SHA256'; e={$_.Hash}}
Compare-Object $base $now -Property Path, SHA256 | Where-Object SideIndicator -eq '=>'Select-Object renames Hash to SHA256 so both sides have the same property names; => rows are new or changed files.
Exercise 12: Review the C
Find the bugs: uint16_t n = read_u16(pkt); char *buf = malloc(n); memcpy(buf, pkt + 2, n + 1); buf[n] = 0;
Answer
memcpy copies n + 1 bytes into n; buf[n] = 0 writes one past the end (off-by-one); malloc's result is not checked; and nothing checks that the packet actually has n + 2 bytes (out-of-bounds read). Fix: check pkt_len >= 2 + n, malloc(n + 1), check for NULL, memcpy(buf, pkt + 2, n), then buf[n] = 0.
Exercise 13: Signed or unsigned jump
After cmp eax, esi a function uses jl .ok. The source compares int i with int n. Is i = -5 accepted? What two source changes fix it?
Answer
Yes: jl is a signed comparison, and -5 < n. Either check i >= 0 && i < n, or make i and n unsigned (size_t), which compiles to jb/jae.
Exercise 14: Find the sinks
Which lines are injection sinks for untrusted x: (1) el.innerHTML = x; (2) el.textContent = x; (3) db.execute("SELECT * FROM t WHERE id = ?", (x,)); (4) db.execute(f"SELECT * FROM t ORDER BY {x}"); (5) new Function(x)(); (6) a.href = x.
Answer
Sinks: (1) HTML, (4) SQL (identifier: use an allowlist), (5) script, (6) URL (javascript:). Safe: (2) text, (3) parameterised value.
Exercise 15: What safety buys
Which of these can still happen in safe Rust: (a) reading past the end of a Vec; (b) a panic triggered by attacker input; (c) SQL injection; (d) a use-after-free; (e) u32 wraparound in a release build.
Answer
(b), (c) and (e). (a) panics instead of reading memory, and (d) is rejected by the borrow checker. Use .get(), checked_* and parameterised queries for the rest.
Exercise 16: Open, closed, filtered
A checker reports for 10.10.0.30: 22 filtered, 80 filtered, 443 open. A second run from another lab subnet reports 22 open. What do you conclude, and what should the report say?
Answer
A host firewall (or network ACL) drops traffic except 443 from the first subnet, and allows SSH from the second. The report states the source of each run, the time, and "filtered" as "no answer within N seconds", not "closed". Reachability is a property of a path, not only of a host.
Exercise 17: Bits and guesses
(a) Entropy of a random 14-character password over 62 symbols. (b) Entropy of 5 Diceware words. (c) The estimator's bits for Winter2024! (word list of 10,000, capital, year, one symbol). (d) Average time for (a) at 1e10 guesses per second.
Answer
(a) 14 × log2 62 ≈ 83.4 bits. (b) 5 × log2 7776 ≈ 64.6 bits. (c) 13.3 + 1 + 7.1 + 5.0 ≈ 26.5 bits. (d) 2^82.4 / 1e10 ≈ 6.2e14 s, about 20 million years. See the program below.
Exercise 18: Read the configuration the program's way
sshd_config contains, in order: Include /etc/ssh/sshd_config.d/*.conf, PasswordAuthentication no. The directory holds 10-a.conf with PasswordAuthentication yes and 20-b.conf with PasswordAuthentication no. What is the effective value, and which file should you change?
Answer
yes: the Include is read first, its files in sorted order, and 10-a.conf sets the keyword first. Change (or remove) 10-a.conf, or add a 00-hardening.conf that sets no, then confirm with sshd -T.
Checking the numbers
import math, struct
rec = bytes.fromhex("01 00 08 61 6c 69 63 65")
t, n = struct.unpack_from("!BH", rec)
print(f"4. record type {t} claims {n} bytes, only {len(rec) - 3} left")
print(f"17a. {14 * math.log2(62):.1f} bits")
print(f"17b. {5 * math.log2(7776):.1f} bits")
print(f"17c. {math.log2(10000) + 1 + math.log2(140) + math.log2(33):.1f} bits")
t = 2 ** (14 * math.log2(62) - 1) / 1e10
print(f"17d. {t:.2g} s = {t / 3.156e7 / 1e6:.0f} million years")
times = [4 * 60 + 30, 4 * 60 + 40, 4 * 60 + 50, 5 * 60, 5 * 60 + 10, 5 * 60 + 20]
fixed = [sum(1 for t in times if b <= t < b + 300) for b in (0, 300)]
rolling = max(sum(1 for u in times if 0 <= t - u < 300) for t in times)
print(f"7. fixed buckets {fixed}, rolling max {rolling}")4. record type 1 claims 8 bytes, only 5 left
17a. 83.4 bits
17b. 64.6 bits
17c. 26.5 bits
17d. 6.2e+14 s = 20 million years
7. fixed buckets [3, 3], rolling max 6
Practice problems for this course, with tests in 21 languages: Adler-32 Checksum, Base64 and Base64url Encoding, Password Entropy Estimate, Brute-Force Login Alerts.
Test yourself
A tool cannot read its input file. Which exit code should it return under the course's convention?
- 0
- 1
- 2
- It should print nothing and continue
Which line is NOT an injection sink for untrusted x?
el.innerHTML = xnew Function(x)()el.textContent = xdb.execute(f"... ORDER BY {x}")
Six failures between 10:04:30 and 10:05:20; rule 6 in 5 minutes. Which approach alerts?
- Fixed 5-minute buckets
- A rolling 5-minute window
- Both
- Neither