Skip to content
KALANBLON
Show contents

Chapter 5 of 6 · 25 min

Project: the cryptographic audit of an online tontine

By the end of this chapter, you'll be able to

  • Inventory an application's uses of cryptography
  • Link each bad choice to its risk, severity and fix
  • Write an automatic rule-based auditor
  • Produce a prioritised report the team can understand

The audit method

The team fixes things in order; the audit is redone after the fixes.

Step 5 of 5
Text description of the animation
  1. We read the code and configuration, and note every place where the app encrypts, hashes, signs or generates a secret.
  2. Each rule encodes a known mistake, with a checkable condition.
  3. Severity combines ease of exploitation and impact.
  4. A precise fix, with the standard algorithm and parameters to use.
  5. The team fixes things in order; the audit is redone after the fixes.

Here is the inventory the team gave you, as data. Each entry describes a use of cryptography in the app.

inventory = [
    {"use": "members' passwords", "algo": "md5", "salt": False},
    {"use": "reset tokens", "generator": "random", "bytes": 8},
    {"use": "stored identity documents", "algo": "aes-128", "mode": "ecb"},
    {"use": "encrypted backups", "algo": "aes-256", "mode": "gcm", "nonce": "fixed"},
    {"use": "Mobile Money notifications", "algo": "hmac-sha256", "comparison": "=="},
    {"use": "receipt signatures", "algo": "rsa", "bits": 1024, "padding": "none"},
    {"use": "bank API call", "tls": True, "checks_name": False},
    {"use": "app key exchange", "algo": "x25519", "pq_hybrid": False, "secret_years": 10},
]

A rule-based auditor links each known mistake to a condition, a severity, the risk and the fix. Let's start with three rules:

inventory = [
    {"use": "members' passwords", "algo": "md5", "salt": False},
    {"use": "reset tokens", "generator": "random", "bytes": 8},
    {"use": "stored identity documents", "algo": "aes-128", "mode": "ecb"},
]

RULES = [
    (lambda u: u.get("algo") in ("md5", "sha1", "sha256") and "passwords" in u["use"],
     "critical", "fast password hashing: billions of guesses per second",
     "Argon2id (or scrypt) with a unique salt per account"),
    (lambda u: u.get("generator") == "random",
     "critical", "secret generated with a predictable generator",
     "secrets.token_urlsafe(32)"),
    (lambda u: u.get("mode") == "ecb",
     "high", "ECB mode: patterns in the data remain visible",
     "AES-256-GCM with a unique nonce per file"),
]

for u in inventory:
    for condition, severity, risk, fix in RULES:
        if condition(u):
            print(f"[{severity}] {u['use']}: {risk}\n           → {fix}")
[critical] members' passwords: fast password hashing: billions of guesses per second
           → Argon2id (or scrypt) with a unique salt per account
[critical] reset tokens: secret generated with a predictable generator
           → secrets.token_urlsafe(32)
[high] stored identity documents: ECB mode: patterns in the data remain visible
           → AES-256-GCM with a unique nonce per file

Each rule is data: rules can be added, tested one by one, and the auditor can be reused on another project. Real static security analysis tools (such as Semgrep or Bandit for Python) work on the same principle, applied directly to source code.

Mini-lab: your first rulePython 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

Project: the complete audit report

Complete the auditor so that it covers the eight entries of the inventory. Add the missing rules:

  • fixed nonce (critical);
  • tag comparison with == (high);
  • RSA shorter than 2,048 bits or without padding (high);
  • TLS without name checking (critical);
  • non-hybrid key exchange for secrets kept more than 5 years (medium).

The report must be sorted by severity (critical, then high, then medium), numbered, and end with a summary of the number of findings per severity.

Hint 1
Give each severity a rank: ORDER = {"critical": 0, "high": 1, "medium": 2}, collect the findings in a list, then sort with sorted(findings, key=lambda f: ORDER[f[0]]).
Hint 2
For the summary, collections.Counter(f[0] for f in findings) counts the findings per severity.
Show the solution and common mistakes
from collections import Counter

inventory = [
    {"use": "members' passwords", "algo": "md5", "salt": False},
    {"use": "reset tokens", "generator": "random", "bytes": 8},
    {"use": "stored identity documents", "algo": "aes-128", "mode": "ecb"},
    {"use": "encrypted backups", "algo": "aes-256", "mode": "gcm", "nonce": "fixed"},
    {"use": "Mobile Money notifications", "algo": "hmac-sha256", "comparison": "=="},
    {"use": "receipt signatures", "algo": "rsa", "bits": 1024, "padding": "none"},
    {"use": "bank API call", "tls": True, "checks_name": False},
    {"use": "app key exchange", "algo": "x25519", "pq_hybrid": False, "secret_years": 10},
]

