Projects 5-6: A Tested Security Tool and a Secure File Vault
Not every security project is an assessment. Much of the field's work is building: the parser that turns logs into alerts, the scanner that checks a configuration, the component that stores a secret correctly. Building projects show something assessments can't: that you can write code that is correct, tested and safe under hostile input. Project 5 is a security tool in Python with a real test suite; project 6 is a small encrypted file vault, where the hard part is not the encryption call but everything around it.
Project 5: a security tool in Python, with tests
Goal. Write one small, useful security tool, as a proper package with a command-line interface, a test suite that includes hostile input, and documentation. Examples: an SSH or web log analyser that reports brute force, a certificate-expiry checker for a list of lab hosts, a configuration checker for sshd_config or Docker Compose files, a file-integrity monitor.
Builds on. Programming for Security: tool design, regex for logs, argparse CLIs, testing, and its toolbox projects (log analyser, TLS inspector, config checker), which are smaller starting points.
Scope. The tool runs on your own files and lab hosts; any network feature takes an explicit target list and defaults to 127.0.0.1.
The test suite is the difference between a script and a tool. Here is the core of an SSH log analyser with four tests. One of them, the "odd input" test, feeds it lines no honest log contains, and it finds a bug:
import io, re, unittest
from collections import Counter
FAIL = re.compile(r"sshd\[\d+\]: Failed password for (?:invalid user )?(?P<user>\S+) "
r"from (?P<ip>\d{1,3}(?:\.\d{1,3}){3}) port \d+")
def failures_by_source(lines, threshold=3):
"""Count failed SSH logins per source address; return those at or above the threshold."""
counts = Counter(m["ip"] for line in lines if (m := FAIL.search(line)))
return {ip: n for ip, n in counts.most_common() if n >= threshold}
class FailuresBySource(unittest.TestCase):
LOG = [
"Jan 15 10:00:01 web01 sshd[901]: Failed password for admin from 10.10.0.66 port 50122 ssh2",
"Jan 15 10:00:03 web01 sshd[901]: Failed password for invalid user oracle from 10.10.0.66 port 50124 ssh2",
"Jan 15 10:00:05 web01 sshd[902]: Failed password for root from 10.10.0.66 port 50126 ssh2",
"Jan 15 10:01:00 web01 sshd[910]: Failed password for alice from 10.10.0.21 port 40001 ssh2",
"Jan 15 10:01:09 web01 sshd[910]: Accepted password for alice from 10.10.0.21 port 40001 ssh2",
]
def test_counts_and_threshold(self):
self.assertEqual(failures_by_source(self.LOG), {"10.10.0.66": 3})
def test_invalid_user_lines_count(self):
self.assertEqual(failures_by_source(self.LOG[1:2], threshold=1), {"10.10.0.66": 1})
def test_success_is_not_a_failure(self):
self.assertEqual(failures_by_source(self.LOG[4:], threshold=1), {})
def test_odd_input_gives_nothing(self):
weird = ["", "\x00" * 50, "sshd[1]: Failed password for x from 999.1.1.1 port 1", "A" * 100_000]
self.assertEqual(failures_by_source(weird, threshold=1), {})
stream = io.StringIO()
result = unittest.TextTestRunner(stream=stream, verbosity=0).run(
unittest.defaultTestLoader.loadTestsFromTestCase(FailuresBySource))
print(f"tests run: {result.testsRun}, failures: {len(result.failures)}, errors: {len(result.errors)}")
for test, trace in result.failures + result.errors:
print("FAILED", test.id().split(".")[-1])
print(next(l for l in trace.splitlines() if l.startswith("AssertionError")))tests run: 4, failures: 1, errors: 0
FAILED test_odd_input_gives_nothing
AssertionError: {'999.1.1.1': 1} != {}
The regex accepts 999.1.1.1 because \d{1,3} matches any one to three digits. In a log analyser that becomes a real problem the moment an attacker controls part of a log line (a user name, a header): forged lines with impossible addresses would show up in reports and blocklists. The fix is to validate what the regex extracts, for example with ipaddress.ip_address(m["ip"]) inside a try, skipping lines that fail; the retest is the same suite passing 4 of 4. Writing the hostile test before the fix is the habit this project trains.
Deliverables. A repository with the package, a CLI with --help, tests (unit tests plus at least three hostile-input tests: empty, binary, enormous, malformed), a README with usage, limits and a threat model of the tool itself (what if its input is attacker-controlled?), and a short write-up of the bugs the tests found.
Rubric specifics. Technical work 3: tests cover the normal cases, the edge cases and hostile input, and run in CI. Detection here means the tool's own output: its findings are actionable (what, where, why, what to do). Fix and retest: every bug found by a test is fixed with that test kept as a regression test.
Stretch goal. Fuzz the parser with random and mutated log lines (the fuzzing project shows how) and add every crash or wrong result as a test.
Project 6: a secure file vault
Goal. Build a command-line tool that encrypts a file under a passphrase so that a wrong passphrase, any modification and any downgrade of the parameters are detected, and document every design decision.
Builds on. Applied Cryptography: AEAD, nonce reuse, password hashing, KDFs and peppers, key management, common mistakes.
Scope. Your own files, lab-only passphrases. The project uses a vetted library (cryptography) for every primitive; it designs the format, never a cipher.
The format is the project. This one stores a magic value, a version, the scrypt cost parameters, a 16-byte salt and a 12-byte nonce in a 39-byte header, then the AES-256-GCM ciphertext and tag. The header is passed as associated data, so it is authenticated too. The salt and nonce are fixed below only so that the output is stable; the real tool draws them from os.urandom for every file.
import struct
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.exceptions import InvalidTag
MAGIC, VERSION = b"TADV", 1
N, R, P = 2**14, 8, 1 # scrypt cost; kept in the header so it can be raised later
def derive(password, salt, n=N, r=R, p=P):
return Scrypt(salt=salt, length=32, n=n, r=r, p=p).derive(password.encode())
def seal(password, plaintext, salt, nonce):
header = MAGIC + struct.pack(">BIBB", VERSION, N, R, P) + salt + nonce
return header + AESGCM(derive(password, salt)).encrypt(nonce, plaintext, header)
def open_vault(password, blob):
if blob[:4] != MAGIC:
raise ValueError("not a vault file")
version, n, r, p = struct.unpack(">BIBB", blob[4:11])
if version != VERSION or n < 2**14:
raise ValueError("unsupported version or parameters too weak")
salt, nonce, body = blob[11:27], blob[27:39], blob[39:]
try:
return AESGCM(derive(password, salt, n, r, p)).decrypt(nonce, body, blob[:39])
except InvalidTag:
raise ValueError("wrong password or file modified") from None
# Fixed salt and nonce so the output is stable; real code uses os.urandom(16) and os.urandom(12)
SALT, NONCE = bytes(range(16)), bytes(12)
blob = seal("lab-only passphrase", b"lab notes: srv01 root is lab-root-pw", SALT, NONCE)
print(f"vault file: {len(blob)} bytes = 39 header + 36 ciphertext + 16 tag")
print("open, right password:", open_vault("lab-only passphrase", blob).decode())
for label, password, data in [
("wrong password", "lab-only passphrase!", blob),
("one ciphertext bit flipped", "lab-only passphrase", blob[:50] + bytes([blob[50] ^ 1]) + blob[51:]),
("header changed to n = 2^15", "lab-only passphrase", blob[:5] + struct.pack(">I", 2**15) + blob[9:]),
("downgraded to n = 2^10", "lab-only passphrase", blob[:5] + struct.pack(">I", 2**10) + blob[9:]),
]:
try:
open_vault(password, data)
print(f"{label:28} opened (BAD)")
except ValueError as e:
print(f"{label:28} refused: {e}")vault file: 91 bytes = 39 header + 36 ciphertext + 16 tag
open, right password: lab notes: srv01 root is lab-root-pw
wrong password refused: wrong password or file modified
one ciphertext bit flipped refused: wrong password or file modified
header changed to n = 2^15 refused: wrong password or file modified
downgraded to n = 2^10 refused: unsupported version or parameters too weak
Every attack on the file is refused, and for the right reason. A wrong passphrase gives a different key, so the GCM tag fails. A flipped ciphertext bit fails the tag. Raising the cost parameter in the header also fails the tag: a different scrypt cost gives a different key, and the header itself is authenticated. Lowering the cost is caught before any decryption by a minimum-parameter check, so an attacker cannot trick the tool into deriving a weak key on purpose. Note that wrong passphrase and modification give the same error message: telling them apart would help an attacker.
The cost parameters here are kept low so the example runs quickly in a browser. OWASP's Password Storage Cheat Sheet gives N = 2^17 (128 MiB), r = 8, p = 1 as its minimum scrypt configuration (or equivalent trade-offs such as N = 2^16 with p = 2), and prefers Argon2id where it is available. A vault derives one key per open, so it can afford at least that: in the real tool, set both N and the minimum that open_vault accepts to 2^17 or more.
Deliverables. The tool; a format specification (every byte of the header and why it is there); a design document with the threat model (lost laptop, modified file, guessed passphrase) and what is not protected (a keylogger on your machine, a weak passphrase); tests for each refused case above plus truncated files and empty input; the password-cost reasoning for the chosen scrypt parameters.
Rubric specifics. Technical work 3: random salt and nonce per file, authenticated header, constant error messages, parameters stored and checked. Detection: tampering, truncation and downgrade are detected and tested. Any homemade primitive (your own XOR, your own MAC) scores 0 on technical work.
Stretch goal. Support passphrase changes without re-encrypting the data (wrap a random data key under the passphrase-derived key, the envelope pattern), or switch the KDF to Argon2id with argon2-cffi and keep reading old version-1 files.
Pitfalls
- Tests only for the happy path. The bugs that matter live in the input nobody expects.
- Nonce reuse. A fixed nonce, as in the demonstration, is safe only because the demonstration encrypts one message; in the tool it would break GCM completely (nonce reuse).
- Unauthenticated parameters. If the header were not associated data, an attacker could change it without detection.
Practice
1. Fix the log analyser so that all four tests pass.
Import ipaddress and count only valid addresses: replace the Counter(...) line with a loop that does m = FAIL.search(line), then try: ipaddress.ip_address(m["ip"]), except ValueError: continue, then counts[m["ip"]] += 1. The output becomes tests run: 4, failures: 0, errors: 0.
2. Why does the vault check n < 2**14 before decrypting, when a changed header fails the GCM tag anyway?
An attacker who replaces the whole file can build a valid file with weak parameters and a passphrase they chose; the tag would verify. The minimum check keeps the tool from ever producing or accepting weakly protected files (in the real tool, with a minimum of at least OWASP's 2^17 rather than the demonstration's 2^14). It also refuses a downgraded header before spending any work on it.
Test yourself
What bug did the hostile-input test find in the log analyser?
- It crashed on empty lines
- It accepted impossible addresses such as 999.1.1.1
- It counted successful logins
- It was too slow
Why is the vault's header passed to AES-GCM as associated data?
- To compress it
- So that any change to the header, such as the cost parameters, fails the authentication tag
- To encrypt it
- Because GCM requires a header
Why do 'wrong password' and 'file modified' give the same error message?
- Laziness
- Distinguishing them would tell an attacker which of the two happened
- GCM cannot tell them apart, and the tool shouldn't try
- Both of the previous two