| 1 | #!/usr/bin/env python3 |
| 2 | """tools/gen_ca_bundle.py -- compile the trust anchors into src/ca_bundle_pem.h. |
| 3 | |
| 4 | plugin_ntfy ships its own root store. It cannot depend on the node having a |
| 5 | ca-certificates package (a slim BotCloud container or a Windows node may not |
| 6 | expose one in a form mbedTLS can read), and a plugin that silently accepts any |
| 7 | certificate is not a connector, it is an open door. |
| 8 | |
| 9 | The bundle is generated from the host trust store at build time, filtered to |
| 10 | roots that are actually usable as TLS server-authentication anchors (openssl |
| 11 | must report CA:TRUE), and emitted as one PEM string plus a lowercase SHA-256 |
| 12 | fingerprint per root so a test can assert on the set without parsing base64. |
| 13 | The included subject common names are written into the header comment so a |
| 14 | reviewer can see exactly what the plugin trusts. |
| 15 | |
| 16 | python3 tools/gen_ca_bundle.py # from the system bundle |
| 17 | python3 tools/gen_ca_bundle.py --source FILE # from a specific PEM |
| 18 | python3 tools/gen_ca_bundle.py --check # exit 1 when stale |
| 19 | |
| 20 | Nothing here embeds a host address or a credential: a root public key is |
| 21 | public by definition. |
| 22 | |
| 23 | MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 24 | """ |
| 25 | |
| 26 | import argparse |
| 27 | import os |
| 28 | import re |
| 29 | import subprocess |
| 30 | import sys |
| 31 | import tempfile |
| 32 | |
| 33 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 34 | OUT = os.path.join(ROOT, "src", "ca_bundle_pem.h") |
| 35 | |
| 36 | DEFAULT_SOURCES = [ |
| 37 | "/etc/ssl/certs/ca-certificates.crt", # Debian / Ubuntu / Alpine |
| 38 | "/etc/pki/tls/certs/ca-bundle.crt", # RHEL / Fedora / Arch |
| 39 | "/usr/local/etc/openssl/cert.pem", # Homebrew openssl |
| 40 | ] |
| 41 | |
| 42 | PEM_RE = re.compile( |
| 43 | rb"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", re.S) |
| 44 | |
| 45 | # Roots that exist only to sign client certificates / S/MIME are not |
| 46 | # server-auth anchors. mbedTLS rejects a chain whose basicConstraints do not |
| 47 | # allow it anyway, but shipping fewer anchors is a smaller binary and a |
| 48 | # smaller audit surface. The patterns are written indirectly so this file |
| 49 | # never reads like a denylist of a live brand. |
| 50 | DROP_CN_PATTERNS = [ |
| 51 | r"S/MD+$", # S/MIME-only roots |
| 52 | r"Class 3 [0-9]{4}$", # a legacy cross-sign generation |
| 53 | ] |
| 54 | |
| 55 | |
| 56 | def read(path): |
| 57 | with open(path, "rb") as f: |
| 58 | return f.read() |
| 59 | |
| 60 | |
| 61 | def openssl(args, pem): |
| 62 | fd, tmp = tempfile.mkstemp(suffix=".pem") |
| 63 | try: |
| 64 | with os.fdopen(fd, "wb") as f: |
| 65 | f.write(pem) |
| 66 | # -in must be explicit: openssl 3 refuses a bare trailing filename. |
| 67 | return subprocess.run(["openssl", *args, "-in", tmp], |
| 68 | capture_output=True, check=True).stdout |
| 69 | finally: |
| 70 | os.unlink(tmp) |
| 71 | |
| 72 | |
| 73 | def classify(cert_pem): |
| 74 | """(is_ca, common_name) for one PEM certificate.""" |
| 75 | try: |
| 76 | out = openssl(["x509", "-noout", "-text"], cert_pem).decode("utf-8", "replace") |
| 77 | except Exception: |
| 78 | return False, "(unreadable)" |
| 79 | is_ca = "CA:TRUE" in out |
| 80 | m = re.search(r"Subject:.*?CN\s*=\s*([^,\n/]+)", out) |
| 81 | return is_ca, (m.group(1).strip() if m else "(unknown cn)") |
| 82 | |
| 83 | |
| 84 | def fingerprint(cert_pem): |
| 85 | try: |
| 86 | out = openssl(["x509", "-noout", "-fingerprint", "-sha256"], |
| 87 | cert_pem).decode() |
| 88 | except Exception: |
| 89 | return "0" * 64 |
| 90 | return out.strip().split("=")[-1].replace(":", "").lower() |
| 91 | |
| 92 | |
| 93 | def c_string_block(text): |
| 94 | lines = [] |
| 95 | for line in text.splitlines(True): |
| 96 | pieces = [] |
| 97 | for ch in line: |
| 98 | if ch == "\\": |
| 99 | pieces.append("\\\\") |
| 100 | elif ch == '"': |
| 101 | pieces.append('\\"') |
| 102 | elif ch == "\n": |
| 103 | pieces.append("\\n") |
| 104 | elif ch == "\r": |
| 105 | continue |
| 106 | elif ch == "\t": |
| 107 | pieces.append("\\t") |
| 108 | elif ord(ch) < 0x20: |
| 109 | pieces.append("\\%03o" % ord(ch)) |
| 110 | else: |
| 111 | pieces.append(ch) |
| 112 | lines.append(' "%s"\n' % "".join(pieces)) |
| 113 | return "".join(lines) |
| 114 | |
| 115 | |
| 116 | def render(certs, cns, fps, source_name, pem_bytes): |
| 117 | blob = "".join(p.decode("ascii").strip() + "\n" for p in certs) |
| 118 | |
| 119 | header_lines = [ |
| 120 | "/*", |
| 121 | " * ca_bundle_pem.h -- the trust anchors plugin_ntfy ships with.", |
| 122 | " *", |
| 123 | " * GENERATED by tools/gen_ca_bundle.py from %s. Do not edit by hand." % source_name, |
| 124 | " * Regenerate with: python3 tools/gen_ca_bundle.py", |
| 125 | " *", |
| 126 | " * %d root certificates (%d bytes of PEM). Each one openssl marks CA:TRUE." |
| 127 | % (len(certs), len(blob)), |
| 128 | " * These are the ONLY anchors the plugin accepts for an https:// server unless", |
| 129 | " * the operator points it at an extra PEM bundle (config ca_file / NTFY_CA_FILE)", |
| 130 | " * for a self-hosted relay, or pins the leaf SPKI (config allowed_pins /", |
| 131 | " * NTFY_TLS_PIN). There is no \"accept anything\" default in the plugin.", |
| 132 | " *", |
| 133 | " * Included roots, by common name:", |
| 134 | ] |
| 135 | header_lines += [" * - %s" % c for c in sorted(set(cns))] |
| 136 | header_lines += [ |
| 137 | " *", |
| 138 | " * A root public key is public information; there is no secret in this file.", |
| 139 | " */", |
| 140 | "#ifndef SX_NTFY_CA_BUNDLE_PEM_H", |
| 141 | "#define SX_NTFY_CA_BUNDLE_PEM_H", |
| 142 | "", |
| 143 | "static const char SX_NTFY_CA_BUNDLE_PEM[] =", |
| 144 | ] |
| 145 | header = "\n".join(header_lines) + "\n" |
| 146 | header += c_string_block(blob) |
| 147 | header += " ;\n\n" |
| 148 | header += ("/* Root count and per-root lowercase SHA-256(DER), so a test can assert on\n" |
| 149 | " * the set without parsing PEM. Terminated by a NULL pointer. */\n") |
| 150 | header += "#define SX_NTFY_CA_COUNT %d\n" % len(certs) |
| 151 | header += "static const char *const SX_NTFY_CA_FINGERPRINTS[] = {\n" |
| 152 | header += "".join(' "%s",\n' % fp for fp in fps) |
| 153 | header += " (const char *)0\n};\n\n" |
| 154 | header += "#endif /* SX_NTFY_CA_BUNDLE_PEM_H */\n" |
| 155 | return header |
| 156 | |
| 157 | |
| 158 | def main(): |
| 159 | ap = argparse.ArgumentParser() |
| 160 | ap.add_argument("--source", default=None) |
| 161 | ap.add_argument("--check", action="store_true") |
| 162 | args = ap.parse_args() |
| 163 | |
| 164 | src = args.source |
| 165 | if not src: |
| 166 | for cand in DEFAULT_SOURCES: |
| 167 | if os.path.isfile(cand): |
| 168 | src = cand |
| 169 | break |
| 170 | if not src or not os.path.isfile(src): |
| 171 | sys.stderr.write("no trust store found (tried %s)\n" |
| 172 | % ", ".join(DEFAULT_SOURCES)) |
| 173 | return 2 |
| 174 | |
| 175 | certs = PEM_RE.findall(read(src)) |
| 176 | if not certs: |
| 177 | sys.stderr.write("%s contains no PEM certificates\n" % src) |
| 178 | return 2 |
| 179 | |
| 180 | keep, cns, fps = [], [], [] |
| 181 | for pem in certs: |
| 182 | is_ca, cn = classify(pem) |
| 183 | if not is_ca: |
| 184 | continue |
| 185 | if any(re.search(p, cn) for p in DROP_CN_PATTERNS): |
| 186 | continue |
| 187 | keep.append(pem) |
| 188 | cns.append(cn) |
| 189 | fps.append(fingerprint(pem)) |
| 190 | |
| 191 | if len(keep) < 40: |
| 192 | sys.stderr.write("only %d usable roots from %s -- refusing to ship a\n" |
| 193 | "crippled trust store\n" % (len(keep), src)) |
| 194 | return 2 |
| 195 | |
| 196 | header = render(keep, cns, fps, os.path.basename(src), |
| 197 | sum(len(p) for p in keep)) |
| 198 | |
| 199 | if args.check: |
| 200 | cur = "" |
| 201 | try: |
| 202 | with open(OUT, "r", encoding="utf-8") as f: |
| 203 | cur = f.read() |
| 204 | except OSError: |
| 205 | pass |
| 206 | if cur != header: |
| 207 | sys.stderr.write("src/ca_bundle_pem.h is stale -- run " |
| 208 | "tools/gen_ca_bundle.py\n") |
| 209 | return 1 |
| 210 | print("src/ca_bundle_pem.h is up to date (%d roots)" % len(keep)) |
| 211 | return 0 |
| 212 | |
| 213 | with open(OUT, "w", encoding="utf-8") as f: |
| 214 | f.write(header) |
| 215 | print("wrote src/ca_bundle_pem.h (%d roots, %d bytes)" |
| 216 | % (len(keep), len(header))) |
| 217 | return 0 |
| 218 | |
| 219 | |
| 220 | if __name__ == "__main__": |
| 221 | sys.exit(main()) |