omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / om / tls / test / fuzz / gen_seeds.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | # Test tooling only (om/tls fuzz targets, run.sh): writes the seed corpus of every fuzz target from |
| 4 | # the repo's own vectors, plus a TLS 1.3 server flight built with python3 `cryptography` for the |
| 5 | # deterministic ClientHello of fz_flight. Nothing here is the implementation under test. |
| 6 | # usage: gen_seeds.py OUTDIR CHFILE |
| 7 | # CHFILE: the ClientHello fz_flight writes with argument 2 (`fz_flight seeds/fzstore.pem CHFILE < |
| 8 | # any-input`; run.sh has no step for it). Keep a copy as seeds/ch.bin: the flight seeds sign and MAC |
| 9 | # exactly that ClientHello, so they must be regenerated whenever tls_mkch's output changes. |
| 10 | # Writes OUTDIR/<target>/<name> and OUTDIR/fzstore.pem (pki/storeAll.pem + this run's own root). |
| 11 | # Keys are fresh on every run, so the flight seeds differ byte-wise between runs (run.sh keeps the |
| 12 | # committed seeds/ directory; regenerate only together with fzstore.pem). |
| 13 | import datetime |
| 14 | import hashlib |
| 15 | import hmac |
| 16 | import importlib.util |
| 17 | import os |
| 18 | import sys |
| 19 | |
| 20 | from cryptography import x509 |
| 21 | from cryptography.hazmat.primitives import hashes, serialization |
| 22 | from cryptography.hazmat.primitives.asymmetric import ec, x25519 |
| 23 | from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID |
| 24 | |
| 25 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 26 | TEST = os.path.dirname(HERE) |
| 27 | REPO = os.path.dirname(os.path.dirname(os.path.dirname(TEST))) |
| 28 | PKI = os.path.join(TEST, "x509", "vectors", "pki") |
| 29 | HOST = b"www.example.test" |
| 30 | NOW = 1792972800 |
| 31 | |
| 32 | |
| 33 | def u8(n): return bytes([n]) |
| 34 | def u16(n): return n.to_bytes(2, "big") |
| 35 | def u24(n): return n.to_bytes(3, "big") |
| 36 | def msg(t, body): return u8(t) + u24(len(body)) + body |
| 37 | def chunk(t, b): return u8(t) + u16(len(b)) + b |
| 38 | def rec(t, b): return u8(t) + b"\x03\x03" + u16(len(b)) + b |
| 39 | def fill(n, v): return bytes((v + i) & 255 for i in range(n)) |
| 40 | def h256(b): return hashlib.sha256(b).digest() |
| 41 | def rd(*p): return open(os.path.join(*p), "rb").read() |
| 42 | |
| 43 | |
| 44 | def expand_label(secret, label, ctx, n): |
| 45 | info = u16(n) + u8(6 + len(label)) + b"tls13 " + label + u8(len(ctx)) + ctx |
| 46 | out, t, i = b"", b"", 1 |
| 47 | while len(out) < n: |
| 48 | t = hmac.new(secret, t + info + u8(i), hashlib.sha256).digest() |
| 49 | out += t |
| 50 | i += 1 |
| 51 | return out[:n] |
| 52 | |
| 53 | |
| 54 | def extract(salt, ikm): return hmac.new(salt, ikm, hashlib.sha256).digest() |
| 55 | |
| 56 | |
| 57 | def pki(): |
| 58 | """root -> int -> leaf, P-256, valid 2025..2049, leaf SAN www.example.test; every certificate |
| 59 | carries a subjectKeyIdentifier, and the two that are not self-issued an authorityKeyIdentifier |
| 60 | (x509.om chain_xchk refuses a presented certificate without one, RFC 5280 4.2.1.1)""" |
| 61 | nb = datetime.datetime(2025, 1, 1, tzinfo=datetime.timezone.utc) |
| 62 | na = datetime.datetime(2049, 12, 31, tzinfo=datetime.timezone.utc) |
| 63 | keys = [ec.generate_private_key(ec.SECP256R1()) for _ in range(3)] |
| 64 | names = [x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, n)]) |
| 65 | for n in ("omfz root", "omfz int", "www.example.test")] |
| 66 | certs = [] |
| 67 | for i in range(3): |
| 68 | b = (x509.CertificateBuilder().subject_name(names[i]) |
| 69 | .issuer_name(names[max(i - 1, 0)]).public_key(keys[i].public_key()) |
| 70 | .serial_number(1000 + i).not_valid_before(nb).not_valid_after(na)) |
| 71 | ca = i < 2 |
| 72 | b = b.add_extension(x509.BasicConstraints(ca=ca, path_length=None), critical=True) |
| 73 | b = b.add_extension(x509.KeyUsage( |
| 74 | digital_signature=not ca, content_commitment=False, key_encipherment=False, |
| 75 | data_encipherment=False, key_agreement=False, key_cert_sign=ca, crl_sign=ca, |
| 76 | encipher_only=False, decipher_only=False), critical=True) |
| 77 | b = b.add_extension(x509.SubjectKeyIdentifier.from_public_key(keys[i].public_key()), False) |
| 78 | if i: |
| 79 | b = b.add_extension( |
| 80 | x509.AuthorityKeyIdentifier.from_issuer_public_key(keys[i - 1].public_key()), False) |
| 81 | if not ca: |
| 82 | b = b.add_extension(x509.SubjectAlternativeName([x509.DNSName(HOST.decode())]), False) |
| 83 | b = b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), False) |
| 84 | certs.append(b.sign(keys[max(i - 1, 0)], hashes.SHA256())) |
| 85 | der = [c.public_bytes(serialization.Encoding.DER) for c in certs] |
| 86 | pem = certs[0].public_bytes(serialization.Encoding.PEM) |
| 87 | return der, keys[2], pem |
| 88 | |
| 89 | |
| 90 | def entry(d): return u24(len(d)) + d + b"\x00\x00" |
| 91 | |
| 92 | |
| 93 | def cvsig(key, th): |
| 94 | content = b"\x20" * 64 + b"TLS 1.3, server CertificateVerify\x00" + th |
| 95 | return key.sign(content, ec.ECDSA(hashes.SHA256())), content |
| 96 | |
| 97 | |
| 98 | class Out: |
| 99 | def __init__(self, root): |
| 100 | self.root = root |
| 101 | self.n = 0 |
| 102 | |
| 103 | def put(self, target, name, data): |
| 104 | d = os.path.join(self.root, target) |
| 105 | os.makedirs(d, exist_ok=True) |
| 106 | open(os.path.join(d, name), "wb").write(data) |
| 107 | self.n += 1 |
| 108 | |
| 109 | |
| 110 | def flight(o, ch, der, key, suite): |
| 111 | """fz_flight: R raw chunks for the ClientHello ch (tls_mkch made deterministic by fz_detch)""" |
| 112 | sk = x25519.X25519PrivateKey.from_private_bytes(fill(32, 7)) |
| 113 | spub = sk.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) |
| 114 | cpub = ch[ch.index(b"\x00\x1d\x00\x20") + 4:][:32] |
| 115 | shared = sk.exchange(x25519.X25519PublicKey.from_public_bytes(cpub)) |
| 116 | sid = ch[39:71] |
| 117 | ext = (u16(43) + u16(2) + b"\x03\x04" + u16(51) + u16(36) + u16(29) + u16(32) + spub) |
| 118 | sh = msg(2, b"\x03\x03" + fill(32, 150) + u8(32) + sid + u16(suite) + b"\x00" |
| 119 | + u16(len(ext)) + ext) |
| 120 | z = b"\x00" * 32 |
| 121 | early = extract(z, z) |
| 122 | hs = extract(expand_label(early, b"derived", h256(b""), 32), shared) |
| 123 | shts = expand_label(hs, b"s hs traffic", h256(ch + sh), 32) |
| 124 | alpn = u16(16) + u16(11) + u16(9) + u8(8) + b"http/1.1" |
| 125 | ee = msg(8, u16(len(alpn)) + alpn) |
| 126 | lst = b"".join(entry(d) for d in (der[2], der[1])) |
| 127 | cert = msg(11, b"\x00" + u24(len(lst)) + lst) |
| 128 | sig, _ = cvsig(key, h256(ch + sh + ee + cert)) |
| 129 | cv = msg(15, u16(0x0403) + u16(len(sig)) + sig) |
| 130 | fk = expand_label(shts, b"finished", b"", 32) |
| 131 | fin = msg(20, hmac.new(fk, h256(ch + sh + ee + cert + cv), hashlib.sha256).digest()) |
| 132 | raw = rec(22, sh) + rec(20, b"\x01") |
| 133 | tag = "chacha" if suite == 0x1303 else "aes" |
| 134 | pre = u16(len(raw)) + raw |
| 135 | o.put("fz_flight", f"full_{tag}", pre + chunk(22, ee + cert + cv + fin)) |
| 136 | o.put("fz_flight", f"split_{tag}", pre + b"".join(chunk(22, m) for m in (ee, cert, cv, fin))) |
| 137 | frag = ee + cert + cv + fin |
| 138 | o.put("fz_flight", f"frag_{tag}", pre + b"".join(chunk(22, frag[i:i + 300]) |
| 139 | for i in range(0, len(frag), 300))) |
| 140 | cr = msg(13, b"\x00" + u16(8) + u16(13) + u16(4) + u16(2) + u16(0x0403)) |
| 141 | o.put("fz_flight", f"cr_{tag}", pre + chunk(22, ee + cr + cert + cv + fin)) |
| 142 | o.put("fz_flight", f"pad_{tag}", pre + chunk(22, ee) + chunk(0, b"") + chunk(22, cert + cv + fin)) |
| 143 | o.put("fz_flight", f"alert_{tag}", pre + chunk(22, ee) + chunk(21, b"\x02\x28")) |
| 144 | o.put("fz_flight", f"shonly_{tag}", u16(len(rec(22, sh))) + rec(22, sh)) |
| 145 | hrr = msg(2, b"\x03\x03" + h256(b"HelloRetryRequest") + u8(32) + sid + u16(suite) + b"\x00" |
| 146 | + u16(12) + u16(43) + u16(2) + b"\x03\x04" + u16(51) + u16(2) + u16(29)) |
| 147 | o.put("fz_flight", f"hrr_{tag}", u16(len(rec(22, hrr))) + rec(22, hrr)) |
| 148 | return sh, ee, cert, cv |
| 149 | |
| 150 | |
| 151 | def hs(o, der, key): |
| 152 | """fz_hs: S message, against fixed state (TLSID zero, TLSHS 33.., transcript hash 217..)""" |
| 153 | spub = fill(32, 9) |
| 154 | ext = (u16(43) + u16(2) + b"\x03\x04" + u16(51) + u16(36) + u16(29) + u16(32) + spub) |
| 155 | for suite in (0x1301, 0x1303): |
| 156 | o.put("fz_hs", f"sh_{suite:04x}", u8(0) + msg(2, b"\x03\x03" + fill(32, 1) + u8(32) |
| 157 | + b"\x00" * 32 + u16(suite) + b"\x00" |
| 158 | + u16(len(ext)) + ext)) |
| 159 | v = {} |
| 160 | for line in open(os.path.join(TEST, "tls", "vectors", "rfc8448-1rtt.txt")): |
| 161 | p = line.split() |
| 162 | if len(p) == 2 and not line.startswith("#"): |
| 163 | v[p[0]] = bytes.fromhex(p[1]) if all(c in "0123456789abcdef" for c in p[1]) else None |
| 164 | o.put("fz_hs", "sh_rfc8448", u8(0) + v["sh"]) |
| 165 | o.put("fz_hs", "ee_rfc8448", u8(1) + v["ee"]) |
| 166 | alpn = u16(16) + u16(11) + u16(9) + u8(8) + b"http/1.1" |
| 167 | o.put("fz_hs", "ee_alpn", u8(1) + msg(8, u16(len(alpn)) + alpn)) |
| 168 | o.put("fz_hs", "cr", u8(2) + msg(13, b"\x00" + u16(8) + u16(13) + u16(4) + u16(2) + u16(0x0403))) |
| 169 | lst = b"".join(entry(d) for d in (der[2], der[1])) |
| 170 | o.put("fz_hs", "cert_own", u8(3) + msg(11, b"\x00" + u24(len(lst)) + lst)) |
| 171 | o.put("fz_hs", "cert_rfc8448", u8(3) + v["cert"]) |
| 172 | sig, _ = cvsig(key, fill(32, 217)) |
| 173 | le = entry(der[2]) |
| 174 | o.put("fz_hs", "cv_own", u8(4) + u16(len(le)) + le + msg(15, u16(0x0403) + u16(len(sig)) + sig)) |
| 175 | fk = expand_label(fill(32, 33), b"finished", b"", 32) |
| 176 | o.put("fz_hs", "sfin", u8(5) + msg(20, hmac.new(fk, fill(32, 217), hashlib.sha256).digest())) |
| 177 | o.put("fz_hs", "kupd0", u8(6) + msg(24, b"\x00")) |
| 178 | o.put("fz_hs", "kupd1", u8(6) + msg(24, b"\x01")) |
| 179 | nst = msg(4, fill(4, 0) + fill(4, 4) + u8(8) + fill(8, 8) + u16(16) + fill(16, 16) + u16(0)) |
| 180 | o.put("fz_hs", "post_nst", u8(7) + nst) |
| 181 | o.put("fz_hs", "post_nst2_ku", u8(7) + nst + nst + msg(24, b"\x00")) |
| 182 | o.put("fz_hs", "post_split", u8(7) + nst[:5]) |
| 183 | |
| 184 | |
| 185 | def x509s(o, der): |
| 186 | """fz_x509: M rest (0 parse, 1 chain, 2 time+host+chain, 3 CertificateVerify)""" |
| 187 | for sub in ("pki", "real", "crafted"): |
| 188 | d = os.path.join(TEST, "x509", "vectors", sub) |
| 189 | for f in sorted(os.listdir(d)): |
| 190 | if f.endswith(".der") and os.path.getsize(os.path.join(d, f)) <= 8192: |
| 191 | o.put("fz_x509", f"p_{sub}_{f[:-4]}", u8(0) + rd(d, f)) |
| 192 | own = b"".join(entry(d) for d in (der[2], der[1])) |
| 193 | rsa = entry(rd(PKI, "lR.der")) + entry(rd(PKI, "intR.der")) |
| 194 | o.put("fz_x509", "c_own", u8(1) + own) |
| 195 | o.put("fz_x509", "c_rsa", u8(1) + rsa) |
| 196 | for name, now, host in (("hq_own", NOW, HOST), ("hq_late", 4102444800, HOST), |
| 197 | ("hq_other", NOW, b"other.example.test")): |
| 198 | o.put("fz_x509", name, u8(2) + now.to_bytes(8, "big") |
| 199 | + u8(len(host)) + host + own) |
| 200 | for leaf, sch, sig in (("lE256", 0x0403, "cv_e256"), ("lE384", 0x0503, "cv_e384"), |
| 201 | ("lR", 0x0804, "cv_r256"), ("lPSS384", 0x0805, "cv_r384"), |
| 202 | ("lPSS512", 0x0806, "cv_r512")): |
| 203 | e = entry(rd(PKI, leaf + ".der")) |
| 204 | o.put("fz_x509", f"cv_{leaf}", u8(3) + u16(sch) + u16(len(e)) + e |
| 205 | + rd(PKI, "cv.msg") + rd(PKI, sig + ".sig")) |
| 206 | |
| 207 | |
| 208 | def pems(o): |
| 209 | """fz_pem: a PEM bundle (argument 1 = a certificate_list file)""" |
| 210 | for f in ("storeAll.pem", "storeR.pem", "storeE.pem", "storeBad.pem", "storeDup.pem", |
| 211 | "storeInt.pem", "storeX.pem"): |
| 212 | o.put("fz_pem", f[:-4], rd(PKI, f)) |
| 213 | |
| 214 | |
| 215 | def dns(o): |
| 216 | """fz_dns: M rest; M even: H name[H] response (dns_parse of dns_query id 0x4f4d), odd: resolv.conf""" |
| 217 | for i, line in enumerate(open(os.path.join(TEST, "tls", "vectors", "dns.txt"))): |
| 218 | p = line.split() |
| 219 | if len(p) == 4 and p[0] in ("0", "E"): |
| 220 | h = p[2].encode() |
| 221 | o.put("fz_dns", f"r{i:02d}", u8(0) + u8(min(len(h), 255)) + h[:255] + bytes.fromhex(p[3])) |
| 222 | elif len(p) == 2 and p[0] == "L": |
| 223 | o.put("fz_dns", f"l{i:02d}", u8(0) + u8(min(len(p[1]), 255)) + p[1].encode()[:255]) |
| 224 | for i, t in enumerate((b"nameserver 192.0.2.53\n", |
| 225 | b"# c\nsearch example.test\nnameserver 10.0.0.1\nnameserver ::1\n", |
| 226 | b"options ndots:1\nnameserver\t127.0.0.53 \n", |
| 227 | b"nameserver 256.1.1.1\nnameserver 1.2.3\n")): |
| 228 | o.put("fz_dns", f"conf{i}", u8(1) + t) |
| 229 | |
| 230 | |
| 231 | def http(o): |
| 232 | """fz_http: M message (0 response, 1 response to HEAD, 2 request); check.py's hand cases""" |
| 233 | spec = importlib.util.spec_from_file_location("check", os.path.join(REPO, "seed", "net", |
| 234 | "tests", "check.py")) |
| 235 | m = importlib.util.module_from_spec(spec) |
| 236 | spec.loader.exec_module(m) |
| 237 | for i, (mode, b, _) in enumerate(m.hand_cases()): |
| 238 | o.put("fz_http", f"hand{i:02d}", u8({"s": 0, "h": 1, "q": 2}[mode]) + b) |
| 239 | |
| 240 | |
| 241 | def https(o): |
| 242 | """fz_https: M chunks (M bit 0 HEAD, bit 1 AES), established keys, sealed by the mirror""" |
| 243 | r1 = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nhello" |
| 244 | r2 = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n" |
| 245 | r3 = b"HTTP/1.1 100 Continue\r\n\r\nHTTP/1.0 200 OK\r\n\r\nbody to close" |
| 246 | close = chunk(21, b"\x01\x00") |
| 247 | nst = msg(4, fill(4, 0) + fill(4, 4) + u8(8) + fill(8, 8) + u16(16) + fill(16, 16) + u16(0)) |
| 248 | for m in (0, 2): |
| 249 | tag = "aes" if m else "chacha" |
| 250 | o.put("fz_https", f"cl_{tag}", u8(m) + chunk(23, r1) + close) |
| 251 | o.put("fz_https", f"chunked_{tag}", u8(m) + chunk(23, r2[:20]) + chunk(23, r2[20:]) + close) |
| 252 | o.put("fz_https", f"interim_{tag}", u8(m) + chunk(23, r3) + close) |
| 253 | o.put("fz_https", f"nst_ku_{tag}", u8(m) + chunk(22, nst) + chunk(22, msg(24, b"\x01")) |
| 254 | + chunk(23, r1) + close) |
| 255 | o.put("fz_https", f"pad_{tag}", u8(m) + chunk(23, b"") + chunk(23, r1) + close) |
| 256 | o.put("fz_https", f"trunc_{tag}", u8(m) + chunk(23, r1[:30])) |
| 257 | o.put("fz_https", f"raw_{tag}", u8(m) + chunk(128, rec(23, b"\x00" * 20))) |
| 258 | o.put("fz_https", "head", u8(1) + chunk(23, r1[:-5]) + close) |
| 259 | |
| 260 | |
| 261 | def main(): |
| 262 | if len(sys.argv) != 3: |
| 263 | sys.exit("usage: gen_seeds.py OUTDIR CHFILE") |
| 264 | o = Out(sys.argv[1]) |
| 265 | ch = open(sys.argv[2], "rb").read() |
| 266 | der, key, root = pki() |
| 267 | open(os.path.join(sys.argv[1], "fzstore.pem"), "wb").write(rd(PKI, "storeAll.pem") + root) |
| 268 | flight(o, ch, der, key, 0x1303) |
| 269 | flight(o, ch, der, key, 0x1301) |
| 270 | hs(o, der, key) |
| 271 | x509s(o, der) |
| 272 | pems(o) |
| 273 | o.put("fz_pem", "own_root", root) |
| 274 | open(os.path.join(sys.argv[1], "chain.bin"), "wb").write( |
| 275 | b"".join(entry(d) for d in (der[2], der[1]))) |
| 276 | dns(o) |
| 277 | o.put("fz_plant", "plain", u8(0) + b"abcd") # no byte of "OMFZ": the fuzzer climbs all four |
| 278 | http(o) |
| 279 | https(o) |
| 280 | print(f"gen_seeds: {o.n} seeds in {sys.argv[1]}") |
| 281 | |
| 282 | |
| 283 | if __name__ == "__main__": |
| 284 | main() |