import base64 import datetime import json import logging import os import time from flask import Flask, jsonify, render_template, request import store from ca import CertificateAuthority from mqtt_worker import MqttWorker logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s") log = logging.getLogger("main") OPTIONS_PATH = "/data/options.json" SSL_DIR = "/ssl" BROKER_CERT_FILENAME = "mosquitto-server.crt" BROKER_KEY_FILENAME = "mosquitto-server.key" CA_FILENAME = "mqtt-cert-manager-ca.crt" CRL_FILENAME = "mqtt-cert-manager-crl.pem" RENEWAL_TIMESTAMP_SKEW_SECONDS = 300 def load_options(): defaults = { "mqtt_host": "core-mosquitto", "mqtt_port": 1883, "mqtt_username": "", "mqtt_password": "", "request_topic_prefix": "cert/enroll", "cert_validity_days": 825, "broker_hostnames": "core-mosquitto,localhost", "renewal_window_days": 30, } if os.path.exists(OPTIONS_PATH): with open(OPTIONS_PATH) as f: defaults.update(json.load(f)) return defaults options = load_options() ca = CertificateAuthority() app = Flask(__name__) # Guard: this server has no login of its own. It relies entirely on only # being reachable through Supervisor's ingress proxy, which itself requires # an authenticated Home Assistant session. Supervisor's internal ingress # proxy always connects from this fixed address — reject anything else # (e.g. other add-ons on the same internal Docker network) outright. SUPERVISOR_INGRESS_IP = "172.30.32.2" @app.before_request def restrict_to_ingress_proxy(): if request.remote_addr != SUPERVISOR_INGRESS_IP: log.warning("rejected request from non-ingress source %s", request.remote_addr) return jsonify({"error": "forbidden"}), 403 def parsed_broker_hostnames(): raw = options.get("broker_hostnames", "core-mosquitto,localhost") return [h.strip() for h in raw.split(",") if h.strip()] def write_broker_files(key_pem: str, cert_pem: str): """Write ca.crt + the broker's own server cert/key into the shared /ssl folder so they can be referenced directly from the Mosquitto add-on's certfile/keyfile/cafile options.""" os.makedirs(SSL_DIR, exist_ok=True) ca_path = os.path.join(SSL_DIR, CA_FILENAME) with open(ca_path, "w") as f: f.write(ca.ca_cert_pem()) cert_path = os.path.join(SSL_DIR, BROKER_CERT_FILENAME) with open(cert_path, "w") as f: f.write(cert_pem) key_path = os.path.join(SSL_DIR, BROKER_KEY_FILENAME) with open(key_path, "w") as f: f.write(key_pem) os.chmod(key_path, 0o600) log.info("wrote CA + broker server cert/key to %s", SSL_DIR) def issue_broker_cert(): hostnames = parsed_broker_hostnames() key_pem, cert_pem = ca.issue_server_cert( hostnames, int(options["cert_validity_days"]) ) write_broker_files(key_pem, cert_pem) from cryptography import x509 not_after = x509.load_pem_x509_certificate( cert_pem.encode() ).not_valid_after_utc.isoformat() store.set_broker_cert(hostnames, not_after) return hostnames, not_after def ensure_broker_cert_exists(): """Issue the broker server cert on first boot, or if the /ssl files are missing (e.g. someone cleared that folder), or if the configured hostnames changed since the last issuance.""" existing = store.get_broker_cert() cert_path = os.path.join(SSL_DIR, BROKER_CERT_FILENAME) key_path = os.path.join(SSL_DIR, BROKER_KEY_FILENAME) ca_path = os.path.join(SSL_DIR, CA_FILENAME) files_present = all(os.path.exists(p) for p in (cert_path, key_path, ca_path)) if existing and files_present and existing.get("hostnames") == parsed_broker_hostnames(): log.info("broker server cert already issued and up to date") return log.info("issuing broker server certificate (first boot, missing files, or hostnames changed)") issue_broker_cert() def write_crl(): """Rebuild the CRL file from every currently-revoked device and write it to /ssl. Called at startup (so the file always exists, even empty, before you point Mosquitto's crlfile at it) and after every revoke.""" revoked = store.list_revoked() entries = [ (r["serial"], datetime.datetime.fromtimestamp(r["revoked_at"], tz=datetime.timezone.utc)) for r in revoked.values() ] crl_pem = ca.build_crl(entries) os.makedirs(SSL_DIR, exist_ok=True) crl_path = os.path.join(SSL_DIR, CRL_FILENAME) with open(crl_path, "w") as f: f.write(crl_pem) log.info("wrote CRL with %d revoked cert(s) to %s", len(entries), crl_path) def handle_request(device_id, csr_pem, meta): store.add_pending(device_id, csr_pem, meta) def finalize_issuance(device_id: str, csr_pem: str, state=None): """Sign a CSR, record it, and deliver it. Shared by manual approval and the auto-renewal fast path so both stay in sync.""" from cryptography import x509 cert_pem = ca.sign_csr(csr_pem, device_id, int(options["cert_validity_days"])) leaf = x509.load_pem_x509_certificate(cert_pem.encode()) not_after = leaf.not_valid_after_utc.isoformat() store.mark_issued(device_id, cert_pem, not_after, leaf.serial_number, state=state) mqtt_worker.publish_issued(device_id, cert_pem, ca.ca_cert_pem()) return cert_pem, not_after def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta): """Auto-issue a renewed cert IF, and only if, the requester proves possession of the *currently on-record* cert's private key, that cert isn't revoked, and we're actually within the renewal window. Any failure falls back to the ordinary manual-approval queue — exactly as if this were a first-time request — rather than being silently dropped, so a legitimate device with e.g. clock skew still gets a cert eventually, just with human review.""" def fall_back_to_manual(why): log.info("renewal from %s falling back to manual approval: %s", device_id, why) store.add_pending(device_id, csr_pem, meta) if device_id in store.list_revoked(): fall_back_to_manual("device is revoked") return issued = store.list_issued().get(device_id) if not issued: fall_back_to_manual("no prior issued cert on record") return now = time.time() try: ts = float(timestamp) except (TypeError, ValueError): fall_back_to_manual("timestamp not a number") return if abs(now - ts) > RENEWAL_TIMESTAMP_SKEW_SECONDS: fall_back_to_manual("timestamp outside allowed skew window") return not_after = datetime.datetime.fromisoformat(issued["not_after"]) renewal_opens_at = not_after - datetime.timedelta(days=int(options["renewal_window_days"])) if datetime.datetime.now(datetime.timezone.utc) < renewal_opens_at: fall_back_to_manual( f"too early to renew (opens {renewal_opens_at.isoformat()})" ) return try: signature = base64.b64decode(signature_b64) except Exception: fall_back_to_manual("signature not valid base64") return message = f"{device_id}|{int(ts)}|renew".encode() if not ca.verify_renewal_proof(issued["cert"], message, signature): fall_back_to_manual("proof-of-possession signature did not verify") return try: _, new_not_after = finalize_issuance(device_id, csr_pem) except ValueError as exc: fall_back_to_manual(f"CSR rejected: {exc}") return log.info("auto-renewed cert for %s (proof verified), now valid until %s", device_id, new_not_after) mqtt_worker = MqttWorker( host=options["mqtt_host"], port=int(options["mqtt_port"]), username=options["mqtt_username"], password=options["mqtt_password"], topic_prefix=options["request_topic_prefix"], on_request=handle_request, on_renew=handle_renew, ) mqtt_worker.start() ensure_broker_cert_exists() write_crl() @app.route("/") def index(): return render_template("index.html") @app.route("/api/pending") def api_pending(): return jsonify(store.list_pending()) @app.route("/api/issued") def api_issued(): return jsonify(store.list_issued()) @app.route("/api/approve/", methods=["POST"]) def api_approve(device_id): pending, state = store.pop_pending(device_id) if not pending: return jsonify({"error": "no pending request for that device"}), 404 try: _, not_after = finalize_issuance(device_id, pending["csr"], state=state) except ValueError as exc: return jsonify({"error": str(exc)}), 400 return jsonify({"status": "issued", "device_id": device_id, "not_after": not_after}) @app.route("/api/reject/", methods=["POST"]) def api_reject(device_id): reason = (request.get_json(silent=True) or {}).get("reason", "rejected by administrator") store.reject_pending(device_id, reason) mqtt_worker.publish_rejected(device_id, reason) return jsonify({"status": "rejected", "device_id": device_id}) @app.route("/api/revoked") def api_revoked(): return jsonify(store.list_revoked()) @app.route("/api/revoke/", methods=["POST"]) def api_revoke(device_id): reason = (request.get_json(silent=True) or {}).get("reason", "revoked by administrator") serial = store.revoke_device(device_id, reason) if serial is None: return jsonify({"error": "no issued cert on record for that device"}), 404 write_crl() mqtt_worker.publish_revoked(device_id, reason) return jsonify( { "status": "revoked", "device_id": device_id, "note": "Mosquitto must be restarted to pick up the updated CRL file.", } ) @app.route("/api/broker-cert") def api_broker_cert(): info = store.get_broker_cert() return jsonify( { "info": info, "ca_filename": CA_FILENAME, "cert_filename": BROKER_CERT_FILENAME, "key_filename": BROKER_KEY_FILENAME, } ) @app.route("/api/broker-cert/reissue", methods=["POST"]) def api_broker_cert_reissue(): try: hostnames, not_after = issue_broker_cert() except ValueError as exc: return jsonify({"error": str(exc)}), 400 return jsonify({"status": "issued", "hostnames": hostnames, "not_after": not_after}) if __name__ == "__main__": app.run(host="0.0.0.0", port=8099)