#!/usr/bin/env python3 """Generates DomiStream's crypto test vectors with tools that are independent of the RustCrypto crates DomiStream uses: Python's hashlib (SHA-256), the OpenSSL 3.x command line (RSA keys, X.509 certificates, PKCS#1 v1.5 SHA-256 signatures, AES-128-ECB without padding, AES-128-CBC with PKCS#7) and .NET's AesGcm (AES-128-GCM, gcm_vectors.cs). Everything written here is TEST-ONLY: the keys are made fresh on this machine for the tests, never a real host's or client's, and must never be used for anything else. Values follow docs/PROTOCOL.md (sections in the comments). python tools/vectors/gen_vectors.py # recompute vectors, keep the existing test keys python tools/vectors/gen_vectors.py --fresh-keys # also make new test keys and certificates Environment: DOMISTREAM_OPENSSL (path to openssl, default: Git for Windows' OpenSSL 3.5, then PATH) and DOMISTREAM_DOTNET (default: dotnet on PATH). Standard library only; nothing is installed or downloaded. Output: crates/domistream/tests/fixtures/ (text only: hex and PEM). """ import argparse import hashlib import os import shutil import subprocess import sys import tempfile ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) HERE = os.path.dirname(os.path.abspath(__file__)) FIXTURES = os.path.join(ROOT, "crates", "domistream", "tests", "fixtures") HEADER = ( "# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.\n" "# Never a real host's or client's key. Do not edit by hand: change the script and run it again.\n" ) def find_openssl(): env = os.environ.get("DOMISTREAM_OPENSSL") if env: return env git = r"C:\Program Files\Git\mingw64\bin\openssl.exe" if os.path.exists(git): return git found = shutil.which("openssl") if not found: sys.exit("openssl not found; set DOMISTREAM_OPENSSL") return found OPENSSL = find_openssl() DOTNET = os.environ.get("DOMISTREAM_DOTNET") or shutil.which("dotnet") or "dotnet" WORK = tempfile.mkdtemp(prefix="domistream-vectors-") OPENSSL_CNF = os.path.join(WORK, "openssl.cnf") with open(OPENSSL_CNF, "w", encoding="ascii") as f: f.write("[req]\ndistinguished_name = dn\nprompt = no\n[dn]\n") def run(args, stdin=None): env = dict(os.environ, OPENSSL_CONF=OPENSSL_CNF) proc = subprocess.run(args, input=stdin, capture_output=True, env=env, check=False) if proc.returncode != 0: sys.exit(f"command failed: {args}\n{proc.stderr.decode(errors='replace')}") return proc.stdout def openssl(*args, stdin=None): return run([OPENSSL, *args], stdin=stdin) def fixed(label, n): """A fixed, reproducible test value: the first n bytes of SHA-256 of a label (chained when n > 32).""" out = b"" counter = 0 while len(out) < n: out += hashlib.sha256(f"domistream-test:{label}:{counter}".encode()).digest() counter += 1 return out[:n] def sha256(*parts): h = hashlib.sha256() for p in parts: h.update(p) return h.digest() def tmp(name, data=None): path = os.path.join(WORK, name) if data is not None: with open(path, "wb") as f: f.write(data) return path # ---------------------------------------------------------------- AES via the OpenSSL CLI def ecb_encrypt(key, data): assert len(data) % 16 == 0 return openssl("enc", "-aes-128-ecb", "-nopad", "-K", key.hex(), stdin=data) def ecb_decrypt(key, data): return openssl("enc", "-d", "-aes-128-ecb", "-nopad", "-K", key.hex(), stdin=data) def cbc_encrypt(key, iv, data): return openssl("enc", "-aes-128-cbc", "-K", key.hex(), "-iv", iv.hex(), stdin=data) # ---------------------------------------------------------------- RSA and X.509 via the OpenSSL CLI def make_rsa_identity(stem, common_name): key = os.path.join(FIXTURES, f"{stem}-key.pem") cert = os.path.join(FIXTURES, f"{stem}-cert.pem") openssl("genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048", "-out", key) openssl("req", "-x509", "-new", "-key", key, "-sha256", "-days", "7300", "-subj", f"/CN={common_name}", "-config", OPENSSL_CNF, "-out", cert) def make_ec_cert(stem): key = tmp(f"{stem}-key.pem") cert = os.path.join(FIXTURES, f"{stem}-cert.pem") openssl("genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", key) openssl("req", "-x509", "-new", "-key", key, "-sha256", "-days", "7300", "-subj", "/CN=DomiStream test-only EC", "-config", OPENSSL_CNF, "-out", cert) def cert_der(stem): return openssl("x509", "-in", os.path.join(FIXTURES, f"{stem}-cert.pem"), "-outform", "DER") def key_pkcs8_der(stem): return openssl("pkcs8", "-topk8", "-nocrypt", "-in", os.path.join(FIXTURES, f"{stem}-key.pem"), "-outform", "DER") def sign(stem, data): """RSASSA-PKCS1-v1_5 with SHA-256 (OpenSSL's default padding for RSA keys).""" sig = openssl("dgst", "-sha256", "-sign", os.path.join(FIXTURES, f"{stem}-key.pem"), tmp("data.bin", data)) # Check it with the certificate's public key, so a vector never carries a signature OpenSSL itself rejects. pub = tmp("pub.pem", openssl("x509", "-in", os.path.join(FIXTURES, f"{stem}-cert.pem"), "-pubkey", "-noout")) openssl("dgst", "-sha256", "-verify", pub, "-signature", tmp("sig.bin", sig), tmp("data.bin", data)) return sig def der_read(buf, pos): """One DER TLV at pos: (tag, content_start, content_end).""" tag = buf[pos] length = buf[pos + 1] pos += 2 if length & 0x80: n = length & 0x7F length = int.from_bytes(buf[pos:pos + n], "big") pos += n return tag, pos, pos + length def cert_signature_value(der): """The raw signatureValue bytes of an X.509 certificate (RFC 5280 4.1): the BIT STRING's content after its unused-bits octet.""" tag, start, end = der_read(der, 0) assert tag == 0x30 and end == len(der) _, _, tbs_end = der_read(der, start) # tbsCertificate _, _, alg_end = der_read(der, tbs_end) # signatureAlgorithm tag, sig_start, sig_end = der_read(der, alg_end) assert tag == 0x03 and sig_end == end assert der[sig_start] == 0, "unused bits in signatureValue" return der[sig_start + 1:sig_end] # ---------------------------------------------------------------- AES-GCM via .NET def gcm_batch(rows): """rows: (name, key, nonce, plaintext) -> {name: (ciphertext, tag)}""" lines = [f"{n} {k.hex()} {iv.hex()} {pt.hex() if pt else '-'}" for n, k, iv, pt in rows] src = tmp("gcm_in.txt", ("\n".join(lines) + "\n").encode()) dst = tmp("gcm_out.txt") run([DOTNET, "run", os.path.join(HERE, "gcm_vectors.cs"), "--", src, dst]) out = {} with open(dst, encoding="ascii") as f: for line in f: name, ct, tag = line.split() out[name] = (b"" if ct == "-" else bytes.fromhex(ct), bytes.fromhex(tag)) return out # ---------------------------------------------------------------- writers def write_vectors(filename, title, entries): path = os.path.join(FIXTURES, filename) with open(path, "w", encoding="ascii", newline="\n") as f: f.write(HEADER) f.write(f"# {title}\n") for name, value in entries: if name.startswith("#"): f.write(f"\n{name}\n") continue if isinstance(value, bytes): value = value.hex() f.write(f"{name} = {value}\n") print("wrote", os.path.relpath(path, ROOT)) # ---------------------------------------------------------------- pairing (PROTOCOL.md 1.5) def pairing_vectors(): host_der = cert_der("test-only-host") client_der = cert_der("test-only-client") rogue_der = cert_der("test-only-rogue") host_sig = cert_signature_value(host_der) client_sig = cert_signature_value(client_der) pin = b"4071" wrong_pin = b"4072" # The client's randomness, in the order the state machine draws it: salt (step 1), C (step 2), secret_c (step 3). salt = fixed("salt-a", 16) c = fixed("client-challenge-a", 16) secret_c = fixed("client-secret-a", 16) # A second session (different randomness) for the replay test. salt_b = fixed("salt-b", 16) c_b = fixed("client-challenge-b", 16) secret_c_b = fixed("client-secret-b", 16) # The host's values. s_c = fixed("server-challenge", 16) secret_s = fixed("server-secret", 16) key = sha256(salt, pin)[:16] req2 = ecb_encrypt(key, c) assert ecb_decrypt(key, req2) == c h_s = sha256(c, host_sig, secret_s) resp2 = ecb_encrypt(key, h_s + s_c) h_c = sha256(s_c, client_sig, secret_c) req3 = ecb_encrypt(key, h_c) secret_s_sig = sign("test-only-host", secret_s) resp3 = secret_s + secret_s_sig secret_c_sig = sign("test-only-client", secret_c) req4 = secret_c + secret_c_sig # Wrong PIN on the host: the host decrypts the client challenge with its own key and answers with it. key_wrong = sha256(salt, wrong_pin)[:16] c_seen_by_host = ecb_decrypt(key_wrong, req2) resp2_wrong_pin = ecb_encrypt(key_wrong, sha256(c_seen_by_host, host_sig, secret_s) + s_c) # Right key, but H_s over a different host secret than the one the host reveals in step 3. resp2_wrong_hash = ecb_encrypt(key, sha256(c, host_sig, fixed("other-server-secret", 16)) + s_c) # Right key, but H_s over the rogue certificate's signature instead of the host's. resp2_wrong_cert = ecb_encrypt(key, sha256(c, cert_signature_value(rogue_der), secret_s) + s_c) # Step 3 signed by a key other than the host certificate's. resp3_rogue = secret_s + sign("test-only-rogue", secret_s) sign_data = b"DomiStream test-only signing input" entries = [ ("# Identities (DER, hex). PEM forms: test-only-*.pem next to this file.", None), ("host_cert_der", host_der), ("host_cert_signature", host_sig), ("client_cert_der", client_der), ("client_key_pkcs8_der", key_pkcs8_der("test-only-client")), ("client_cert_signature", client_sig), ("rogue_cert_der", rogue_der), ("rogue_key_pkcs8_der", key_pkcs8_der("test-only-rogue")), ("# Session A: the client's randomness (rng stream = salt || client_challenge || client_secret)", None), ("pin", pin.decode()), ("wrong_pin", wrong_pin.decode()), ("salt", salt), ("client_challenge", c), ("client_secret", secret_c), ("# Host values", None), ("server_challenge", s_c), ("server_secret", secret_s), ("# Derived, step by step", None), ("key", key), ("step2_clientchallenge", req2), ("host_proof", h_s), ("step2_challengeresponse", resp2), ("client_proof", h_c), ("step3_serverchallengeresp", req3), ("server_secret_signature", secret_s_sig), ("step3_pairingsecret", resp3), ("client_secret_signature", secret_c_sig), ("step4_clientpairingsecret", req4), ("# Hostile host answers", None), ("step2_challengeresponse_wrong_pin", resp2_wrong_pin), ("step2_challengeresponse_wrong_hash", resp2_wrong_hash), ("step2_challengeresponse_wrong_cert", resp2_wrong_cert), ("step3_pairingsecret_rogue_signature", resp3_rogue), ("# Session B: different randomness, for replaying session A's answers", None), ("salt_b", salt_b), ("client_challenge_b", c_b), ("client_secret_b", secret_c_b), ("# ClientIdentity::sign over a fixed input (PKCS#1 v1.5 is deterministic)", None), ("sign_data", sign_data), ("sign_data_client_signature", sign("test-only-client", sign_data)), ] # derive_key over several salts and PINs. entries.append(("# derive_key: SHA-256(salt || pin)[0..16]", None)) for i, p in enumerate([b"0000", b"9999", b"1234", b"4071"]): s = fixed(f"derive-salt-{i}", 16) entries += [(f"derive_{i}_salt", s), (f"derive_{i}_pin", p.decode()), (f"derive_{i}_key", sha256(s, p)[:16])] # AES-128-ECB, no padding, 1 to 4 blocks. entries.append(("# ecb: AES-128-ECB without padding", None)) for blocks in [1, 2, 3, 4]: k = fixed(f"ecb-key-{blocks}", 16) pt = fixed(f"ecb-plain-{blocks}", 16 * blocks) entries += [(f"ecb_{blocks}_key", k), (f"ecb_{blocks}_plain", pt), (f"ecb_{blocks}_cipher", ecb_encrypt(k, pt))] # proof_hash with signatures of several lengths (RSA-1024 .. RSA-8192, plus 0 and 1 byte). entries.append(("# proof_hash: SHA-256(challenge || signature || secret)", None)) for i, n in enumerate([0, 1, 128, 256, 512, 1024]): ch = fixed(f"proof-challenge-{i}", 16) sg = fixed(f"proof-signature-{i}", n) se = fixed(f"proof-secret-{i}", 16) entries += [(f"proof_{i}_challenge", ch), (f"proof_{i}_signature", sg if n else "-"), (f"proof_{i}_secret", se), (f"proof_{i}_hash", sha256(ch, sg, se))] write_vectors("pairing.txt", "Pairing (PROTOCOL.md 1.5): SHA-256 hashlib, AES-ECB + RSA openssl", entries) # ---------------------------------------------------------------- control frames (PROTOCOL.md 3.2) def control_nonce(seq, direction): return seq.to_bytes(4, "little") + bytes(6) + direction + b"C" def control_vectors(): key = fixed("control-rikey", 16) cases = [ # (name, seq, direction byte, plaintext) ("c_ping_0", 0, b"C", bytes.fromhex("00020000")), ("c_input_1", 1, b"C", bytes.fromhex("06020c000000000807000000ffff0000")), ("c_ping_ffff", 0xFFFF, b"C", bytes.fromhex("00020000")), ("c_ping_10000", 0x10000, b"C", bytes.fromhex("00020000")), ("c_ping_fffffffe", 0xFFFFFFFE, b"C", bytes.fromhex("00020000")), ("c_ping_ffffffff", 0xFFFFFFFF, b"C", bytes.fromhex("00020000")), ("h_rumble_0", 0, b"H", bytes.fromhex("0b010a00000000000100ff7f0080")), ("h_rumble_7", 7, b"H", bytes.fromhex("0b010a00000000000100ff7f0080")), ("h_termination_ffffffff", 0xFFFFFFFF, b"H", bytes.fromhex("0901040080030023")), ("h_rgb_2a", 0x2A, b"H", bytes.fromhex("0255050003001020ff")), ] out = gcm_batch([(n, key, control_nonce(s, d), pt) for n, s, d, pt in cases]) entries = [("key", key)] for name, seq, direction, pt in cases: ct, tag = out[name] frame = (1).to_bytes(2, "little") + (4 + 16 + len(ct)).to_bytes(2, "little") + seq.to_bytes(4, "little") frame += tag + ct entries += [ (f"# {name}", None), (f"{name}_sequence", f"{seq:08x}"), (f"{name}_direction", direction.decode()), (f"{name}_nonce", control_nonce(seq, direction)), (f"{name}_plain", pt), (f"{name}_frame", frame), ] write_vectors("control_gcm.txt", "Control frames (PROTOCOL.md 3.2): AES-128-GCM by .NET AesGcm", entries) # ---------------------------------------------------------------- video encryption (PROTOCOL.md 7) def video_vectors(): key = fixed("video-rikey", 16) cases = [] for name, counter, frame_number, n in [ ("v_0", 0, 0, 48), ("v_1", 1, 0, 48), ("v_big_counter", 0x0102030405060708, 0x11223344, 64), ("v_1040", 7, 3, 1040), ]: pt = fixed(f"video-plain-{name}", n) iv = counter.to_bytes(8, "little") + bytes(3) + b"V" cases.append((name, counter, frame_number, iv, pt)) out = gcm_batch([(n, key, iv, pt) for n, _, _, iv, pt in cases]) entries = [("key", key)] for name, counter, frame_number, iv, pt in cases: ct, tag = out[name] packet = iv + frame_number.to_bytes(4, "little") + tag + ct entries += [(f"# {name}", None), (f"{name}_plain", pt), (f"{name}_packet", packet)] write_vectors("video_gcm.txt", "Video packets (PROTOCOL.md 7): AES-128-GCM by .NET AesGcm", entries) # ---------------------------------------------------------------- audio encryption (PROTOCOL.md 6.3) def audio_vectors(): key = fixed("audio-rikey", 16) entries = [("key", key)] for name, rikeyid, seq, n in [ ("a_0", 0, 0, 20), ("a_1", 0x01020304, 1, 20), ("a_ffff", 0x00000010, 0xFFFF, 33), ("a_wrap", 0xFFFFFFFE, 5, 16), ("a_exact_block", 7, 100, 32), ("a_one_byte", 7, 101, 1), ]: iv = ((rikeyid + seq) & 0xFFFFFFFF).to_bytes(4, "big") + bytes(12) pt = fixed(f"audio-plain-{name}", n) entries += [ (f"# {name}", None), (f"{name}_rikeyid", f"{rikeyid:08x}"), (f"{name}_sequence", f"{seq:04x}"), (f"{name}_iv", iv), (f"{name}_plain", pt), (f"{name}_cipher", cbc_encrypt(key, iv, pt)), ] write_vectors("audio_cbc.txt", "Audio payloads (PROTOCOL.md 6.3): AES-128-CBC + PKCS#7 by openssl", entries) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--fresh-keys", action="store_true", help="make new test-only keys and certificates") args = parser.parse_args() print("openssl:", openssl("version").decode().strip()) os.makedirs(FIXTURES, exist_ok=True) stems = ["test-only-host", "test-only-client", "test-only-rogue"] missing = any(not os.path.exists(os.path.join(FIXTURES, f"{s}-cert.pem")) for s in stems) if args.fresh_keys or missing: make_rsa_identity("test-only-host", "DomiStream test-only host") make_rsa_identity("test-only-client", "DomiStream test-only client") make_rsa_identity("test-only-rogue", "DomiStream test-only rogue") make_ec_cert("test-only-ec") print("made fresh test-only keys") pairing_vectors() control_vectors() video_vectors() audio_vectors() shutil.rmtree(WORK, ignore_errors=True) if __name__ == "__main__": main()