Oracle Examples
These examples implement the two oracle interfaces. Copy an
example into your project’s oracles/ directory, edit the marked constants,
and pass its path to the brute-force or N-sweep command.
generic_aes_gcm.py — stateless AES-GCM
1"""Stateless AES-GCM oracle boilerplate.
2
3Copy this file, edit the three module-level constants, point
4``memdiver brute-force --oracle generic_aes_gcm.py`` at it.
5
6The verification strategy: AEAD-decrypt a known ciphertext with the
7candidate as the key. A matching tag verifies the candidate against that sample.
8Wrong-length candidates are rejected in O(1).
9"""
10
11from cryptography.hazmat.primitives.ciphers.aead import AESGCM
12
13KEY_LENGTH = 32
14NONCE = bytes.fromhex("00" * 12)
15CIPHERTEXT_WITH_TAG = bytes.fromhex(
16 "aabbccddeeff00112233445566778899"
17 "aabbccddeeff0011"
18)
19ASSOCIATED_DATA: bytes | None = None
20
21
22def verify(candidate: bytes) -> bool:
23 if len(candidate) != KEY_LENGTH:
24 return False
25 try:
26 AESGCM(candidate).decrypt(NONCE, CIPHERTEXT_WITH_TAG, ASSOCIATED_DATA)
27 return True
28 except Exception:
29 return False
gocryptfs.py — stateful factory, HKDF-SHA256 + per-block AEAD
1"""Gocryptfs master-key oracle.
2
3A candidate is treated as the 32-byte **unwrapped** master key (already
4resident in process memory — scrypt is irrelevant on the hot path).
5Verification derives the per-instance content key and AEAD-decrypts the
6first block of a real ciphertext file from the vault.
7
8gocryptfs v2 on-disk format (per file):
9
10 file_header = version(2 big-endian) || file_id(16)
11 block_0 = nonce(16) || ciphertext(4096) || gcm_tag(16)
12 block_1 = nonce(16) || ciphertext(4096) || gcm_tag(16)
13 ...
14
15Content key:
16
17 content_key = HKDF-SHA256(master_key,
18 info="AES-GCM file content encryption",
19 length=32)
20
21Per-block AEAD:
22
23 AES-256-GCM( key = content_key,
24 nonce = block.nonce,
25 ct+tag = block.ciphertext || block.gcm_tag,
26 aad = block_num (8 big-endian) || file_id (16) )
27
28A successful tag check means the derived key authenticates block 0.
29The function returns False when the library raises ``InvalidTag``. ~150 µs per candidate on CPython, no filesystem mount.
30
31Requires ``pip install cryptography``.
32
33Driven by a TOML config passed via ``--oracle-config``:
34
35 # gocryptfs_oracle.toml
36 sample_ciphertext = "/path/to/vault/<encrypted_file>"
37
38The ``sample_ciphertext`` path must point at any file encrypted by the
39target gocryptfs instance. Its header_id is read directly from the
40first 18 bytes.
41"""
42
43from pathlib import Path
44
45from cryptography.hazmat.primitives import hashes
46from cryptography.hazmat.primitives.ciphers.aead import AESGCM
47from cryptography.hazmat.primitives.kdf.hkdf import HKDF
48
49MASTER_KEY_LENGTH = 32
50HEADER_VERSION_LENGTH = 2
51HEADER_ID_LENGTH = 16
52NONCE_LENGTH = 16
53GCM_TAG_LENGTH = 16
54CONTENT_KEY_INFO = b"AES-GCM file content encryption"
55
56
57def build_oracle(config: dict) -> "GocryptfsOracle":
58 return GocryptfsOracle(config)
59
60
61class GocryptfsOracle:
62 def __init__(self, config: dict):
63 sample = Path(config["sample_ciphertext"]).read_bytes()
64 min_size = (
65 HEADER_VERSION_LENGTH + HEADER_ID_LENGTH
66 + NONCE_LENGTH + GCM_TAG_LENGTH
67 )
68 if len(sample) < min_size:
69 raise ValueError(
70 f"sample ciphertext too short ({len(sample)} < {min_size})"
71 )
72 self.header_id = sample[
73 HEADER_VERSION_LENGTH : HEADER_VERSION_LENGTH + HEADER_ID_LENGTH
74 ]
75 body = sample[HEADER_VERSION_LENGTH + HEADER_ID_LENGTH :]
76 self.nonce = body[:NONCE_LENGTH]
77 self.ct_and_tag = body[NONCE_LENGTH:]
78 # Block 0 AAD = block_num(8 BE) || file_header_id(16)
79 self.aad = (0).to_bytes(8, "big") + self.header_id
80
81 def verify(self, candidate: bytes) -> bool:
82 if len(candidate) != MASTER_KEY_LENGTH:
83 return False
84 try:
85 content_key = HKDF(
86 algorithm=hashes.SHA256(),
87 length=MASTER_KEY_LENGTH,
88 salt=None,
89 info=CONTENT_KEY_INFO,
90 ).derive(candidate)
91 AESGCM(content_key).decrypt(self.nonce, self.ct_and_tag, self.aad)
92 return True
93 except Exception:
94 return False
tls13_stub.py — TLS 1.3 traffic-secret verification scaffold
1"""TLS 1.3 traffic-secret oracle — fill in the key schedule.
2
3This scaffold treats each candidate as a 32- or 48-byte traffic secret.
4The record check requires ``_derive_keys``, which is a placeholder.
5Once the key derivation is implemented, the tag check can verify a
6candidate against a captured record. Point it at
7RFC 8446 §7.1 once you know the AEAD your target uses.
8
9Driven by TOML:
10
11 # tls13_oracle.toml
12 encrypted_record = "/path/to/record0.bin" # full TLS record body
13 record_nonce_hex = "001122334455" # explicit nonce bytes
14 aead = "AES-128-GCM" # or "AES-256-GCM"
15 hash_algo = "SHA-256" # or "SHA-384"
16"""
17
18from pathlib import Path
19
20from cryptography.hazmat.primitives.ciphers.aead import AESGCM
21
22SHA256_LENGTH = 32
23SHA384_LENGTH = 48
24
25
26def build_oracle(config: dict) -> "Tls13Oracle":
27 return Tls13Oracle(config)
28
29
30class Tls13Oracle:
31 def __init__(self, config: dict):
32 self.record = Path(config["encrypted_record"]).read_bytes()
33 self.nonce = bytes.fromhex(config["record_nonce_hex"])
34 self.aead_name = config.get("aead", "AES-128-GCM")
35 self.hash_name = config.get("hash_algo", "SHA-256")
36 self.expected_length = (
37 SHA256_LENGTH if self.hash_name == "SHA-256" else SHA384_LENGTH
38 )
39
40 def _derive_keys(self, traffic_secret: bytes) -> bytes:
41 """Return the AEAD key derived from a TLS 1.3 traffic secret.
42
43 TODO: implement per RFC 8446 §7.1 using HKDF-Expand-Label with
44 the label "tls13 key". Return the AEAD key bytes (16 for
45 AES-128-GCM, 32 for AES-256-GCM).
46 """
47 raise NotImplementedError("fill in TLS 1.3 HKDF-Expand-Label here")
48
49 def verify(self, candidate: bytes) -> bool:
50 if len(candidate) != self.expected_length:
51 return False
52 try:
53 key = self._derive_keys(candidate)
54 AESGCM(key).decrypt(self.nonce, self.record, None)
55 return True
56 except Exception:
57 return False
Using the examples from the web UI
The pipeline wizard’s Oracle stage lists every *.py in docs/oracle/examples/
(files starting with _ are skipped) through GET /api/oracles/examples. Each
entry carries the file’s sha256, detected shape, a one-line summary and its
first lines, plus — when a sibling <name>.toml exists — a config_template the
UI prefills its config form from and config_placeholders naming the template
keys that are questions rather than answers.
Picking an example calls POST /api/oracles/examples/{filename}/load, which
copies the file into the enabled oracle directory and registers it through the
same path as an upload (mode 0o600, __pycache__ purge, sandboxed load
probe, shape detection) — shipping a file in the repo is not a trust decision.
It needs an enabled oracle directory, like an upload; see
Running oracles from the web UI.
Config auto-fill ([memdiver] table)
An example’s .toml may contain a reserved [memdiver] table. It is MemDiver’s
own automation metadata: it is stripped before the config reaches
build_oracle(), so an oracle never sees it. gocryptfs.toml uses it like this:
[memdiver]
requires_cipher = "aes"
[memdiver.autofill.sample_ciphertext]
strategy = "vault_content_file"
exclude = ["gocryptfs.conf", "gocryptfs.diriv"]
POST /api/oracles/examples/{filename}/suggest-config (body
{"source_paths": [...]}, the dumps already selected in the wizard) turns that
into a suggestion (app/oracle_autoconfig.py):
Only the first selected dump matters — it is the reference the sweep verifies against. Its run’s
meta.json(core/dataset_metadata.py) is looked up; a selection spanning several runs adds a warning.vault_content_file(the only strategy implemented) fills the key with the encrypted file in the run’s declaredvault_cipher_dir, skipping theexcludenames. It fills only when exactly one candidate file remains; otherwise the field stays empty and a warning names the directory.If the run’s
cipherdoes not matchrequires_cipher(for gocryptfs: anxchacharun against the AES-only oracle), nothing is prefilled andblocked_reasonsays why, because such a run could never produce a hit.A dump outside any corpus is a 200 with an empty
config— fill the field by hand. Only an unknown example filename is an error (404).