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/net/hostile.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 / net / hostile.py` 600 lines ยท 23364 bytes Raw Blame History 1 #!/usr/bin/env python3 2 # SPDX-License-Identifier: Apache-2.0 3 # Test tooling only: a scripted hostile TLS 1.3 server for the om/tls client (Omega has no TLS 4 # server, so every misbehaviour is driven from this side). One connection on 127.0.0.1:PORT, 5 # x25519 + TLS_CHACHA20_POLY1305_SHA256, written on python3 `cryptography` with its own record 6 # layer so every byte can be bent. The PKI comes from DIR (hostile.sh writes it): root.pem, 7 # int.pem, good.pem/good.key (EC P-256 leaf for localhost), rsa.pem/rsa.key (RSA-2048 leaf), 8 # other.key (an unrelated EC key). 9 # usage: hostile.py PORT DIR CASE (CASE: a row of hostile.tsv, or ch_policy) 10 # hostile.py PORT DIR replay CHAINPEM (badssl.sh: present CHAINPEM, then a CertificateVerify 11 # made with good.key, which is never the leaf's key) 12 # Prints "READY" once listening, then "SRV key=value ..." facts about what the client sent: 13 # alert=N (the client's alert description, decrypted when it was protected; none when it closed 14 # without one), cfin=ok|bad|none (the client Finished checked against our transcript), 15 # ccert=empty|none|other, req=1 (an HTTP request arrived), ku=N (client KeyUpdates). 16 import hashlib, hmac, os, socket, sys, threading, time 17 from cryptography import x509 18 from cryptography.hazmat.primitives import hashes, serialization 19 from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa 20 from cryptography.hazmat.primitives.asymmetric.utils import decode_dss_signature, encode_dss_signature 21 from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey 22 from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 23 24 port, d, mode = int(sys.argv[1]), sys.argv[2], sys.argv[3] 25 chainpem = sys.argv[4] if mode == "replay" else None 26 u = lambda n, k: n.to_bytes(k, "big") 27 H = lambda b: hashlib.sha256(b).digest() 28 ext = lambda t, b: u(t, 2) + u(len(b), 2) + b 29 hmsg = lambda t, b: bytes([t]) + u(len(b), 3) + b 30 rec = lambda t, b, v=b"\x03\x03": bytes([t]) + v + u(len(b), 2) + b 31 CCS = rec(20, b"\x01") 32 facts = {} 33 34 35 def say(**kw): 36 facts.update(kw) 37 38 39 def expand_label(secret, label, ctx, n): 40 info = u(n, 2) + bytes([6 + len(label)]) + b"tls13 " + label + bytes([len(ctx)]) + ctx 41 out, t, i = b"", b"", 1 42 while len(out) < n: 43 t = hmac.new(secret, t + info + bytes([i]), hashlib.sha256).digest() 44 out += t; i += 1 45 return out[:n] 46 47 48 extract = lambda salt, ikm: hmac.new(salt, ikm, hashlib.sha256).digest() 49 50 51 class Keys: 52 def __init__(self, secret): 53 self.secret = secret 54 self.aead = ChaCha20Poly1305(expand_label(secret, b"key", b"", 32)) 55 self.iv = expand_label(secret, b"iv", b"", 12) 56 self.seq = 0 57 58 def nonce(self): 59 n = bytes(a ^ b for a, b in zip(self.iv, u(self.seq, 12))) 60 self.seq += 1 61 return n 62 63 # seal: inner = data || type || pad zeros; outer type and a raw inner override for tests 64 def seal(self, ctype, data, pad=0, outer=23, inner=None): 65 if inner is None: 66 inner = data + bytes([ctype]) + bytes(pad) 67 hdr = bytes([outer]) + b"\x03\x03" + u(len(inner) + 16, 2) 68 return hdr + self.aead.encrypt(self.nonce(), inner, hdr) 69 70 def open(self, r): 71 inner = self.aead.decrypt(self.nonce(), r[5:], r[:5]).rstrip(b"\x00") 72 return inner[-1], inner[:-1] 73 74 75 # A reader thread drains the socket as bytes arrive: a client that aborts with our later records 76 # still unread closes with a TCP RST, and the kernel drops whatever the server had not yet read, 77 # which would lose the client's alert. 78 inbuf = {"b": b"", "eof": False} 79 cv_in = threading.Condition() 80 81 82 def reader(c): 83 while True: 84 try: 85 b = c.recv(65536) 86 except OSError: 87 b = b"" 88 with cv_in: 89 if not b: 90 inbuf["eof"] = True 91 inbuf["b"] += b 92 cv_in.notify_all() 93 if not b: 94 return 95 96 97 def take(n): 98 with cv_in: 99 cv_in.wait_for(lambda: len(inbuf["b"]) >= n or inbuf["eof"], timeout=20) 100 if len(inbuf["b"]) < n: 101 return None 102 out, inbuf["b"] = inbuf["b"][:n], inbuf["b"][n:] 103 return out 104 105 106 def recv_record(c): 107 h = take(5) 108 if h is None: 109 return None 110 b = take(int.from_bytes(h[3:5], "big")) 111 return None if b is None else h + b 112 113 114 def send(c, b): 115 try: 116 c.sendall(b) 117 return True 118 except OSError: 119 return False 120 121 122 def paced(b, quiet=True): 123 """send one record at a time and stop once the client has aborted, so it never closes with our 124 records unread (that close is a TCP RST, which can drop its alert before we read it). 125 quiet: the client writes nothing while we send (handshake flight), so any byte from it means it 126 aborted; otherwise (after the handshake, where it may answer a KeyUpdate) only its close counts.""" 127 # the client's middlebox-compatibility ChangeCipherSpec (RFC 8446 D.4) is not an abort 128 noccs = lambda: inbuf["b"].replace(b"\x14\x03\x03\x00\x01\x01", b"") 129 done = (lambda: noccs() or inbuf["eof"]) if quiet else (lambda: inbuf["eof"]) 130 while b: 131 n = 5 + int.from_bytes(b[3:5], "big") 132 with cv_in: 133 if done(): 134 return 135 if not send(c, b[:n]): 136 return 137 b = b[n:] 138 with cv_in: 139 cv_in.wait_for(done, timeout=0.05) 140 141 ls = socket.socket(); ls.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 142 ls.bind(("127.0.0.1", port)); ls.listen(1) 143 print("READY", flush=True) 144 c, _ = ls.accept() 145 c.settimeout(20) 146 threading.Thread(target=reader, args=(c,), daemon=True).start() 147 148 # ---- ClientHello ---- 149 r = recv_record(c) 150 ch = r[5:] 151 p = 4 + 2 + 32 152 sid = ch[p + 1:p + 1 + ch[p]] 153 p += 1 + ch[p] 154 suites = [int.from_bytes(ch[p + 2 + i:p + 4 + i], "big") for i in range(0, int.from_bytes(ch[p:p + 2], "big"), 2)] 155 p += 2 + int.from_bytes(ch[p:p + 2], "big") 156 comps = list(ch[p + 1:p + 1 + ch[p]]) 157 p += 1 + ch[p] 158 end = p + 2 + int.from_bytes(ch[p:p + 2], "big") 159 p += 2 160 cpub, exts, extbody = None, [], {} 161 while p < end: 162 t, n = int.from_bytes(ch[p:p + 2], "big"), int.from_bytes(ch[p + 2:p + 4], "big") 163 exts.append(t); extbody[t] = ch[p + 4:p + 4 + n] 164 if t == 51: 165 q = p + 6 166 while q < p + 4 + n: 167 g, kn = int.from_bytes(ch[q:q + 2], "big"), int.from_bytes(ch[q + 2:q + 4], "big") 168 if g == 0x1d: 169 cpub = ch[q + 4:q + 4 + kn] 170 q += 4 + kn 171 p += 4 + n 172 lst = lambda b, w, o: [int.from_bytes(b[o + i:o + i + w], "big") for i in range(0, len(b) - o, w)] 173 174 if mode == "ch_policy": 175 # ClientHello policy (no handshake): what can ever be negotiated with this client 176 sv = lst(extbody.get(43, b"\x00"), 2, 1) 177 groups = lst(extbody.get(10, b"\x00\x00"), 2, 2) 178 sigs = lst(extbody.get(13, b"\x00\x00"), 2, 2) 179 ks = [] 180 kb = extbody.get(51, b"\x00\x00") 181 q = 2 182 while q < len(kb): 183 ks.append(int.from_bytes(kb[q:q + 2], "big")); q += 4 + int.from_bytes(kb[q + 2:q + 4], "big") 184 bad = [] 185 if ch[4:6] != b"\x03\x03": bad.append("legacy_version") 186 if sv != [0x0304]: bad.append("supported_versions") 187 if not set(suites) <= {0x1301, 0x1302, 0x1303}: bad.append("suites") 188 if comps != [0]: bad.append("compression") 189 if not set(groups) <= {0x1d, 0x17, 0x18, 0x11ec, 0x6399}: bad.append("groups") 190 if any(s in (0x0201, 0x0203, 0x0202) for s in sigs): bad.append("sha1_sigalgs") 191 if 41 in exts or 42 in exts or 45 in exts: bad.append("psk_or_early_data") 192 if len(sid) != 32: bad.append("session_id") 193 print("SRV ch_policy versions=%s suites=%s comp=%s groups=%s key_shares=%s sigalgs=%s exts=%s bad=%s" 194 % (",".join("%04x" % x for x in sv), ",".join("%04x" % x for x in suites), comps, 195 ",".join("%04x" % x for x in groups), ",".join("%04x" % x for x in ks), 196 ",".join("%04x" % x for x in sigs), ",".join(str(x) for x in exts), ",".join(bad) or "none"), flush=True) 197 send(c, rec(21, b"\x02\x28")) 198 c.close(); sys.exit(0) 199 200 # ---- ServerHello ---- 201 sk = X25519PrivateKey.generate() 202 spub = sk.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) 203 shared = sk.exchange(X25519PublicKey.from_public_bytes(cpub)) 204 share = spub 205 if mode == "sh_ks_hibit": 206 share = spub[:31] + bytes([spub[31] | 0x80]) # RFC 7748 section 5: the receiver masks bit 255 207 if mode == "sh_ks_lo1": 208 share = b"\x01" + bytes(31) 209 if mode == "sh_ks_lo8": 210 share = bytes.fromhex("`e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800`") 211 ks = ext(51, b"\x00\x1d\x00\x20" + share) 212 if mode == "sh_kslen31": 213 ks = ext(51, b"\x00\x1d\x00\x1f" + share[:31]) 214 sv = ext(43, {"sh_sv0303": b"\x03\x03", "sh_sv7f": b"\x7f\x1c"}.get(mode, b"\x03\x04")) 215 if mode == "sh_svlen": 216 sv = ext(43, b"\x03\x04\x00") 217 shx = {"sh_noks": sv, "sh_dupks": sv + ks + ks, 218 "sh_ext_unsol": sv + ks + ext(0x0a0a, b""), "sh_ext_psk": sv + ks + ext(41, b"\x00\x00"), 219 "sh_ext_sni": sv + ks + ext(0, b""), "sh_ext_cookie": sv + ks + ext(44, b"\x00\x02ab"), 220 "sh_ext_early": sv + ks + ext(42, b""), 221 "sh_ext_ksalias": sv + ext(0x0a0a, ks[4:]), 222 "sh_dgrd12": ks, "sh_dgrd11": ks}.get(mode, sv + ks) 223 rnd = os.urandom(32) 224 if mode == "sh_dgrd12": 225 rnd = rnd[:24] + b"DOWNGRD\x01" 226 if mode == "sh_dgrd11": 227 rnd = rnd[:24] + b"DOWNGRD\x00" 228 legacy = {"sh_dgrd11": b"\x03\x02"}.get(mode, b"\x03\x03") 229 sidf = bytes([len(sid)]) + sid 230 if mode == "sh_sid33": 231 sidf = b"\x21" + sid + b"\x00" 232 suite = {"sh_suite_tls12": b"\xc0\x2f"}.get(mode, b"\x13\x03") 233 comp = b"\x01" if mode == "sh_comp1" else b"\x00" 234 extlen = u(len(shx) + (5 if mode == "sh_extlen" else 0), 2) 235 body = legacy + rnd + sidf + suite + comp + extlen + shx 236 sh = hmsg(2, body) 237 238 pre = b"" 239 if mode == "rec_unknown_type": 240 pre = rec(0x63, b"\x00\x01") 241 if mode == "rec_appdata_plain": 242 pre = rec(23, b"GET") 243 if mode == "rec_alert_frag": 244 pre = rec(21, b"\x02") 245 if mode == "rec_alert_zero": 246 pre = rec(21, b"") 247 if mode == "rec_alert_unknown_plain": 248 pre = rec(21, b"\x02\xc8") 249 if mode == "sh_hs_zero": 250 pre = rec(22, b"") 251 if mode == "rec_overflow_plain": 252 shrec = rec(22, sh + bytes(16385 - len(sh))) # 2^14 + 1 bytes of plaintext fragment 253 elif mode == "sh_twice": 254 shrec = rec(22, sh + sh) 255 elif mode == "sh_split": 256 shrec = rec(22, sh[:40]) + rec(22, sh[40:]) 257 elif mode == "sh_rec0301": 258 shrec = rec(22, sh, b"\x03\x01") 259 else: 260 shrec = rec(22, sh) 261 tr = ch + sh 262 early = extract(bytes(32), bytes(32)) 263 hs = extract(expand_label(early, b"derived", H(b""), 32), shared) 264 s_hs = expand_label(hs, b"s hs traffic", H(tr), 32) 265 c_hs = expand_label(hs, b"c hs traffic", H(tr), 32) 266 sw = Keys(s_hs) 267 268 # the client's records: plaintext alerts, then protected under c_hs, then c_ap (set later) 269 cr_state = {"keys": [Keys(c_hs)], "alert": None} 270 271 272 def client_records(until, limit=4000): 273 """read the client's records; until(type, data) returns True to stop. EOF/timeout stops.""" 274 for _ in range(limit): 275 try: 276 r = recv_record(c) 277 except OSError: 278 return False 279 if r is None: 280 return False 281 t = r[0] 282 if t == 20: 283 continue 284 if t == 21: 285 cr_state["alert"] = r[6] if len(r) > 6 else -1 286 say(alert=cr_state["alert"]) 287 return False 288 if t == 23: 289 ok = False 290 for k in list(cr_state["keys"]): 291 seq = k.seq 292 try: 293 it, data = k.open(r) 294 ok = True 295 break 296 except Exception: 297 k.seq = seq 298 if not ok: 299 say(undecryptable=1) 300 continue 301 if it == 21: 302 cr_state["alert"] = data[1] if len(data) > 1 else -1 303 say(alert=cr_state["alert"]) 304 return False 305 if until(it, data): 306 return True 307 return False 308 309 310 if mode == "sh_plus_ee": 311 shrec = rec(22, sh + hmsg(8, b"\x00\x00")) 312 paced(pre + shrec) 313 ccs = {"ccs_val2": rec(20, b"\x02"), "ccs_len2": rec(20, b"\x01\x01"), "ccs_zero": rec(20, b"")}.get(mode, CCS) 314 paced(ccs) 315 316 # ---- encrypted flight ---- 317 def cert_msg(ders, ctx=b"", entry_ext=b""): 318 cl = b"".join(u(len(x), 3) + x + u(len(entry_ext), 2) + entry_ext for x in ders) 319 return hmsg(11, bytes([len(ctx)]) + ctx + u(len(cl), 3) + cl) 320 321 322 def load_ders(path): 323 data = open(path, "rb").read() 324 out = [] 325 for blk in data.split(b"-----END CERTIFICATE-----")[:-1]: 326 out.append(x509.load_pem_x509_certificate(blk + b"-----END CERTIFICATE-----\n").public_bytes(serialization.Encoding.DER)) 327 return out 328 329 330 ee_exts = {"ee_ks": ext(51, b"\x00\x1d\x00\x20" + spub), "ee_sv": ext(43, b"\x03\x04"), 331 "ee_psk": ext(41, b"\x00\x00"), "ee_dup": ext(0, b"") + ext(0, b""), 332 "ee_unsol": ext(0x0a0a, b""), "ee_mfl": ext(1, b"\x01"), 333 "ee_alpn_other": ext(16, b"\x00\x03\x02h2"), 334 "ee_alpn_two": ext(16, b"\x00\x0c\x08http/1.1\x02h2")}.get(mode, b"") 335 ee = hmsg(8, u(len(ee_exts), 2) + ee_exts + (b"\x00" if mode == "ee_trail" else b"")) 336 if mode == "ee_bigdecl": 337 ee = b"\x08\xff\xff\xff" + bytes(64) 338 rsaleaf = mode in ("cv_pkcs1",) 339 if mode == "replay": 340 ders = load_ders(chainpem) 341 else: 342 ders = load_ders(f"{d}/{'rsa' if rsaleaf else 'good'}.pem") + load_ders(f"{d}/int.pem") 343 cctx, eext = b"", b"" 344 if mode == "cert_ctx": 345 cctx = b"\x01\x02" 346 if mode == "cert_entry_ext": 347 eext = ext(0x0a0a, b"") 348 cert = cert_msg(ders, cctx, eext) 349 if mode == "cert_empty": 350 cert = hmsg(11, b"\x00\x00\x00\x00") 351 if mode == "cert_zero_entry": 352 cert = hmsg(11, b"\x00" + u(5, 3) + b"\x00\x00\x00\x00\x00") 353 if mode == "cert_list_overrun": 354 cert = cert[:5] + u(int.from_bytes(cert[5:8], "big") + 10, 3) + cert[8:] 355 cr = b"" 356 if mode in ("cr_hs", "cr_ctx", "cr_nosigalgs"): 357 crx = b"" if mode == "cr_nosigalgs" else ext(13, b"\x00\x04\x04\x03\x08\x04") 358 cr = hmsg(13, (b"\x02ab" if mode == "cr_ctx" else b"\x00") + u(len(crx), 2) + crx) 359 360 361 def cv_msg(trans): 362 content = b" " * 64 + b"TLS 1.3, " + (b"client" if mode == "cv_ctxclient" else b"server") + b" CertificateVerify\x00" + H(trans) 363 if mode == "cv_pkcs1": 364 key = serialization.load_pem_private_key(open(f"{d}/rsa.key", "rb").read(), None) 365 return hmsg(15, b"\x04\x01" + u(256, 2) + key.sign(content, padding.PKCS1v15(), hashes.SHA256())) 366 key = serialization.load_pem_private_key(open(f"{d}/good.key", "rb").read(), None) 367 sig = key.sign(content, ec.ECDSA(hashes.SHA256())) 368 if mode == "cv_highs": 369 r_, s_ = decode_dss_signature(sig) 370 n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 371 sig = encode_dss_signature(r_, n - s_) 372 scheme = {"cv_unoffered": b"\x06\x03", "cv_keymismatch": b"\x08\x04"}.get(mode, b"\x04\x03") 373 if mode == "cv_empty": 374 sig = b"" 375 return hmsg(15, scheme + u(len(sig), 2) + sig + (b"\x00" if mode == "cv_trail" else b"")) 376 377 378 fl = [] # (kind, message) in order; kind "hs" is sealed as handshake 379 order = ["ee", "cr", "cert", "cv", "fin"] 380 if mode == "order_cert_first": 381 order = ["cert", "ee", "cv", "fin"] 382 if mode == "order_fin_noauth": 383 order = ["ee", "fin"] 384 if mode == "order_cv_first": 385 order = ["ee", "cv", "cert", "fin"] 386 if mode == "ee_twice": 387 order = ["ee", "ee", "cert", "cv", "fin"] 388 if mode == "cv_twice": 389 order = ["ee", "cert", "cv", "cv", "fin"] 390 msgs = [] 391 for k in order: 392 if k == "ee": 393 m = ee 394 elif k == "cr": 395 if not cr: 396 continue 397 m = cr 398 elif k == "cert": 399 m = cert 400 elif k == "cv": 401 m = cv_msg(tr) 402 else: 403 vd = hmac.new(expand_label(s_hs, b"finished", b"", 32), H(tr), hashlib.sha256).digest() 404 if mode == "fin_bad": 405 vd = vd[:5] + bytes([vd[5] ^ 1]) + vd[6:] 406 if mode == "fin_short": 407 vd = vd[:31] 408 if mode == "fin_long": 409 vd = vd + b"\x00" 410 m = hmsg(20, vd) 411 tr += m 412 msgs.append(m) 413 fin = msgs[-1] 414 415 # application secrets (only meaningful when the transcript above is the real one) 416 ms = extract(expand_label(hs, b"derived", H(b""), 32), bytes(32)) 417 s_ap = expand_label(ms, b"s ap traffic", H(tr), 32) 418 c_ap = expand_label(ms, b"c ap traffic", H(tr), 32) 419 aw = Keys(s_ap) 420 out = b"" 421 if mode == "hs_coalesce": 422 out += sw.seal(22, b"".join(msgs)) 423 elif mode == "hs_frag_ee": 424 out += sw.seal(22, msgs[0][:3]) + sw.seal(22, msgs[0][3:]) + b"".join(sw.seal(22, m) for m in msgs[1:]) 425 elif mode == "fin_plus_nst": 426 nst = hmsg(4, u(60, 4) + u(1, 4) + b"\x01\x00" + u(2, 2) + b"tk" + b"\x00\x00") 427 out += b"".join(sw.seal(22, m) for m in msgs[:-1]) + sw.seal(22, fin + nst) 428 else: 429 for i, m in enumerate(msgs): 430 if mode == "hs_pad_big" and i == 0: 431 out += sw.seal(22, m, pad=16000) 432 elif mode == "rec_allzero" and i == 0: 433 out += sw.seal(0, b"", inner=bytes(40)) 434 elif mode == "rec_innertype_unk" and i == 0: 435 out += sw.seal(0x63, m) 436 elif mode == "rec_overflow_cipher" and i == 0: 437 out += sw.seal(22, m, pad=16384 + 256 + 1 - 16 - len(m) - 1) # ciphertext 2^14+256+1 438 elif mode == "rec_overflow_inner" and i == 0: 439 out += sw.seal(22, m, pad=16386 - len(m) - 1) # inner 2^14+2 440 elif mode == "rec_short" and i == 0: 441 out += b"\x17\x03\x03\x00\x05" + os.urandom(5) 442 elif mode == "rec_replay" and i == 0: 443 rr = sw.seal(22, m) 444 out += rr + rr 445 elif mode == "rec_outer_type22" and i == 0: 446 out += sw.seal(22, m, outer=22) 447 elif mode == "hs_appdata_early" and i == 1: 448 out += sw.seal(23, b"early") + sw.seal(22, m) 449 elif mode == "hs_plain_alert" and i == 1: 450 out += rec(21, b"\x02\x28") + sw.seal(22, m) 451 elif mode == "ee_zero_frag" and i == 0: 452 out += sw.seal(22, b"") + sw.seal(22, m) 453 else: 454 # a message over 2^14 (a replayed big chain) goes out in 2^14-byte records (5.1) 455 out += b"".join(sw.seal(22, m[k:k + 16384]) for k in range(0, len(m), 16384)) 456 paced(out) 457 if mode == "fin_twice": 458 # after our Finished the client legitimately writes its own flight, which stops paced(); the 459 # second Finished must still go out (it is the case) and its sequence number must be used 460 send(c, aw.seal(22, hmsg(20, bytes(32)))) 461 462 # ---- the client's flight: [Certificate], Finished, then the request under c_ap ---- 463 ctr = tr 464 st = {"fin": False, "req": b"", "ku": 0} 465 466 467 def on_hs(it, data): 468 global ctr 469 if it != 22: 470 say(cunexpected=it) 471 return True 472 q = 0 473 while q + 4 <= len(data): 474 ht, hl = data[q], int.from_bytes(data[q + 1:q + 4], "big") 475 m = data[q:q + 4 + hl] 476 if ht == 11: 477 say(ccert="empty" if m[4 + 1 + m[4]:] == b"\x00\x00\x00" else "other") 478 ctr += m 479 elif ht == 20: 480 want = hmac.new(expand_label(c_hs, b"finished", b"", 32), H(ctr), hashlib.sha256).digest() 481 say(cfin="ok" if m[4:] == want else "bad") 482 st["fin"] = True 483 return True 484 else: 485 say(chs=ht) 486 q += 4 + hl 487 return False 488 489 490 ok = client_records(on_hs) 491 if not ok or not st["fin"]: 492 facts.setdefault("cfin", "none") 493 print("SRV " + " ".join("%s=%s" % kv for kv in facts.items()), flush=True) 494 c.close(); sys.exit(0) 495 ar = Keys(c_ap) 496 cr_state["keys"] = [ar] 497 capk = [c_ap] 498 499 500 def on_app(it, data): 501 if it == 22 and data[:1] == b"\x18": 502 st["ku"] += 1 503 capk[0] = expand_label(capk[0], b"traffic upd", b"", 32) 504 cr_state["keys"][0] = Keys(capk[0]) 505 return False 506 if it == 23: 507 st["req"] += data 508 return b"\r\n\r\n" in st["req"] 509 say(capp=it) 510 return True 511 512 513 client_records(on_app) 514 say(req=int(b"\r\n\r\n" in st["req"])) 515 REPLY = b"HTTP/1.0 200 ok\r\ncontent-length: 3\r\n\r\nok\n" 516 517 518 def reply(w): 519 return w.seal(23, REPLY) + w.seal(21, b"\x01\x00") 520 521 522 nst = hmsg(4, u(60, 4) + u(1, 4) + b"\x01\x00" + u(2, 2) + b"tk" + b"\x00\x00") 523 o, tail = b"", b"" 524 if mode == "post_cr": 525 o = aw.seal(22, hmsg(13, b"\x02ab\x00\x08" + ext(13, b"\x00\x02\x04\x03"))) + reply(aw) 526 elif mode == "post_unknown_hs": 527 o = aw.seal(22, hmsg(99, b"\x00\x00")) + reply(aw) 528 elif mode == "post_sh": 529 o = aw.seal(22, sh) + reply(aw) 530 elif mode == "post_ku_req": 531 o = aw.seal(22, hmsg(24, b"\x01")) 532 s2 = expand_label(s_ap, b"traffic upd", b"", 32); aw = Keys(s2) 533 o += reply(aw) 534 elif mode == "post_ku_bad": 535 o = aw.seal(22, hmsg(24, b"\x02")) + reply(aw) 536 elif mode == "post_ku_len": 537 o = aw.seal(22, hmsg(24, b"\x00\x00")) + reply(aw) 538 elif mode == "post_ku_flood": 539 s2 = s_ap 540 for _ in range(1001): # tls_read gives up after 1001 records without data 541 o += aw.seal(22, hmsg(24, b"\x01")) 542 s2 = expand_label(s2, b"traffic upd", b"", 32); aw = Keys(s2) 543 tail = reply(aw) 544 elif mode == "post_nst_split": 545 o = aw.seal(22, nst[:7]) + aw.seal(22, nst[7:]) + reply(aw) 546 elif mode == "post_interleave": 547 o = aw.seal(22, nst[:7]) + aw.seal(23, b"x") + aw.seal(22, nst[7:]) + reply(aw) 548 elif mode == "post_nst_trail": 549 o = aw.seal(22, hmsg(4, nst[4:] + b"\x00")) + reply(aw) 550 elif mode == "post_plain_close": 551 o = aw.seal(23, b"HTTP/1.0 200 ok\r\ncontent-length: 100\r\n\r\npart") + rec(21, b"\x01\x00") 552 elif mode == "post_trunc": 553 o = aw.seal(23, b"HTTP/1.0 200 ok\r\ncontent-length: 100\r\n\r\npart") 554 elif mode == "post_trunc_full": 555 o = aw.seal(23, REPLY) 556 elif mode == "post_alert_unknown": 557 o = aw.seal(23, b"HTTP/1.0 200 ok\r\n") + aw.seal(21, b"\x02\xc8") 558 elif mode == "post_alert_warn": 559 o = aw.seal(23, b"HTTP/1.0 200 ok\r\n") + aw.seal(21, b"\x01\x2a") 560 elif mode == "post_user_canceled": 561 o = aw.seal(21, b"\x01\x5a") + reply(aw) 562 elif mode == "post_alert_trail": 563 o = aw.seal(23, b"HTTP/1.0 200 ok\r\n") + aw.seal(21, b"\x01\x00\x00") 564 elif mode == "post_close_then_data": 565 o = reply(aw) + aw.seal(23, b"EXTRA-AFTER-CLOSE") 566 elif mode == "post_appdata_max": 567 body = b"HTTP/1.0 200 ok\r\ncontent-length: 16000\r\n\r\n" 568 data = body + b"a" * (16384 - len(body)) 569 o = aw.seal(23, data) + aw.seal(21, b"\x01\x00") 570 elif mode == "post_appdata_over": 571 body = b"HTTP/1.0 200 ok\r\ncontent-length: 16001\r\n\r\n" 572 data = body + b"a" * (16385 - len(body)) 573 o = aw.seal(23, data) + aw.seal(21, b"\x01\x00") 574 elif mode == "post_empty_hs": 575 o = aw.seal(22, b"") + reply(aw) 576 elif mode == "ccs_post": 577 o = CCS + reply(aw) 578 elif mode == "post_hs_bigdecl": 579 o = aw.seal(22, b"\x04\xff\xff\xff" + bytes(100)) + reply(aw) 580 else: 581 o = reply(aw) 582 if mode in ("post_ku_flood", "post_close_then_data"): 583 send(c, o) # the flood is sized to be read whole; the data after close_notify must arrive 584 else: 585 paced(o, quiet=False) 586 if tail: 587 with cv_in: 588 cv_in.wait_for(lambda: inbuf["eof"], timeout=3) 589 if not inbuf["eof"]: 590 send(c, tail) 591 if mode in ("post_trunc", "post_trunc_full"): 592 try: 593 c.shutdown(socket.SHUT_WR) 594 except OSError: 595 pass 596 # what the client sends afterwards: KeyUpdate answers, close_notify or an alert 597 client_records(on_app) 598 say(ku=st["ku"]) 599 print("SRV " + " ".join("%s=%s" % kv for kv in facts.items()), flush=True) 600 c.close()