RULES = [
    (lambda u: u.get("algo") in ("md5", "sha1", "sha256") and "passwords" in u["use"],
     "critical", "fast password hashing", "Argon2id with a unique salt per account"),
    (lambda u: u.get("generator") == "random",
     "critical", "secret generated with a predictable generator", "secrets.token_urlsafe(32)"),
    (lambda u: u.get("nonce") == "fixed",
     "critical", "reused nonce: backups can be decrypted by XOR", "random 96-bit nonce per backup"),
    (lambda u: u.get("tls") and not u.get("checks_name", True),
     "critical", "certificate not checked: man in the middle possible", "ssl.create_default_context(), no exceptions"),
    (lambda u: u.get("mode") == "ecb",
     "high", "ECB mode: visible patterns", "AES-256-GCM with a unique nonce"),
    (lambda u: u.get("comparison") == "==",
     "high", "non-constant tag comparison", "hmac.compare_digest"),
    (lambda u: u.get("algo") == "rsa" and (u.get("bits", 0) < 2048 or u.get("padding") == "none"),
     "high", "RSA too short or without padding", "Ed25519, or RSA-3072 with PSS"),
    (lambda u: u.get("pq_hybrid") is False and u.get("secret_years", 0) > 5,
     "medium", "key exchange exposed to \"harvest now, decrypt later\"", "hybrid X25519 + ML-KEM-768"),
]
ORDER = {"critical": 0, "high": 1, "medium": 2}

findings = [(severity, u["use"], risk, fix)
            for u in inventory
            for condition, severity, risk, fix in RULES if condition(u)]

print("CRYPTOGRAPHIC AUDIT REPORT — Online Tontine\n")
for i, (severity, use, risk, fix) in enumerate(sorted(findings, key=lambda f: ORDER[f[0]]), 1):
    print(f"{i}. [{severity.upper()}] {use}")
    print(f"   risk: {risk}")
    print(f"   fix : {fix}")
count = Counter(f[0] for f in findings)
print("\nSummary:", ", ".join(f"{count[s]} {s}" for s in ORDER))
CRYPTOGRAPHIC AUDIT REPORT — Online Tontine

1. [CRITICAL] members' passwords
   risk: fast password hashing
   fix : Argon2id with a unique salt per account
2. [CRITICAL] reset tokens
   risk: secret generated with a predictable generator
   fix : secrets.token_urlsafe(32)
3. [CRITICAL] encrypted backups
   risk: reused nonce: backups can be decrypted by XOR
   fix : random 96-bit nonce per backup
4. [CRITICAL] bank API call
   risk: certificate not checked: man in the middle possible
   fix : ssl.create_default_context(), no exceptions
5. [HIGH] stored identity documents
   risk: ECB mode: visible patterns
   fix : AES-256-GCM with a unique nonce
6. [HIGH] Mobile Money notifications
   risk: non-constant tag comparison
   fix : hmac.compare_digest
7. [HIGH] receipt signatures
   risk: RSA too short or without padding
   fix : Ed25519, or RSA-3072 with PSS
8. [MEDIUM] app key exchange
   risk: key exchange exposed to "harvest now, decrypt later"
   fix : hybrid X25519 + ML-KEM-768

Summary: 4 critical, 3 high, 1 medium

sorted is stable: at equal severity, findings keep the inventory's order. The report fits on one page, each line says what to do, and the critical points come first. A real engagement would add evidence (code excerpts, exploitation demo on a test environment), the date, the audited version and a verification plan after the fixes.

Common mistakes:

  • Reporting a problem without a precise fix ("improve encryption security"): the team does not know what to do.
  • Putting every severity at the same level: a report where everything is critical does not help prioritise.
  • Writing conditions that raise an error on incomplete entries: u["bits"] instead of u.get("bits", 0) crashes as soon as an entry is not an RSA key.

Summary

  1. 1A cryptographic audit starts with an inventory of every use: algorithm, mode, parameters, generator.
  2. 2Each known mistake becomes a rule with a condition, a severity, a risk and a precise fix.
  3. 3Stacking fast hashes does not protect passwords: Argon2id with a salt is needed.
  4. 4The report is sorted by severity, each point says what to do, and the audit is redone after the fixes.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.