interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / om / tls / test / acvp / acvp2om.py

316 lines · 13484 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3"""Convert one ACVP-Server sample vector set (gen-val/json-files/<FOLDER>/prompt.json) into records
4for acvp.om. Test-vector conversion only: no cryptography happens here. Everything the IUT computes
5(hashes, MACs, AES, signature checks, HKDF, the TLS 1.3 key schedule, X25519) is done by the .om
6library through acvp.om.
7
8usage: acvp2om.py JSONDIR FOLDER OUTDIR
9writes OUTDIR/FOLDER.in.N (record chunks, each under 15 MiB, acvp.om reads at most 16 MiB) and
10OUTDIR/FOLDER.map.json: {"records": [[id, tgId, tcId, kind], ...], "na": [[tgId, tcId, reason], ...]}.
11Every prompt test is either a record or a not-applicable entry with its reason; nothing is dropped.
12
13Conversions that are pure re-encoding of the prompt (stated in NOTES.md):
14- ECDSA: the public key as 04 || X || Y and the signature as r || s, each left-padded to the curve
15 width (the library's raw interface; ACVP gives the integers as hex).
16- RSA: the public key (n, e) as a DER RSAPublicKey (the library's key format).
17- KDA HKDF: IKM = Z || T (SP 800-56C Rev. 2 section 2: the hybrid secret Z' = Z || T) and FixedInfo
18 = uPartyInfo || vPartyInfo || L, with partyInfo = partyId || ephemeralData and L the 32-bit
19 big-endian output length in bits (the vector set's fixedInfoPattern and concatenation encoding).
20"""
21import json
22import os
23import sys
24
25CHUNK = 15 * 1024 * 1024
26SHA = {"SHA2-256": 256, "SHA2-384": 384, "SHA2-512": 512}
27CURVE = {"P-256": (256, 32), "P-384": (384, 48)}
28
29
30def h(s):
31 return s if s else "-"
32
33
34def load(jdir, folder, name):
35 with open(os.path.join(jdir, folder, name)) as f:
36 j = json.load(f)
37 return j[1] if isinstance(j, list) else j
38
39
40class Out:
41 def __init__(self):
42 self.records, self.na, self.lines = [], [], []
43
44 def rec(self, op, tg, tc, kind, fields):
45 rid = len(self.records) + 1
46 self.records.append([rid, tg, tc, kind])
47 self.lines.append(" ".join([op, str(rid)] + [str(x) for x in fields]) + "\n")
48
49 def skip(self, tg, tests, reason):
50 for t in tests:
51 self.na.append([tg, t["tcId"], reason])
52
53
54def der_len(n):
55 if n < 128:
56 return bytes([n])
57 b = n.to_bytes((n.bit_length() + 7) // 8, "big")
58 return bytes([0x80 | len(b)]) + b
59
60
61def der_int(hexs):
62 v = bytes.fromhex(hexs).lstrip(b"\0") or b"\0"
63 if v[0] & 0x80:
64 v = b"\0" + v
65 return b"\x02" + der_len(len(v)) + v
66
67
68def der_rsa(n, e):
69 body = der_int(n) + der_int(e)
70 return (b"\x30" + der_len(len(body)) + body).hex()
71
72
73def pad(hexs, width):
74 v = bytes.fromhex(hexs).lstrip(b"\0")
75 if len(v) > width:
76 return None
77 return (b"\0" * (width - len(v)) + v).hex()
78
79
80def sha2(o, p, folder):
81 alg = int(folder.split("-")[1])
82 for g in p["testGroups"]:
83 tg, tt = g["tgId"], g["testType"]
84 for t in g["tests"]:
85 if tt == "AFT":
86 if t["len"] % 8:
87 o.skip(tg, [t], "message length not a whole number of bytes (the library hashes bytes)")
88 continue
89 o.rec("H", tg, t["tcId"], "md", [alg, h(t["msg"][: t["len"] // 4])])
90 elif tt == "MCT":
91 ver = {"standard": 0, "alternate": 1}[g["mctVersion"]]
92 o.rec("M", tg, t["tcId"], "mct-md", [alg, ver, h(t["msg"][: t["len"] // 4])])
93 elif tt == "LDT":
94 m = t["largeMsg"]
95 assert m["expansionTechnique"] == "repeating" and m["contentLength"] % 8 == 0
96 assert m["fullLength"] % m["contentLength"] == 0
97 o.rec("L", tg, t["tcId"], "md", [alg, m["content"], m["fullLength"] // 8])
98 else:
99 raise SystemExit(f"unknown testType {tt}")
100
101
102def hmac(o, p, folder):
103 alg = SHA[folder.split("-", 1)[1].rsplit("-", 1)[0]]
104 for g in p["testGroups"]:
105 for t in g["tests"]:
106 kl = t.get("keyLen", g.get("keyLen"))
107 ml = t.get("msgLen", g.get("msgLen"))
108 tl = t.get("macLen", g.get("macLen"))
109 if kl % 8 or ml % 8 or tl % 8:
110 o.skip(g["tgId"], [t], "bit length not a whole number of bytes")
111 continue
112 o.rec("T", g["tgId"], t["tcId"], "mac", [alg, h(t["key"]), h(t["msg"]), tl // 8])
113
114
115def gcm(o, p, folder):
116 for g in p["testGroups"]:
117 tg = g["tgId"]
118 if g.get("ivGen") != "external":
119 o.skip(tg, g["tests"], "internal IV generation: the library takes the IV from the caller")
120 continue
121 assert g["tagLen"] % 8 == 0 and g["ivLen"] % 8 == 0
122 for t in g["tests"]:
123 if g["direction"] == "encrypt":
124 o.rec("G", tg, t["tcId"], "gcm-enc", [t["key"], t["iv"], h(t["aad"]), h(t["pt"]), g["tagLen"] // 8])
125 else:
126 o.rec("D", tg, t["tcId"], "gcm-dec", [t["key"], t["iv"], h(t["aad"]), h(t["ct"]), t["tag"]])
127
128
129def ecb(o, p, folder):
130 for g in p["testGroups"]:
131 tg = g["tgId"]
132 if g["direction"] != "encrypt":
133 o.skip(tg, g["tests"], "AES decryption (inverse cipher) is not in the library: TLS uses AES only inside GCM")
134 continue
135 for t in g["tests"]:
136 if g["testType"] == "AFT":
137 o.rec("B", tg, t["tcId"], "ecb-ct", [t["key"], t["pt"]])
138 else:
139 o.rec("C", tg, t["tcId"], "ecb-mct", [t["key"], t["pt"]])
140
141
142def ecdsa(o, p, folder):
143 for g in p["testGroups"]:
144 tg = g["tgId"]
145 if g["curve"] not in CURVE:
146 o.skip(tg, g["tests"], f"curve {g['curve']} not in the library (P-256 and P-384 only)")
147 continue
148 if g["hashAlg"] not in SHA:
149 o.skip(tg, g["tests"], f"hash {g['hashAlg']} not in the library (SHA2-256/384/512 only)")
150 continue
151 if g.get("conformance") == "SP800-106":
152 o.skip(tg, g["tests"], "SP 800-106 randomized hashing (message transformed with randomValue before "
153 "hashing): not in the library, which verifies signatures over plain SHA-2 digests as TLS 1.3 does")
154 continue
155 assert "conformance" not in g, (tg, g["conformance"])
156 crv, w = CURVE[g["curve"]]
157 for t in g["tests"]:
158 qx, qy = pad(t.get("qx", g.get("qx", "")), w), pad(t.get("qy", g.get("qy", "")), w)
159 r, s = pad(t["r"], w), pad(t["s"], w)
160 assert None not in (qx, qy, r, s), (tg, t["tcId"])
161 o.rec("E", tg, t["tcId"], "verify", [crv, SHA[g["hashAlg"]], h(t["message"]), "04" + qx + qy, r + s])
162
163
164def rsa(o, p, folder):
165 for g in p["testGroups"]:
166 tg = g["tgId"]
167 if g["sigType"] != "pkcs1v1.5":
168 why = "ANSI X9.31 signatures are not in the library" if g["sigType"] == "ansx9.31" else \
169 f"RSASSA-PSS with {g['hashAlg']}/{g.get('maskFunction', 'mgf1')}: the library's PSS takes SHA2-256/384/512 with MGF1 only"
170 if g["sigType"] == "pss" and g["hashAlg"] in SHA and g.get("maskFunction", "mgf1") == "mgf1":
171 raise SystemExit("in-scope PSS group: add a PSS record type")
172 o.skip(tg, g["tests"], why)
173 continue
174 if g["hashAlg"] not in SHA:
175 o.skip(tg, g["tests"], f"hash {g['hashAlg']} not in the library (SHA2-256/384/512 only)")
176 continue
177 key = der_rsa(g["n"], g["e"])
178 for t in g["tests"]:
179 o.rec("R", tg, t["tcId"], "verify", [SHA[g["hashAlg"]], key, h(t["message"]), t["signature"]])
180
181
182def party(pi):
183 return pi["partyId"] + pi.get("ephemeralData", "")
184
185
186def kda(o, p, folder):
187 for g in p["testGroups"]:
188 tg, val = g["tgId"], g["testType"] == "VAL"
189 multi = g.get("multiExpansion", False)
190 cfg = g["kdfMultiExpansionConfiguration"] if multi else g["kdfConfiguration"]
191 assert cfg["kdfType"] == "hkdf"
192 if cfg["hmacAlg"] not in SHA:
193 o.skip(tg, g["tests"], f"HMAC {cfg['hmacAlg']} not in the library (SHA2-256/384/512 only)")
194 continue
195 alg = SHA[cfg["hmacAlg"]]
196 if not multi:
197 assert cfg["fixedInfoPattern"] == "uPartyInfo||vPartyInfo||l" and cfg["fixedInfoEncoding"] == "concatenation"
198 for t in g["tests"]:
199 if multi:
200 kp = t["kdfMultiExpansionParameter"]
201 assert kp["hmacAlg"] == cfg["hmacAlg"]
202 its = [(i["fixedInfo"], i["l"]) for i in kp["iterationParameters"]]
203 else:
204 kp = t["kdfParameter"]
205 fi = party(t["fixedInfoPartyU"]) + party(t["fixedInfoPartyV"]) + kp["l"].to_bytes(4, "big").hex()
206 its = [(fi, kp["l"])]
207 assert all(l % 8 == 0 for _, l in its)
208 ikm = kp["z"] + kp.get("t", "")
209 fields = [alg, h(kp["salt"]), h(ikm), len(its)]
210 if val:
211 dkms = t["dkms"] if multi else [t["dkm"]]
212 for (fi, l), d in zip(its, dkms):
213 fields += [h(fi), l // 8, h(d)]
214 o.rec("V", tg, t["tcId"], "kda-val", fields)
215 else:
216 for fi, l in its:
217 fields += [h(fi), l // 8]
218 o.rec("K", tg, t["tcId"], "kda-multi" if multi else "kda", fields)
219
220
221def tls13(o, p, folder):
222 for g in p["testGroups"]:
223 tg, mode = g["tgId"], g["runningMode"]
224 alg = SHA[g["hmacAlg"]]
225 for t in g["tests"]:
226 psk = t.get("psk", "") if "PSK" in mode else ""
227 dhe = t.get("dhe", "") if "DHE" in mode else ""
228 msgs = [t["helloClientRandom"], t["helloServerRandom"], t["finishedServerRandom"], t["finishedClientRandom"]]
229 o.rec("S", tg, t["tcId"], "tls13", [alg, h(psk), h(dhe)] + [h(m) for m in msgs])
230 if alg == 256 and len(psk) == 64 and len(dhe) == 64:
231 o.rec("N", tg, t["tcId"], "tls13-native", [psk, dhe] + [h(m) for m in msgs[:3]])
232
233
234def xecdh(o, p, folder, ip):
235 priv = {(g["tgId"], t["tcId"]): t["privateIut"] for g in ip["testGroups"] for t in g["tests"]}
236 for g in p["testGroups"]:
237 tg = g["tgId"]
238 if g["curve"] != "Curve25519":
239 o.skip(tg, g["tests"], f"{g['curve']} not in the library (X25519 only)")
240 continue
241 for t in g["tests"]:
242 o.rec("X", tg, t["tcId"], "xecdh", [priv[(tg, t["tcId"])], t["publicServer"]])
243
244
245def kasecc(o, p, folder):
246 for g in p["testGroups"]:
247 crv = g["domainParameterGenerationMode"]
248 if crv in ("P-256", "P-384"):
249 raise SystemExit(f"KAS-ECC group {g['tgId']} on {crv}: wire it to ecdh.om before running")
250 o.skip(g["tgId"], g["tests"], f"KAS-ECC {g['scheme']} on {crv}: the library implements SP 800-56A "
251 "ECC CDH only on P-256/P-384 (ecdh.om, approved mode); this sample group uses another curve")
252
253
254def mlkem(o, p, folder):
255 for g in p["testGroups"]:
256 tg = g["tgId"]
257 if g["parameterSet"] != "ML-KEM-768":
258 o.skip(tg, g["tests"], f"{g['parameterSet']} not in the library (ML-KEM-768 only)")
259 continue
260 fn = g.get("function", "keyGen")
261 for t in g["tests"]:
262 if fn == "keyGen":
263 o.rec("Q", tg, t["tcId"], "mlkem-keygen", [t["d"], t["z"]])
264 elif fn == "encapsulation":
265 o.rec("P", tg, t["tcId"], "mlkem-encap", [t["ek"], t["m"]])
266 elif fn == "decapsulation":
267 o.rec("U", tg, t["tcId"], "mlkem-decap", [t["dk"], t["c"]])
268 elif fn == "decapsulationKeyCheck":
269 o.rec("Y", tg, t["tcId"], "mlkem-check", [t["dk"]])
270 elif fn == "encapsulationKeyCheck":
271 o.rec("Z", tg, t["tcId"], "mlkem-check", [t["ek"]])
272 else:
273 raise SystemExit(f"unknown ML-KEM function {fn}")
274
275
276HANDLERS = [("SHA2-", sha2), ("HMAC-SHA2-", hmac), ("ACVP-AES-GCM", gcm), ("ACVP-AES-ECB", ecb),
277 ("ECDSA-SigVer", ecdsa), ("RSA-SigVer", rsa), ("KDA-HKDF", kda), ("TLS-v1.3-KDF", tls13),
278 ("KAS-ECC-SSC", kasecc), ("ML-KEM-", mlkem)]
279
280
281def main():
282 jdir, folder, outdir = sys.argv[1:4]
283 p = load(jdir, folder, "prompt.json")
284 o = Out()
285 if folder.startswith("XECDH"):
286 xecdh(o, p, folder, load(jdir, folder, "internalProjection.json"))
287 else:
288 fn = [f for pre, f in HANDLERS if folder.startswith(pre)]
289 if not fn:
290 raise SystemExit(f"no converter for {folder}")
291 fn[0](o, p, folder)
292 ntests = sum(len(g["tests"]) for g in p["testGroups"])
293 covered = {(r[1], r[2]) for r in o.records} | {(n[0], n[1]) for n in o.na}
294 assert len(covered) == ntests, (folder, len(covered), ntests)
295 os.makedirs(outdir, exist_ok=True)
296 for f in os.listdir(outdir):
297 if f.startswith(folder + ".in."):
298 os.remove(os.path.join(outdir, f))
299 chunk, size, k = [], 0, 0
300 for line in o.lines + [None]:
301 if line is None or (chunk and size + len(line) > CHUNK):
302 if chunk:
303 with open(os.path.join(outdir, f"{folder}.in.{k}"), "w") as f:
304 f.writelines(chunk)
305 k += 1
306 chunk, size = [], 0
307 if line is not None:
308 chunk.append(line)
309 size += len(line)
310 with open(os.path.join(outdir, f"{folder}.map.json"), "w") as f:
311 json.dump({"folder": folder, "prompt_tests": ntests, "records": o.records, "na": o.na}, f)
312 print(f"{folder} tests={ntests} records={len(o.records)} not_applicable={len(o.na)} chunks={k}")
313
314
315if __name__ == "__main__":
316 main()