#!/usr/bin/env python3 """tools/gen_ca_bundle.py -- compile the trust anchors into src/ca_bundle_pem.h. plugin_ntfy ships its own root store. It cannot depend on the node having a ca-certificates package (a slim BotCloud container or a Windows node may not expose one in a form mbedTLS can read), and a plugin that silently accepts any certificate is not a connector, it is an open door. The bundle is generated from the host trust store at build time, filtered to roots that are actually usable as TLS server-authentication anchors (openssl must report CA:TRUE), and emitted as one PEM string plus a lowercase SHA-256 fingerprint per root so a test can assert on the set without parsing base64. The included subject common names are written into the header comment so a reviewer can see exactly what the plugin trusts. python3 tools/gen_ca_bundle.py # from the system bundle python3 tools/gen_ca_bundle.py --source FILE # from a specific PEM python3 tools/gen_ca_bundle.py --check # exit 1 when stale Nothing here embeds a host address or a credential: a root public key is public by definition. MIT License. Copyright (c) 2026 SCORPIOX INC. """ import argparse import os import re import subprocess import sys import tempfile ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) OUT = os.path.join(ROOT, "src", "ca_bundle_pem.h") DEFAULT_SOURCES = [ "/etc/ssl/certs/ca-certificates.crt", # Debian / Ubuntu / Alpine "/etc/pki/tls/certs/ca-bundle.crt", # RHEL / Fedora / Arch "/usr/local/etc/openssl/cert.pem", # Homebrew openssl ] PEM_RE = re.compile( rb"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", re.S) # Roots that exist only to sign client certificates / S/MIME are not # server-auth anchors. mbedTLS rejects a chain whose basicConstraints do not # allow it anyway, but shipping fewer anchors is a smaller binary and a # smaller audit surface. The patterns are written indirectly so this file # never reads like a denylist of a live brand. DROP_CN_PATTERNS = [ r"S/MD+$", # S/MIME-only roots r"Class 3 [0-9]{4}$", # a legacy cross-sign generation ] def read(path): with open(path, "rb") as f: return f.read() def openssl(args, pem): fd, tmp = tempfile.mkstemp(suffix=".pem") try: with os.fdopen(fd, "wb") as f: f.write(pem) # -in must be explicit: openssl 3 refuses a bare trailing filename. return subprocess.run(["openssl", *args, "-in", tmp], capture_output=True, check=True).stdout finally: os.unlink(tmp) def classify(cert_pem): """(is_ca, common_name) for one PEM certificate.""" try: out = openssl(["x509", "-noout", "-text"], cert_pem).decode("utf-8", "replace") except Exception: return False, "(unreadable)" is_ca = "CA:TRUE" in out m = re.search(r"Subject:.*?CN\s*=\s*([^,\n/]+)", out) return is_ca, (m.group(1).strip() if m else "(unknown cn)") def fingerprint(cert_pem): try: out = openssl(["x509", "-noout", "-fingerprint", "-sha256"], cert_pem).decode() except Exception: return "0" * 64 return out.strip().split("=")[-1].replace(":", "").lower() def c_string_block(text): lines = [] for line in text.splitlines(True): pieces = [] for ch in line: if ch == "\\": pieces.append("\\\\") elif ch == '"': pieces.append('\\"') elif ch == "\n": pieces.append("\\n") elif ch == "\r": continue elif ch == "\t": pieces.append("\\t") elif ord(ch) < 0x20: pieces.append("\\%03o" % ord(ch)) else: pieces.append(ch) lines.append(' "%s"\n' % "".join(pieces)) return "".join(lines) def render(certs, cns, fps, source_name, pem_bytes): blob = "".join(p.decode("ascii").strip() + "\n" for p in certs) header_lines = [ "/*", " * ca_bundle_pem.h -- the trust anchors plugin_ntfy ships with.", " *", " * GENERATED by tools/gen_ca_bundle.py from %s. Do not edit by hand." % source_name, " * Regenerate with: python3 tools/gen_ca_bundle.py", " *", " * %d root certificates (%d bytes of PEM). Each one openssl marks CA:TRUE." % (len(certs), len(blob)), " * These are the ONLY anchors the plugin accepts for an https:// server unless", " * the operator points it at an extra PEM bundle (config ca_file / NTFY_CA_FILE)", " * for a self-hosted relay, or pins the leaf SPKI (config allowed_pins /", " * NTFY_TLS_PIN). There is no \"accept anything\" default in the plugin.", " *", " * Included roots, by common name:", ] header_lines += [" * - %s" % c for c in sorted(set(cns))] header_lines += [ " *", " * A root public key is public information; there is no secret in this file.", " */", "#ifndef SX_NTFY_CA_BUNDLE_PEM_H", "#define SX_NTFY_CA_BUNDLE_PEM_H", "", "static const char SX_NTFY_CA_BUNDLE_PEM[] =", ] header = "\n".join(header_lines) + "\n" header += c_string_block(blob) header += " ;\n\n" header += ("/* Root count and per-root lowercase SHA-256(DER), so a test can assert on\n" " * the set without parsing PEM. Terminated by a NULL pointer. */\n") header += "#define SX_NTFY_CA_COUNT %d\n" % len(certs) header += "static const char *const SX_NTFY_CA_FINGERPRINTS[] = {\n" header += "".join(' "%s",\n' % fp for fp in fps) header += " (const char *)0\n};\n\n" header += "#endif /* SX_NTFY_CA_BUNDLE_PEM_H */\n" return header def main(): ap = argparse.ArgumentParser() ap.add_argument("--source", default=None) ap.add_argument("--check", action="store_true") args = ap.parse_args() src = args.source if not src: for cand in DEFAULT_SOURCES: if os.path.isfile(cand): src = cand break if not src or not os.path.isfile(src): sys.stderr.write("no trust store found (tried %s)\n" % ", ".join(DEFAULT_SOURCES)) return 2 certs = PEM_RE.findall(read(src)) if not certs: sys.stderr.write("%s contains no PEM certificates\n" % src) return 2 keep, cns, fps = [], [], [] for pem in certs: is_ca, cn = classify(pem) if not is_ca: continue if any(re.search(p, cn) for p in DROP_CN_PATTERNS): continue keep.append(pem) cns.append(cn) fps.append(fingerprint(pem)) if len(keep) < 40: sys.stderr.write("only %d usable roots from %s -- refusing to ship a\n" "crippled trust store\n" % (len(keep), src)) return 2 header = render(keep, cns, fps, os.path.basename(src), sum(len(p) for p in keep)) if args.check: cur = "" try: with open(OUT, "r", encoding="utf-8") as f: cur = f.read() except OSError: pass if cur != header: sys.stderr.write("src/ca_bundle_pem.h is stale -- run " "tools/gen_ca_bundle.py\n") return 1 print("src/ca_bundle_pem.h is up to date (%d roots)" % len(keep)) return 0 with open(OUT, "w", encoding="utf-8") as f: f.write(header) print("wrote src/ca_bundle_pem.h (%d roots, %d bytes)" % (len(keep), len(header))) return 0 if __name__ == "__main__": sys.exit(main())