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 / x509 / gen_crafted.py
| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # Test tooling only: write the crafted X.509 fixtures of the security review (omega-mv #813) into |
| 3 | # vectors/crafted/ with Python cryptography (>= 41). Keys are fresh random keys, so a rerun produces |
| 4 | # different (equally valid) fixtures; cases.txt does not depend on key bytes. |
| 5 | # uid_* repeated / reordered issuerUniqueID [1] and subjectUniqueID [2] (finding 1) |
| 6 | # *10001 SEQUENCE OF lists with 10001 elements, *9999 controls (finding 2) |
| 7 | # lXbig a validly signed leaf larger than 16896 bytes (finding 2) |
| 8 | # intXnc* nameConstraints, NOT critical, on an intermediate (finding 5) |
| 9 | # lX6144 lXe32 lXeven lXe1 intX6144 intXe32, controls lXe3 lX4096 (finding 6) |
| 10 | # Usage: python3 gen_crafted.py |
| 11 | import datetime |
| 12 | import math |
| 13 | import os |
| 14 | import sys |
| 15 | |
| 16 | from cryptography import x509 |
| 17 | from cryptography.hazmat.primitives import hashes, serialization |
| 18 | from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa |
| 19 | from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID |
| 20 | |
| 21 | here = os.path.dirname(os.path.abspath(__file__)) |
| 22 | out = os.path.join(here, "vectors", "crafted") |
| 23 | os.makedirs(out, exist_ok=True) |
| 24 | for f in os.listdir(out): |
| 25 | os.remove(os.path.join(out, f)) |
| 26 | T0 = datetime.datetime(2026, 1, 1) |
| 27 | T1 = datetime.datetime(2027, 1, 1) |
| 28 | R0 = datetime.datetime(2020, 1, 1) |
| 29 | R1 = datetime.datetime(2051, 1, 1) |
| 30 | |
| 31 | |
| 32 | def tlv(tag, body): |
| 33 | n = len(body) |
| 34 | if n < 128: |
| 35 | h = bytes([n]) |
| 36 | else: |
| 37 | b = n.to_bytes((n.bit_length() + 7) // 8, "big") |
| 38 | h = bytes([0x80 | len(b)]) + b |
| 39 | return bytes([tag]) + h + body |
| 40 | |
| 41 | |
| 42 | def parse(d): |
| 43 | """children of the constructed TLV d as (tag, full TLV bytes)""" |
| 44 | def hdr(d, i): |
| 45 | t = d[i] |
| 46 | n = d[i + 1] |
| 47 | i += 2 |
| 48 | if n & 0x80: |
| 49 | k = n & 0x7F |
| 50 | n = int.from_bytes(d[i:i + k], "big") |
| 51 | i += k |
| 52 | return t, i, n |
| 53 | _, i, n = hdr(d, 0) |
| 54 | end = i + n |
| 55 | r = [] |
| 56 | while i < end: |
| 57 | s = i |
| 58 | t, j, n = hdr(d, i) |
| 59 | i = j + n |
| 60 | r.append((t, d[s:i])) |
| 61 | return r |
| 62 | |
| 63 | |
| 64 | def name(cn): |
| 65 | return x509.Name([x509.NameAttribute(NameOID.ORGANIZATION_NAME, "omtls test"), |
| 66 | x509.NameAttribute(NameOID.COMMON_NAME, cn)]) |
| 67 | |
| 68 | |
| 69 | def build(cn, pub, issuer, ikey, ca, t0=T0, t1=T1, san=("www.example.test", "example.test"), nc=None): |
| 70 | b = (x509.CertificateBuilder().subject_name(name(cn)).issuer_name(issuer.subject if issuer else name(cn)) |
| 71 | .public_key(pub).serial_number(x509.random_serial_number()).not_valid_before(t0).not_valid_after(t1)) |
| 72 | b = b.add_extension(x509.SubjectKeyIdentifier.from_public_key(pub), critical=False) |
| 73 | if issuer: |
| 74 | b = b.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ikey.public_key()), critical=False) |
| 75 | if ca: |
| 76 | b = b.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) |
| 77 | b = b.add_extension(x509.KeyUsage(False, False, False, False, False, True, True, False, False), critical=True) |
| 78 | if nc: |
| 79 | b = b.add_extension(x509.NameConstraints(permitted_subtrees=[x509.DNSName(nc)], excluded_subtrees=None), |
| 80 | critical=False) |
| 81 | else: |
| 82 | b = b.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) |
| 83 | b = b.add_extension(x509.KeyUsage(True, False, False, False, False, False, False, False, False), critical=True) |
| 84 | b = b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False) |
| 85 | b = b.add_extension(x509.SubjectAlternativeName([x509.DNSName(s) for s in san]), critical=False) |
| 86 | return b.sign(ikey, hashes.SHA256()) |
| 87 | |
| 88 | |
| 89 | def der(c): |
| 90 | return c.public_bytes(serialization.Encoding.DER) |
| 91 | |
| 92 | |
| 93 | def put(n, data): |
| 94 | with open(os.path.join(out, n), "wb") as f: |
| 95 | f.write(data) |
| 96 | |
| 97 | |
| 98 | def resign(cdef, key, tbs_children): |
| 99 | """certificate from replaced tbsCertificate children, signed again with key (same algorithm)""" |
| 100 | alg = parse(cdef)[1][1] |
| 101 | tbs = tlv(0x30, b"".join(tbs_children)) |
| 102 | if isinstance(key, ec.EllipticCurvePrivateKey): |
| 103 | sig = key.sign(tbs, ec.ECDSA(hashes.SHA256())) |
| 104 | else: |
| 105 | sig = key.sign(tbs, padding.PKCS1v15(), hashes.SHA256()) |
| 106 | return tlv(0x30, tbs + alg + tlv(0x03, b"\x00" + sig)) |
| 107 | |
| 108 | |
| 109 | def rsa_with_e(bits, e): |
| 110 | """an RSA key with public exponent e (odd, coprime to lambda): CRT values from fresh primes""" |
| 111 | while True: |
| 112 | k = rsa.generate_private_key(public_exponent=65537, key_size=bits) |
| 113 | p = k.private_numbers().p |
| 114 | q = k.private_numbers().q |
| 115 | lam = (p - 1) * (q - 1) // math.gcd(p - 1, q - 1) |
| 116 | if math.gcd(e, lam) == 1: |
| 117 | d = pow(e, -1, lam) |
| 118 | pub = rsa.RSAPublicNumbers(e, p * q) |
| 119 | return rsa.RSAPrivateNumbers(p, q, d, rsa.rsa_crt_dmp1(d, p), rsa.rsa_crt_dmq1(d, q), |
| 120 | rsa.rsa_crt_iqmp(p, q), pub).private_key() |
| 121 | |
| 122 | |
| 123 | def rsa_spki(n, e): |
| 124 | """SubjectPublicKeyInfo rsaEncryption with RSAPublicKey {n, e} (any e, no private key)""" |
| 125 | def integer(v): |
| 126 | b = v.to_bytes(v.bit_length() // 8 + 1, "big") |
| 127 | return tlv(0x02, b) |
| 128 | alg = tlv(0x30, tlv(0x06, bytes.fromhex("2a864886f70d010101")) + b"\x05\x00") |
| 129 | return tlv(0x30, alg + tlv(0x03, b"\x00" + tlv(0x30, integer(n) + integer(e)))) |
| 130 | |
| 131 | |
| 132 | # root (EC P-256) and store |
| 133 | rk = ec.generate_private_key(ec.SECP256R1()) |
| 134 | root = build("rootX", rk.public_key(), None, rk, True, R0, R1) |
| 135 | put("rootX.der", der(root)) |
| 136 | put("storeX.pem", root.public_bytes(serialization.Encoding.PEM)) |
| 137 | lk = ec.generate_private_key(ec.SECP256R1()) |
| 138 | base = der(build("lXbase", lk.public_key(), root, rk, False)) |
| 139 | put("lXbase.der", base) |
| 140 | tbs = [c for _, c in parse(parse(base)[0][1])] |
| 141 | assert tbs[0][0] == 0xA0 and tbs[7][0] == 0xA3 and len(tbs) == 8 |
| 142 | head, exts = tbs[:7], tbs[7] |
| 143 | uid1 = tlv(0x81, b"\x00\x01\x02") |
| 144 | uid2 = tlv(0x82, b"\x00\x03\x04") |
| 145 | |
| 146 | # finding 1: unique IDs |
| 147 | for n, ids in [("uid_ok", [uid1, uid2]), ("uid_one2", [uid2]), ("uid_two1", [uid1, uid1]), |
| 148 | ("uid_two2", [uid2, uid2]), ("uid_21", [uid2, uid1]), |
| 149 | ("uid_five", [tlv(0x81, b"\x00")] * 5), ("uid_112", [uid1, uid1, uid2])]: |
| 150 | put(n + ".der", resign(base, rk, head + ids + [exts])) |
| 151 | |
| 152 | |
| 153 | # finding 2: element counts (smallest valid elements, so the lists are short in bytes) |
| 154 | def ext(oid_hex, crit, value): |
| 155 | return tlv(0x30, tlv(0x06, bytes.fromhex(oid_hex)) + (b"\x01\x01\xff" if crit else b"") + tlv(0x04, value)) |
| 156 | |
| 157 | |
| 158 | def with_exts(extlist): |
| 159 | return head + [tlv(0xA3, tlv(0x30, b"".join(extlist)))] |
| 160 | |
| 161 | |
| 162 | oid12 = tlv(0x06, b"\x2a") # 1.2 |
| 163 | for cnt in (9999, 10001): |
| 164 | put("eku%d.der" % cnt, resign(base, rk, with_exts([ext("551d25", False, tlv(0x30, oid12 * cnt))]))) |
| 165 | put("san%d.der" % cnt, resign(base, rk, with_exts([ext("551d11", False, tlv(0x30, tlv(0x82, b"a") * cnt))]))) |
| 166 | put("ext10001.der", resign(base, rk, with_exts([ext("2a03", False, b"")] * 10001))) |
| 167 | big = build("lXbig", lk.public_key(), root, rk, False, |
| 168 | san=["www.example.test"] + ["n%04d.example.test" % i for i in range(1500)]) |
| 169 | assert len(der(big)) > 16896 |
| 170 | put("lXbig.der", der(big)) |
| 171 | |
| 172 | # finding 5: nameConstraints not critical on an intermediate |
| 173 | ik = ec.generate_private_key(ec.SECP256R1()) |
| 174 | inc = build("intXnc", ik.public_key(), root, rk, True, nc="example.test") |
| 175 | put("intXnc.der", der(inc)) |
| 176 | put("lViaXnc.der", der(build("lViaXnc", lk.public_key(), inc, ik, False))) |
| 177 | put("lViaXncOut.der", der(build("lViaXncOut", lk.public_key(), inc, ik, False, san=("www.other.test",)))) |
| 178 | |
| 179 | # finding 6: RSA policy for presented keys |
| 180 | k6144 = rsa.generate_private_key(public_exponent=65537, key_size=6144) |
| 181 | put("lX6144.der", der(build("lX6144", k6144.public_key(), root, rk, False))) |
| 182 | put("cv_x6144.sig", k6144.sign(open(os.path.join(here, "vectors", "pki", "cv.msg"), "rb").read(), |
| 183 | padding.PSS(padding.MGF1(hashes.SHA256()), 32), hashes.SHA256())) |
| 184 | k4096 = rsa.generate_private_key(public_exponent=65537, key_size=4096) |
| 185 | put("lX4096.der", der(build("lX4096", k4096.public_key(), root, rk, False))) |
| 186 | ke32 = rsa_with_e(2048, 4294967297) |
| 187 | put("lXe32.der", der(build("lXe32", ke32.public_key(), root, rk, False))) |
| 188 | ke3 = rsa.generate_private_key(public_exponent=3, key_size=2048) |
| 189 | put("lXe3.der", der(build("lXe3", ke3.public_key(), root, rk, False))) |
| 190 | n2048 = ke3.public_key().public_numbers().n |
| 191 | for nm, e in (("lXeven", 65536), ("lXe1", 1)): |
| 192 | put(nm + ".der", resign(base, rk, tbs[:6] + [rsa_spki(n2048, e), exts])) |
| 193 | i6144 = rsa.generate_private_key(public_exponent=65537, key_size=6144) |
| 194 | ci = build("intX6144", i6144.public_key(), root, rk, True) |
| 195 | put("intX6144.der", der(ci)) |
| 196 | put("lViaX6144.der", der(build("lViaX6144", lk.public_key(), ci, i6144, False))) |
| 197 | ie32 = rsa_with_e(2048, 4294967297) |
| 198 | ce = build("intXe32", ie32.public_key(), root, rk, True) |
| 199 | put("intXe32.der", der(ce)) |
| 200 | put("lViaXe32.der", der(build("lViaXe32", lk.public_key(), ce, ie32, False))) |
| 201 | |
| 202 | # omega-mv #833 suite audit (x509-limbo cases and MODEL-REVIEWED findings L2, I5) |
| 203 | bexts = [c for _, c in parse(parse(exts)[0][1])] |
| 204 | |
| 205 | |
| 206 | def oid_of(e): |
| 207 | return parse(e)[0][1][2:] |
| 208 | |
| 209 | |
| 210 | def exts_without(lst, oid_hex): |
| 211 | return [e for e in lst if oid_of(e) != bytes.fromhex(oid_hex)] |
| 212 | |
| 213 | |
| 214 | def wrap(lst): |
| 215 | return tlv(0xA3, tlv(0x30, b"".join(lst))) |
| 216 | |
| 217 | |
| 218 | put("lXsanStar.der", der(build("lXsanStar", lk.public_key(), root, rk, False, san=("*",)))) |
| 219 | sanx = [e for e in bexts if oid_of(e) == bytes.fromhex("551d11")][0] |
| 220 | put("lXdupSan.der", resign(base, rk, head + [wrap(bexts + [sanx])])) |
| 221 | put("lXdupUnk.der", resign(base, rk, head + [wrap(bexts + [ext("2a03", False, b""), ext("2a03", False, b"")])])) |
| 222 | put("lXunkCrit.der", resign(base, rk, head + [wrap(bexts + [ext("2a03", True, b"")])])) |
| 223 | for nm, ser in (("lXser0", b"\x00"), ("lXserNeg", b"\xff"), ("lXser21", b"\x01" * 21), ("lXser20", b"\x01" * 20)): |
| 224 | put(nm + ".der", resign(base, rk, [tbs[0], tlv(0x02, ser)] + tbs[2:])) |
| 225 | gt = tlv(0x30, tlv(0x18, b"20260101000000Z") + tlv(0x17, b"270101000000Z")) |
| 226 | put("lXgenTime.der", resign(base, rk, tbs[:4] + [gt] + tbs[5:])) |
| 227 | for nm, ku in (("lXku4", b"\x07\x80\x00\x00"), ("lXku3bad", b"\x00\x80\x01"), ("lXku3ok", b"\x07\x80\x80"), |
| 228 | ("lXkuCertSign", b"\x02\x84")): |
| 229 | put(nm + ".der", resign(base, rk, head + [wrap(exts_without(bexts, "551d0f") + [ext("551d0f", True, tlv(0x03, ku))])])) |
| 230 | put("lXnoAki.der", resign(base, rk, head + [wrap(exts_without(bexts, "551d23"))])) |
| 231 | esub = tbs[:5] + [tlv(0x30, b"")] + [tbs[6]] |
| 232 | sanc = ext("551d11", True, parse(sanx)[-1][1][2:]) |
| 233 | put("lXemptySubj.der", resign(base, rk, esub + [wrap(bexts)])) |
| 234 | put("lXemptySubjCrit.der", resign(base, rk, esub + [wrap(exts_without(bexts, "551d11") + [sanc])])) |
| 235 | nodd = (1 << 2051) | int.from_bytes(os.urandom(256), "big") | 1 |
| 236 | put("lXrsa2052.der", resign(base, rk, tbs[:6] + [rsa_spki(nodd, 65537), exts])) |
| 237 | # intermediate without subjectKeyIdentifier, and a leaf under it |
| 238 | ink = ec.generate_private_key(ec.SECP256R1()) |
| 239 | cin = der(build("intXnoSki", ink.public_key(), root, rk, True)) |
| 240 | ctbs = [c for _, c in parse(parse(cin)[0][1])] |
| 241 | cexts = [c for _, c in parse(parse(ctbs[7])[0][1])] |
| 242 | put("intXnoSki.der", resign(cin, rk, ctbs[:7] + [wrap(exts_without(cexts, "551d0e"))])) |
| 243 | put("lViaXnoSki.der", der(build("lViaXnoSki", lk.public_key(), x509.load_der_x509_certificate(cin), ink, False))) |
| 244 | # anchors: expired, and without basicConstraints |
| 245 | for nm, t1, drop in (("rootXexp", datetime.datetime(2026, 6, 1), None), ("rootXnoBc", R1, "551d13")): |
| 246 | k = ec.generate_private_key(ec.SECP256R1()) |
| 247 | c = der(build(nm, k.public_key(), None, k, True, R0, t1)) |
| 248 | if drop: |
| 249 | rt = [x for _, x in parse(parse(c)[0][1])] |
| 250 | re_ = [x for _, x in parse(parse(rt[7])[0][1])] |
| 251 | c = resign(c, k, rt[:7] + [wrap(exts_without(re_, drop))]) |
| 252 | cc = x509.load_der_x509_certificate(c) |
| 253 | put(nm + ".pem", cc.public_bytes(serialization.Encoding.PEM)) |
| 254 | put("lVia" + nm + ".der", der(build("lVia" + nm, lk.public_key(), cc, k, False))) |
| 255 | print(len(os.listdir(out)), "files in", out, file=sys.stderr) |