Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/om/tls/test/rsa/gen_vectors.py # 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 Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / om / tls / test / rsa / gen_vectors.py` 371 lines ยท 17153 bytes Raw Blame History 1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: Apache-2.0 3 # Test tooling for om/tls/rsa.om: converts Wycheproof RSA signature JSON to the flat vector format 4 # read by driver.om, writes the hand-built edge file, and (with --pyca) the pyca/cryptography 5 # differential file. No RSA arithmetic of the library is reimplemented here except as an oracle 6 # for the --pyca vectors (signatures come from pyca/cryptography; one large-exponent key is 7 # assembled from pyca primes with Python pow, a test oracle only). 8 # 9 # Usage: python3 gen_vectors.py WYCHEPROOF_DIR [--pyca] 10 # 11 # Line format (space separated, one case per line, '#' starts a comment line): 12 # EXP MODE CTL KEY MSG DIG SIG ID 13 # EXP 0..5 exact expected return code, or n = any nonzero (refused) 14 # MODE p = rsa_verify_pkcs1 (CTL = hash bits), s = rsa_verify_pss (CTL = packed ctl, decimal) 15 # KEY DER RSAPublicKey hex; MSG message hex ('-' empty, '*' = no message: use DIG verbatim) 16 # DIG hashlib digest of MSG with the CTL hash (cross-checked against sha2_digest by the driver) 17 # SIG signature hex ('-' empty); ID source reference, ignored by the driver 18 import hashlib 19 import json 20 import os 21 import subprocess 22 import sys 23 24 HASHES = {"SHA-256": 256, "SHA-384": 384, "SHA-512": 512} 25 HL = {256: hashlib.sha256, 384: hashlib.sha384, 512: hashlib.sha512} 26 # acceptable flags and the way rsa.om goes (documented in run.sh output and the README section) 27 ACCEPT_WAY = { 28 "MissingNull": "n", # DigestInfo without NULL: rsa.om compares the full DER block -> refused 29 "SmallModulus": "0", # 1024/1536-bit keys: accepted by the primitive; >=2048 is caller policy 30 "SmallPublicKey": "0", # e = 3: accepted (odd, >= 3) 31 "WeakHash": None, # only on SHA-1/SHA-224 groups, which are NOT_RUN 32 } 33 34 here = os.path.dirname(os.path.abspath(__file__)) 35 vdir = os.path.join(here, "vectors") 36 37 38 def hx(b): 39 return b.hex() if b else "-" 40 41 42 def ctl(h, m, s): 43 return h | (m << 16) | (s << 32) 44 45 46 def line(exp, mode, c, key, msg, dig, sig, ident): 47 return f"{exp} {mode} {c} {key} {msg} {dig} {sig} {ident}\n" 48 49 50 def dig(h, msg): 51 return HL[h](msg).hexdigest() 52 53 54 def wy_header(src, sha): 55 return (f"# source: https://github.com/C2SP/wycheproof testvectors_v1/{src}\n" 56 f"# commit: {COMMIT}\n# file sha256: {sha}\n" 57 "# license: Apache-2.0 (vectors/LICENSE.wycheproof)\n" 58 "# converted by om/tls/test/rsa/gen_vectors.py\n") 59 60 61 def scope_of(fname): 62 """('pkcs1'|'pss'|None, reason) for a testvectors_v1/rsa_* file name.""" 63 if fname.startswith("rsa_signature_"): 64 return "pkcs1", None 65 if fname.startswith("rsa_pkcs1_") and fname.endswith("_sig_gen_test.json"): 66 return "pkcs1", None 67 if fname.startswith("rsa_pss_"): 68 return "pss", None 69 if "oaep" in fname: 70 return None, "RSAES-OAEP encryption/decryption suite: not in scope (signature verification only)" 71 if fname.startswith("rsa_pkcs1_"): 72 return None, "RSAES-PKCS1-v1_5 encryption/decryption suite: not in scope (signature verification only)" 73 return None, "not an RSA signature verification suite" 74 75 76 def hash_reason(sha, mgf): 77 bad = sha if sha not in HASHES else mgf 78 name = {"SHA-1": "SHA-1", "SHA-224": "SHA-224", "SHA-512/224": "SHA-512/224", 79 "SHA-512/256": "SHA-512/256"}.get(bad, bad) 80 if bad and bad.startswith("SHA3"): 81 return f"{bad}: SHA-3 not in scope (sha2.om provides SHA-256/384/512 only)" 82 if bad and bad.startswith("SHAKE"): 83 return f"{bad}: SHAKE not in scope" 84 return f"{name}: hash not in scope (SHA-256/384/512 only)" 85 86 87 def wycheproof(wdir): 88 tv = os.path.join(wdir, "testvectors_v1") 89 os.makedirs(os.path.join(vdir, "wycheproof"), exist_ok=True) 90 notrun = [] 91 stats = {} 92 for f in sorted(os.listdir(tv)): 93 if not f.startswith("rsa_") or not f.endswith(".json"): 94 continue 95 kind, why = scope_of(f) 96 raw = open(os.path.join(tv, f), "rb").read() 97 d = json.loads(raw) 98 if kind is None: 99 notrun.append(f"{f} tests={d['numberOfTests']} reason: {why}\n") 100 continue 101 out = [] 102 skipped = {} 103 for g in d["testGroups"]: 104 sha = g["sha"] 105 mgf = g.get("mgfSha", sha) if kind == "pss" else sha 106 if kind == "pss" and g.get("mgf", "MGF1") != "MGF1": 107 r = f"hash {sha} mgf {g.get('mgf')}: SHAKE (RFC 8702 PSS) not in scope (SHA-256/384/512 with MGF1 only)" 108 skipped[r] = skipped.get(r, 0) + len(g["tests"]) 109 continue 110 if sha not in HASHES or mgf not in HASHES: 111 r = hash_reason(sha, mgf) if kind == "pkcs1" else \ 112 f"hash {sha} mgf1 {mgf}: " + hash_reason(sha, mgf) 113 skipped[r] = skipped.get(r, 0) + len(g["tests"]) 114 continue 115 key = g.get("publicKeyAsn") or g.get("keyAsn") 116 h = HASHES[sha] 117 c = h if kind == "pkcs1" else ctl(h, HASHES[mgf], g["sLen"]) 118 mode = "p" if kind == "pkcs1" else "s" 119 for t in g["tests"]: 120 res = t["result"] 121 if res == "valid": 122 exp = "0" 123 elif res == "invalid": 124 exp = "n" 125 else: 126 ways = {ACCEPT_WAY[fl] for fl in t["flags"] if ACCEPT_WAY.get(fl) is not None} 127 assert len(ways) == 1, (f, t["tcId"], t["flags"]) 128 exp = ways.pop() 129 msg = bytes.fromhex(t["msg"]) 130 ident = f"{f}#{t['tcId']}/{res}" 131 if res == "acceptable": 132 ident += "/" + "+".join(t["flags"]) 133 out.append(line(exp, mode, c, key, hx(msg), dig(h, msg), t["sig"] or "-", ident)) 134 sha = hashlib.sha256(raw).hexdigest() 135 if out: 136 name = f[:-5] + ".txt" 137 with open(os.path.join(vdir, "wycheproof", name), "w") as o: 138 o.write(wy_header(f, sha)) 139 for r, n in sorted(skipped.items()): 140 o.write(f"# NOT_RUN groups of this file: {n} tests, {r}\n") 141 o.writelines(out) 142 stats[f] = len(out) 143 for r, n in sorted(skipped.items()): 144 notrun.append(f"{f} tests={n} reason: {r}\n") 145 with open(os.path.join(vdir, "NOT_RUN.txt"), "w") as o: 146 o.write(f"# Wycheproof {COMMIT} testvectors_v1/rsa_* tests not run by om/tls/rsa.om\n") 147 o.writelines(notrun) 148 return stats 149 150 151 def der_len(n): 152 if n < 0x80: 153 return bytes([n]) 154 if n < 0x100: 155 return bytes([0x81, n]) 156 return bytes([0x82, n >> 8, n & 0xff]) 157 158 159 def der(tag, c, lenbytes=None): 160 return bytes([tag]) + (der_len(len(c)) if lenbytes is None else lenbytes) + c 161 162 163 def dint(v): 164 b = v.to_bytes(max(1, (v.bit_length() + 8) // 8), "big") 165 return b 166 167 168 def rsakey(n_c, e_c): 169 return der(0x30, der(0x02, n_c) + der(0x02, e_c)) 170 171 172 def edge(wdir): 173 """Exact-code cases built from Wycheproof rsa_pss_2048_sha256_mgf1_32 group 1 (n, e = 65537).""" 174 src = "rsa_pss_2048_sha256_mgf1_32_test.json" 175 d = json.load(open(os.path.join(wdir, "testvectors_v1", src))) 176 g = d["testGroups"][0] 177 key = bytes.fromhex(g["publicKeyAsn"]) 178 t = d["testGroups"][0]["tests"][0] 179 assert t["result"] == "valid" 180 msg = bytes.fromhex(t["msg"]) 181 sig = bytes.fromhex(t["sig"]) 182 n = int(g["publicKey"]["modulus"], 16) 183 e = int(g["publicKey"]["publicExponent"], 16) 184 k = (n.bit_length() + 7) // 8 185 c32 = ctl(256, 256, 32) 186 ncb, ecb = dint(n), dint(e) 187 cases = [] 188 189 def add(exp, mode, c, kk, s, ident, m=msg, dd=None): 190 cases.append(line(exp, mode, c, hx(kk), hx(m) if m != "*" else "*", 191 dd if dd is not None else dig(c & 0xffff, m), hx(s), "edge#" + ident)) 192 193 add("0", "s", c32, key, sig, "baseline-valid") 194 # 5: hash 195 add("5", "s", ctl(256, 1, 32), key, sig, "mgf1-hash-sha1-code") 196 add("5", "s", ctl(224, 256, 32), key, sig, "hash-224", m="*", dd="00" * 28) 197 add("5", "s", ctl(256, 256, 32), key, sig, "hlen-48-for-sha256", m="*", dd="00" * 48) 198 add("5", "p", 160, key, sig, "pkcs1-hash-160", m="*", dd="00" * 20) 199 add("5", "p", 0, key, sig, "pkcs1-hash-0", m="*", dd="00" * 32) 200 add("5", "p", 256, key, sig, "pkcs1-hlen-64-for-sha256", m="*", dd="00" * 64) 201 # 2: key encoding 202 inner = der(0x02, ncb) + der(0x02, ecb) 203 add("2", "s", c32, b"", sig, "key-empty") 204 add("2", "s", c32, b"\x31" + key[1:], sig, "key-outer-set-tag") 205 add("2", "s", c32, key + b"\x00", sig, "key-trailing-byte") 206 add("2", "s", c32, key[:-1], sig, "key-truncated") 207 add("2", "s", c32, b"\x30\x83\x00" + key[2:], sig, "key-len-3-octets-nonminimal") 208 add("2", "s", c32, b"\x30\x80" + inner + b"\x00\x00", sig, "key-indefinite-length") 209 add("2", "s", c32, der(0x30, inner + der(0x02, b"\x01")), sig, "key-extra-integer") 210 add("2", "s", c32, der(0x30, der(0x02, ncb[1:]) + der(0x02, ecb)), sig, "key-n-negative") 211 add("2", "s", c32, der(0x30, der(0x02, b"\x00" + ncb) + der(0x02, ecb)), sig, "key-n-leading-zero") 212 add("2", "s", c32, der(0x30, der(0x02, ncb) + der(0x02, b"\x00" + ecb)), sig, "key-e-leading-zero") 213 add("2", "s", c32, der(0x30, der(0x03, ncb) + der(0x02, ecb)), sig, "key-n-bitstring-tag") 214 add("2", "s", c32, der(0x30, der(0x02, ncb) + b"\x02\x81\x03" + ecb), sig, "key-e-len-81-short") 215 add("2", "s", c32, der(0x30, der(0x02, ncb) + b"\x02\x00"), sig, "key-e-empty-integer") 216 add("2", "s", c32, b"\x30\x82\x01\x0b" + inner, sig, "key-outer-len-too-long") 217 add("2", "s", c32, b"\x30\x82\x00\xff" + inner, sig, "key-outer-len-82-nonminimal") 218 add("2", "s", c32, b"\x30", sig, "key-tag-only") 219 add("2", "p", 256, b"\x30\x82\x01", sig, "key-cut-length") 220 add("2", "s", c32, der(0x30, der(0x02, ncb) + der(0x02, ecb)[:-1]), sig, "key-e-cut") 221 # 3: size / exponent 222 add("3", "s", c32, rsakey(ncb, dint(1)), sig, "e-1") 223 add("3", "s", c32, rsakey(ncb, dint(2)), sig, "e-2") 224 add("3", "s", c32, rsakey(ncb, dint(0)), sig, "e-0") 225 add("3", "s", c32, rsakey(ncb, dint(65536)), sig, "e-even") 226 add("3", "s", c32, rsakey(dint(n ^ 1), ecb), sig, "n-even") 227 add("3", "s", c32, rsakey(dint(n >> 1025), ecb), sig, "n-1023-bits") 228 add("3", "s", c32, rsakey(dint((n << 6145) | 1), ecb), sig, "n-8193-bits") 229 add("3", "s", c32, rsakey(ncb, dint((1 << 2048) + 1)), sig, "e-2049-bits-gt-n") 230 add("3", "p", 256, rsakey(dint(0), ecb), sig, "n-0") 231 # 4: signature length / range 232 add("4", "s", c32, key, sig[1:], "sig-short") 233 add("4", "s", c32, key, b"\x00" + sig, "sig-leading-zero-long") 234 add("4", "s", c32, key, b"", "sig-empty") 235 add("4", "s", c32, key, n.to_bytes(k, "big"), "sig-eq-n") 236 add("4", "p", 256, key, (n + 1).to_bytes(k, "big"), "sig-n-plus-1") 237 add("4", "s", c32, key, b"\xff" * k, "sig-all-ff") 238 add("1", "s", c32, key, (n - 1).to_bytes(k, "big"), "sig-n-minus-1") 239 add("1", "s", c32, key, b"\x00" * k, "sig-zero") 240 add("1", "p", 256, key, (1).to_bytes(k, "big"), "sig-one") 241 # 1: PSS parameter mismatch on the valid signature 242 add("1", "s", ctl(256, 256, 31), key, sig, "pss-salt-31") 243 add("1", "s", ctl(256, 256, 0), key, sig, "pss-salt-0") 244 add("1", "s", ctl(256, 256, 0xffffffff), key, sig, "pss-salt-huge") 245 add("1", "s", ctl(256, 384, 32), key, sig, "pss-mgf-sha384") 246 add("1", "p", 256, key, sig, "pss-sig-as-pkcs1") 247 with open(os.path.join(vdir, "edge.txt"), "w") as o: 248 o.write("# exact-code edge cases, built by gen_vectors.py from Wycheproof " 249 f"testvectors_v1/{src} group 1 test 1 (commit {COMMIT}, Apache-2.0)\n") 250 o.writelines(cases) 251 return len(cases) 252 253 254 def fuzz(wdir): 255 """No-trap corpus (every case must be refused, any nonzero code, never a trap): every 256 truncation of a valid key, header-byte substitutions, every signature length 0..k+2 around the 257 valid one, and seeded random PSS ctl values. Deterministic (random.Random(8017)).""" 258 import random 259 rnd = random.Random(8017) 260 src = "rsa_pss_2048_sha256_mgf1_32_test.json" 261 d = json.load(open(os.path.join(wdir, "testvectors_v1", src))) 262 g = d["testGroups"][0] 263 key = bytes.fromhex(g["publicKeyAsn"]) 264 t = g["tests"][0] 265 msg = bytes.fromhex(t["msg"]) 266 sig = bytes.fromhex(t["sig"]) 267 k = len(sig) 268 c32 = ctl(256, 256, 32) 269 out = [] 270 271 def add(mode, c, kk, s, ident): 272 out.append(line("n", mode, c, hx(kk), hx(msg), dig(c & 0xffff, msg), hx(s), "fuzz#" + ident)) 273 274 for i in range(len(key)): 275 add("s", c32, key[:i], sig, f"key-trunc-{i}") 276 heads = list(range(0, 12)) + list(range(len(key) - 8, len(key))) 277 for i in heads: 278 for v in (0x00, 0x01, 0x02, 0x30, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0xff): 279 if key[i] == v: 280 continue 281 kk = key[:i] + bytes([v]) + key[i + 1:] 282 add("s" if v & 1 else "p", c32 if v & 1 else 256, kk, sig, f"key-byte-{i}-{v:02x}") 283 for n in range(0, k + 3): 284 if n == k: 285 continue 286 s = (sig + sig)[:n] 287 add("s", c32, key, s, f"sig-len-{n}") 288 for i in range(64): 289 h = rnd.choice((256, 384, 512)) 290 m = rnd.choice((256, 384, 512)) 291 sl = rnd.choice((rnd.randrange(0, 300), rnd.randrange(0, 1 << 32))) 292 if (h, m, sl) == (256, 256, 32): 293 continue 294 add("s", ctl(h, m, sl), key, sig, f"ctl-{h}-{m}-{sl}") 295 for i in range(64): 296 kk = bytearray(key) 297 for _ in range(rnd.randrange(1, 4)): 298 kk[rnd.randrange(len(kk))] = rnd.randrange(256) 299 if bytes(kk) == key: 300 kk[0] ^= 1 301 add("s", c32, bytes(kk), sig, f"key-rand-{i}") 302 with open(os.path.join(vdir, "fuzz.txt"), "w") as o: 303 o.write("# no-trap corpus built by gen_vectors.py (random.Random(8017)) from Wycheproof " 304 f"testvectors_v1/{src} group 1 test 1 (commit {COMMIT}, Apache-2.0)\n") 305 o.writelines(out) 306 return len(out) 307 308 309 def pyca(): 310 """Odd modulus sizes and a large public exponent, signed by pyca/cryptography (test oracle).""" 311 import cryptography 312 from cryptography.hazmat.primitives import hashes, serialization 313 from cryptography.hazmat.primitives.asymmetric import padding, rsa 314 H = {256: hashes.SHA256, 384: hashes.SHA384, 512: hashes.SHA512} 315 out = [] 316 keys = [] 317 for bits, e in ((1025, 65537), (1031, 3), (2047, 65537), (2049, 65537), (2056, 3), 318 (3073, 65537), (4095, 65537), (4097, 3), (8192, 65537)): 319 keys.append((f"{bits}-e{e}", rsa.generate_private_key(e, bits))) 320 # a 2048-bit key with a 2047-bit odd public exponent, assembled from pyca primes 321 base = rsa.generate_private_key(65537, 2048).private_numbers() 322 p, q = base.p, base.q 323 lam = (p - 1) * (q - 1) 324 import math 325 import secrets 326 while True: 327 e = secrets.randbits(2047) | (1 << 2046) | 1 328 if math.gcd(e, lam) == 1: 329 break 330 dd = pow(e, -1, lam) 331 pn = rsa.RSAPublicNumbers(e, p * q) 332 big = rsa.RSAPrivateNumbers(p, q, dd, dd % (p - 1), dd % (q - 1), pow(q, -1, p), pn).private_key() 333 keys.append(("2048-e2047bits", big)) 334 for name, sk in keys: 335 pk = sk.public_key() 336 kder = pk.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.PKCS1) 337 hlen_max = {256: 32, 384: 48, 512: 64} 338 for h in (256, 384, 512): 339 for msg in (b"", b"om/tls rsa " + name.encode()): 340 s = sk.sign(msg, padding.PKCS1v15(), H[h]()) 341 out.append(line("0", "p", h, kder.hex(), hx(msg), dig(h, msg), s.hex(), 342 f"pyca#{name}/pkcs1/sha{h}")) 343 emlen = (pk.key_size - 1 + 7) // 8 344 for m in (256, 384, 512): 345 for sl in sorted({0, hlen_max[h], emlen - hlen_max[h] - 2}): 346 if sl < 0 or emlen < hlen_max[h] + sl + 2: 347 continue 348 msg = b"pss " + name.encode() 349 s = sk.sign(msg, padding.PSS(padding.MGF1(H[m]()), sl), H[h]()) 350 out.append(line("0", "s", ctl(h, m, sl), kder.hex(), hx(msg), dig(h, msg), 351 s.hex(), f"pyca#{name}/pss/sha{h}/mgf{m}/salt{sl}")) 352 with open(os.path.join(vdir, "pyca_gen.txt"), "w") as o: 353 o.write(f"# differential vectors signed by pyca/cryptography {cryptography.__version__} " 354 "(random keys; regenerate with gen_vectors.py --pyca; committed output is the test)\n" 355 "# sizes 1025 1031 2047 2049 2056 3073 4095 4097 8192 bits, e = 3 / 65537, and one " 356 "2048-bit key with a 2047-bit e\n") 357 o.writelines(out) 358 return len(out) 359 360 361 if __name__ == "__main__": 362 wdir = sys.argv[1] 363 COMMIT = subprocess.run(["git", "-C", wdir, "rev-parse", "HEAD"], capture_output=True, 364 text=True, check=True).stdout.strip() 365 os.makedirs(vdir, exist_ok=True) 366 st = wycheproof(wdir) 367 print("wycheproof", sum(st.values()), "cases in", len(st), "files") 368 print("edge", edge(wdir)) 369 print("fuzz", fuzz(wdir)) 370 if "--pyca" in sys.argv: 371 print("pyca", pyca())