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 / net / badssl_run.py
| 1 | #!/usr/bin/env python3 |
| 2 | # SPDX-License-Identifier: Apache-2.0 |
| 3 | # Test tooling only (driver and oracle, no TLS logic of its own): the badssl.com sweep for the |
| 4 | # om/tls client. Called by badssl.sh. |
| 5 | # usage: badssl_run.py CLIENT PKIDIR DASHBOARD.html CACHEDIR OUT.tsv |
| 6 | # For every host on the badssl.com dashboard: |
| 7 | # live the client against HOST:PORT itself (system trust store). badssl.com servers offer no |
| 8 | # TLS 1.3 (probed per host with openssl s_client -tls1_3), so live runs end in the |
| 9 | # server's alert and never reach the client's certificate checks; they are recorded, |
| 10 | # not scored, unless a server does speak TLS 1.3. |
| 11 | # replay the host's real certificate chain (fetched once with openssl s_client -showcerts and |
| 12 | # cached in CACHEDIR) presented by hostile.py on 127.0.0.1, the client connecting as |
| 13 | # HOST with the system trust store. hostile.py signs CertificateVerify with its own key, |
| 14 | # so a chain the client accepts ends in CERTIFICATE_VERIFY/SIGNATURE_SCHEME (the chain |
| 15 | # and name checks run first, at the Certificate message), and a refused chain ends in |
| 16 | # TLS_ERR_CERTIFICATE with the x509 detail. |
| 17 | # oracle openssl verify of the same chain against the same trust store, with -verify_hostname |
| 18 | # and -purpose sslserver: the expected chain verdict. |
| 19 | # Scoring (replay): REFUSE expected and refused = refuse_ok; ACCEPT expected and accepted = |
| 20 | # accept_ok; a mismatch listed in GAPS below = explained; any other mismatch = unexplained. |
| 21 | # Negotiation hosts (cipher suite, key exchange, protocol) are scored on the live result plus |
| 22 | # the ClientHello policy check of hostile.sh (TLS 1.3 only, AEAD suites, x25519). |
| 23 | import html.parser, os, re, socket, subprocess, sys, tempfile, time |
| 24 | |
| 25 | client, pki, dash, cache, outp = sys.argv[1:6] |
| 26 | here = os.path.dirname(os.path.abspath(__file__)) |
| 27 | STORE = "/etc/ssl/certs/ca-certificates.crt" |
| 28 | # x509 detail codes, from the X5E* constants of om/tls/x509.om:91-111 |
| 29 | X5 = ["OK", "MALFORMED", "EXPIRED", "NOT_YET_VALID", "NAME_MISMATCH", "UNKNOWN_ISSUER", "BAD_SIGNATURE", |
| 30 | "NOT_CA", "PATH_LENGTH", "KEY_USAGE", "EKU", "UNSUPPORTED_ALG", "WEAK_KEY", "CRITICAL_EXT", "TOO_DEEP", |
| 31 | "LEAF_IS_CA", "NO_SAN", "IP_HOST", "ALG_MISMATCH", "SCHEME", "X5ENC", "X5EEXT"] |
| 32 | # Known, documented gaps: badssl marks these bad for a property this client does not check. |
| 33 | GAPS = {"revoked": "no revocation checking (no OCSP, no CRL)", |
| 34 | "pinning-test": "no HTTP public key pinning (RFC 7469, retired by browsers)", |
| 35 | "no-sct": "no Certificate Transparency enforcement", |
| 36 | "invalid-expected-sct": "no Certificate Transparency enforcement"} |
| 37 | # Client policy that refuses chains a browser accepts, with the reason. |
| 38 | POLICY = {("10000-sans", "MESSAGE_TOO_BIG"): "Certificate message larger than the client's handshake buffer", |
| 39 | ("incomplete-chain", "CERTIFICATE UNKNOWN_ISSUER"): "no AIA fetching; browsers fetch the missing intermediate"} |
| 40 | NEGOTIATION = {"cipher-suite", "key-exchange", "protocol"} |
| 41 | PAGE = {"mixed-content": "mixed content is a page property", "ui": "a browser UI property", |
| 42 | "upgrade": "HSTS/upgrade is an HTTP property", "client-certificate": "client certificate handling"} |
| 43 | |
| 44 | |
| 45 | class Dash(html.parser.HTMLParser): |
| 46 | def __init__(self): |
| 47 | super().__init__(); self.sec = None; self.rows = [] |
| 48 | |
| 49 | def handle_starttag(self, tag, a): |
| 50 | a = dict(a) |
| 51 | if tag == "h2": |
| 52 | self.sec = a.get("id") |
| 53 | if tag == "a" and a.get("class") in ("good", "bad", "dubious"): |
| 54 | m = re.match(r"(https?)://([a-z0-9.-]+\.badssl\.com)(?::(\d+))?/", a.get("href", "")) |
| 55 | if m: |
| 56 | self.rows.append((m.group(2), int(m.group(3) or (443 if m.group(1) == "https" else 80)), |
| 57 | self.sec, a["class"], m.group(1))) |
| 58 | |
| 59 | |
| 60 | def run(cmd, timeout, inp=b""): |
| 61 | try: |
| 62 | p = subprocess.run(cmd, input=inp, capture_output=True, timeout=timeout) |
| 63 | return p.returncode, p.stdout.decode("latin-1"), p.stderr.decode("latin-1") |
| 64 | except subprocess.TimeoutExpired: |
| 65 | return None, "", "" |
| 66 | |
| 67 | |
| 68 | def outcome(rc, out, err): |
| 69 | m = re.search(r"TLSERR TLS_ERR_([A-Z_]+) detail (\d+)", err) |
| 70 | if rc is None: |
| 71 | return "HANG" |
| 72 | if rc == 0: |
| 73 | return "ACCEPT" |
| 74 | if not m: |
| 75 | return "EXIT%d" % rc |
| 76 | n, dt = m.group(1), int(m.group(2)) |
| 77 | if n == "CERTIFICATE": |
| 78 | return "CERTIFICATE " + (X5[dt] if dt < len(X5) else str(dt)) |
| 79 | if n == "ALERT_RECEIVED": |
| 80 | return "ALERT_RECEIVED %d" % dt |
| 81 | return n |
| 82 | |
| 83 | |
| 84 | def fetch_chain(host, port): |
| 85 | path = os.path.join(cache, "%s_%d.pem" % (host, port)) |
| 86 | if os.path.exists(path) and os.path.getsize(path) > 0: |
| 87 | return path, "cached" |
| 88 | for extra in ([], ["-cipher", "ALL:@SECLEVEL=0"], ["-tls1", "-cipher", "ALL:@SECLEVEL=0"], |
| 89 | ["-tls1_1", "-cipher", "ALL:@SECLEVEL=0"]): |
| 90 | rc, out, _ = run(["openssl", "s_client", "-showcerts", "-servername", host, "-connect", "%s:%d" % (host, port)] + extra, 20) |
| 91 | pems = re.findall(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\n", out or "", re.S) |
| 92 | if pems: |
| 93 | open(path, "w").write("".join(pems)) |
| 94 | open(os.path.join(cache, "fetched.log"), "a").write("%s %s:%d %s %d certs\n" % ( |
| 95 | time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), host, port, " ".join(extra) or "default", len(pems))) |
| 96 | return path, "fetched" |
| 97 | # OpenSSL caps a certificate list at 100 KiB ("excessive message size", 10000-sans); tlslite-ng |
| 98 | # (venv in $TLSLITE_PY, test tooling only) has no such cap |
| 99 | py = os.environ.get("TLSLITE_PY", os.path.join(here, "../../../../../tlsverify-TlsSuites-ext/venv/bin/python")) |
| 100 | if os.path.exists(py): |
| 101 | code = ("import socket,sys,base64\nfrom tlslite.api import TLSConnection\n" |
| 102 | "c=TLSConnection(socket.create_connection((sys.argv[1],int(sys.argv[2])),timeout=30))\n" |
| 103 | "c.handshakeClientCert(serverName=sys.argv[1])\n" |
| 104 | "sys.stdout.write(''.join('-----BEGIN CERTIFICATE-----\\n'+base64.encodebytes(bytes(x.bytes)).decode()" |
| 105 | "+'-----END CERTIFICATE-----\\n' for x in c.session.serverCertChain.x509List))\n") |
| 106 | rc, out, _ = run([py, "-c", code, host, str(port)], 60) |
| 107 | if rc == 0 and "BEGIN CERTIFICATE" in (out or ""): |
| 108 | open(path, "w").write(out) |
| 109 | open(os.path.join(cache, "fetched.log"), "a").write("%s %s:%d tlslite-ng %d certs\n" % ( |
| 110 | time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), host, port, out.count("BEGIN CERTIFICATE"))) |
| 111 | return path, "fetched (tlslite-ng)" |
| 112 | return None, "no chain" |
| 113 | |
| 114 | |
| 115 | def oracle(host, chain): |
| 116 | pems = re.findall(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\n", open(chain).read(), re.S) |
| 117 | with tempfile.TemporaryDirectory() as t: |
| 118 | open(t + "/leaf.pem", "w").write(pems[0]); open(t + "/rest.pem", "w").write("".join(pems[1:]) or pems[0]) |
| 119 | rc, out, err = run(["openssl", "verify", "-CAfile", STORE, "-untrusted", t + "/rest.pem", |
| 120 | "-verify_hostname", host, "-purpose", "sslserver", t + "/leaf.pem"], 20) |
| 121 | if rc == 0: |
| 122 | return "ACCEPT", "openssl verify OK" |
| 123 | m = re.search(r"error \d+ at \d+ depth lookup: ([^\n]+)", out + err) |
| 124 | return "REFUSE", "openssl: " + (m.group(1) if m else (out + err).strip().splitlines()[-1][:80]) |
| 125 | |
| 126 | |
| 127 | def freeport(): |
| 128 | s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close() |
| 129 | return p |
| 130 | |
| 131 | |
| 132 | def replay(host, chain, port=443): |
| 133 | lp = freeport() |
| 134 | srv = subprocess.Popen([sys.executable, os.path.join(here, "hostile.py"), str(lp), pki, "replay", chain], |
| 135 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| 136 | if srv.stdout.readline().strip() != "READY": |
| 137 | srv.kill(); return "SERVER-FAIL" |
| 138 | rc, out, err = run([client, host, str(lp), "get", "127.0.0.1", "-", "/", "0,15000,0"], 40) |
| 139 | try: |
| 140 | srv.communicate(timeout=25) |
| 141 | except subprocess.TimeoutExpired: |
| 142 | srv.kill(); srv.communicate() |
| 143 | o = outcome(rc, out, err) |
| 144 | # chain and name accepted: the handshake got as far as our (deliberately foreign) signature |
| 145 | return "ACCEPT(chain; then %s)" % o if o in ("CERTIFICATE_VERIFY", "SIGNATURE_SCHEME") else o |
| 146 | |
| 147 | |
| 148 | def tls13(host, port): |
| 149 | rc, out, _ = run(["openssl", "s_client", "-tls1_3", "-servername", host, "-connect", "%s:%d" % (host, port)], 20) |
| 150 | return "yes" if "TLSv1.3" in out and "Cipher is (NONE)" not in out else "no" |
| 151 | |
| 152 | |
| 153 | d = Dash(); d.feed(open(dash, encoding="utf-8").read()) |
| 154 | rows = d.rows |
| 155 | os.makedirs(cache, exist_ok=True) |
| 156 | res = [] |
| 157 | cnt = dict(refuse_ok=0, accept_ok=0, explained=0, unexplained=0, na=0) |
| 158 | for host, port, sec, cls, scheme in rows: |
| 159 | short = host[:-len(".badssl.com")] |
| 160 | cat = "%s/%s" % (sec, cls) |
| 161 | if scheme == "http": |
| 162 | res.append((host, port, cat, "NA (plain HTTP site; no TLS)", "-", "NA", "-", "-")); cnt["na"] += 1; continue |
| 163 | try: |
| 164 | socket.getaddrinfo(host, port) |
| 165 | except OSError: |
| 166 | res.append((host, port, cat, "NA (host does not resolve)", "DNS", "NA", "-", "-")); cnt["na"] += 1; continue |
| 167 | live = outcome(*run([client, host, str(port), "get", host, "-", "/", "0,15000,0"], 40)) |
| 168 | t13 = tls13(host, port) |
| 169 | chain, how = fetch_chain(host, port) |
| 170 | if sec in NEGOTIATION: |
| 171 | notes = "tls13=%s; chain %s" % (t13, (replay(host, chain) if chain else how)) |
| 172 | if cls == "good": |
| 173 | # a server without TLS 1.3 says nothing about this TLS 1.3-only client; scored only if it speaks 1.3 |
| 174 | if t13 == "yes": |
| 175 | exp = "ACCEPT (server speaks TLS 1.3)"; v = "accept_ok" if live == "ACCEPT" else "unexplained" |
| 176 | else: |
| 177 | exp = "NA (server has no TLS 1.3; the client offers nothing else)"; v = "na" |
| 178 | else: |
| 179 | exp = "REFUSE (client offers only TLS 1.3, suites 1303/1301, x25519: see the ch_policy line)" |
| 180 | v = "refuse_ok" if live != "ACCEPT" else "unexplained" |
| 181 | cnt[v] += 1 |
| 182 | res.append((host, port, cat, exp, "live " + live, v if v != "na" else "NA", live, notes)) |
| 183 | print("%-12s %s:%d %s -> live %s" % (v, host, port, exp[:70], live), flush=True) |
| 184 | continue |
| 185 | if not chain: |
| 186 | res.append((host, port, cat, "NA (no chain fetched)", "-", "NA", live, "tls13=%s" % t13)); cnt["na"] += 1; continue |
| 187 | oexp, why = oracle(host, chain) |
| 188 | rep = replay(host, chain) |
| 189 | acc = rep.startswith("ACCEPT") |
| 190 | if short in GAPS: |
| 191 | exp = "REFUSE (badssl %s; %s)" % (cls, why) |
| 192 | else: |
| 193 | exp = "%s (%s)" % (oexp, why) |
| 194 | want_refuse = exp.startswith("REFUSE") |
| 195 | if want_refuse and not acc: |
| 196 | v = "refuse_ok" |
| 197 | elif not want_refuse and acc: |
| 198 | v = "accept_ok" |
| 199 | elif want_refuse and acc and short in GAPS: |
| 200 | v = "explained"; exp += " | gap: " + GAPS[short] |
| 201 | elif not want_refuse and (short, rep) in POLICY: |
| 202 | v = "explained"; exp += " | client policy: " + POLICY[(short, rep)] |
| 203 | else: |
| 204 | v = "unexplained" |
| 205 | notes = "tls13=%s; chain %s" % (t13, how) |
| 206 | if sec in PAGE: |
| 207 | notes += "; page-level property N/A to a TLS client (%s)" % PAGE[sec] |
| 208 | if v == "refuse_ok" and rep == "CERTIFICATE MALFORMED": |
| 209 | notes += ("; client refuses earlier than openssl, at its strict profile checks (x509.om chain_xchk/chain_strict:" |
| 210 | " e.g. a leaf without authorityKeyIdentifier, RFC 5280 4.2.1.1)") |
| 211 | cnt[v] += 1 |
| 212 | res.append((host, port, cat, exp, "replay " + rep, v, live, notes)) |
| 213 | print("%-12s %s:%d %s -> %s" % (v, host, port, exp[:70], rep), flush=True) |
| 214 | |
| 215 | # controls: the same machinery must refuse a good chain under the wrong name and with a broken |
| 216 | # leaf signature |
| 217 | ctl_ok = True |
| 218 | good = os.path.join(cache, "sha256.badssl.com_443.pem") |
| 219 | if os.path.exists(good): |
| 220 | r1 = replay("wrong-name-control.badssl.org", good) |
| 221 | pems = re.findall(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\n", open(good).read(), re.S) |
| 222 | from cryptography import x509 |
| 223 | from cryptography.hazmat.primitives import serialization |
| 224 | der = bytearray(x509.load_pem_x509_certificate(pems[0].encode()).public_bytes(serialization.Encoding.DER)) |
| 225 | der[-8] ^= 0x01 # inside the leaf's signature value |
| 226 | import base64 |
| 227 | bad = os.path.join(cache, "control-badsig.pem") |
| 228 | b64 = base64.encodebytes(bytes(der)).decode() |
| 229 | open(bad, "w").write("-----BEGIN CERTIFICATE-----\n" + b64 + "-----END CERTIFICATE-----\n" + "".join(pems[1:])) |
| 230 | r2 = replay("sha256.badssl.com", bad) |
| 231 | r3 = replay("sha256.badssl.com", good) |
| 232 | for name, got, want in (("wrong name", r1, "CERTIFICATE NAME_MISMATCH"), ("bad leaf signature", r2, "CERTIFICATE BAD_SIGNATURE"), |
| 233 | ("good chain", r3, "ACCEPT")): |
| 234 | ok = got.startswith(want) |
| 235 | ctl_ok &= ok |
| 236 | print("CONTROL %s %s: %s (want %s)" % ("PASS" if ok else "FAIL", name, got, want)) |
| 237 | else: |
| 238 | ctl_ok = False |
| 239 | print("CONTROL FAIL: no sha256.badssl.com chain") |
| 240 | |
| 241 | with open(outp, "w") as f: |
| 242 | f.write("# badssl.com sweep of the om/tls client; generated by om/tls/test/net/badssl.sh on %s\n" % time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())) |
| 243 | f.write("# observed: 'replay X' = the host's real chain served locally (see badssl_run.py); 'live X' = the real server\n") |
| 244 | f.write("host\tport\tcategory\texpected\tobserved\tverdict\tlive\tnotes\n") |
| 245 | for r in res: |
| 246 | f.write("\t".join(str(x) for x in r) + "\n") |
| 247 | ok = cnt["unexplained"] == 0 and ctl_ok |
| 248 | print("BADSSL %s refuse_ok=%d accept_ok=%d explained=%d unexplained=%d na=%d hosts=%d" % ( |
| 249 | "PASS" if ok else "FAIL", cnt["refuse_ok"], cnt["accept_ok"], cnt["explained"], cnt["unexplained"], cnt["na"], len(rows))) |
| 250 | sys.exit(0 if ok else 1) |