Files
eta bfefcbf636
build-and-push / check-branch (push) Successful in 14s
build-and-push / prepare (push) Successful in 8s
build-and-push / build (amd64, linux/amd64) (push) Successful in 19m43s
mcm: revokation
- Bug fix for revokation procedure
- Increased CRL (Certificate Revocation List) expiration from 7 days to 365
2026-11-07 11:36:38 +03:30

422 lines
15 KiB
Python

import base64
import datetime
import json
import logging
import os
import sys
from flask import Flask, jsonify, render_template, request
import store
from ca import CertificateAuthority, extract_cert_common_name, extract_csr_common_name
from challenges import ChallengeStore, csr_digest, renewal_message
from mqtt_worker import MqttWorker
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s")
log = logging.getLogger("main")
def _log_uncaught(exc_type, exc, tb):
# Python prints uncaught exceptions straight to stderr, bypassing
# logging entirely -- which is why a crash traceback had no timestamp
# while every other line did. Route it through the logger instead.
log.critical("uncaught exception, add-on is exiting", exc_info=(exc_type, exc, tb))
sys.excepthook = _log_uncaught
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"
# Single-use renewal challenges (see challenges.py). Nodes have no clock, so
# freshness comes from the server issuing a nonce rather than a timestamp.
challenge_store = ChallengeStore()
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": "homeassistant.local,192.168.1.80, core-mosquitto,localhost",
"renewal_window_days": 30,
"cert_organization": "",
"cert_organizational_unit": "",
}
if os.path.exists(OPTIONS_PATH):
with open(OPTIONS_PATH) as f:
defaults.update(json.load(f))
return defaults
options = load_options()
ca = CertificateAuthority(
organization=options["cert_organization"],
organizational_unit=options["cert_organizational_unit"],
)
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 resolve_common_name(device_id: str, csr_pem: str) -> str:
"""CN comes from the CSR itself -- devices set it there deliberately,
often shared across a whole device category (e.g. all TH sensors use
one CN, all light sensors another) for ACL grouping purposes. This
is intentionally NOT unique per device, unlike device_id.
Falls back to device_id only if the CSR has no CN at all (malformed
or lazy firmware) -- a safety net, not the intended path."""
from_csr = extract_csr_common_name(csr_pem)
return from_csr or device_id
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, common_name: 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. `common_name`
is resolved by the caller -- see resolve_common_name for fresh
issuance, and handle_renew's own logic for renewals (which must NOT
use CSR-based resolution -- it always keeps the existing CN)."""
from cryptography import x509
cert_pem = ca.sign_csr(csr_pem, common_name, 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_begin(device_id):
"""Step 1 of renewal: a node asks for a challenge.
Only devices that already hold an issued, non-revoked cert get one, so
strangers can't make the server accumulate nonces. A device that gets no
answer should fall back to an ordinary enrollment request."""
if store.is_revoked(device_id):
log.info("renewal challenge refused for %s: device is revoked", device_id)
return
if device_id not in store.list_issued():
log.info(
"renewal challenge refused for %s: no issued cert on record "
"(it needs a normal enrollment request)", device_id,
)
return
nonce, expires_in = challenge_store.issue(device_id)
mqtt_worker.publish_challenge(device_id, nonce, expires_in)
def handle_renew(device_id, csr_pem, nonce, signature_b64, meta):
"""Step 2 of renewal. Auto-issue a renewed cert IF, and only if, the
requester proves possession of the *currently on-record* cert's private
key by signing the server's challenge, that cert isn't revoked, and
we're actually within the renewal window.
The signature must cover renew-v1|device_id|nonce|sha256(DER(csr)), so
it is bound to this device, to a nonce this server issued (single-use,
short-lived), and to the exact CSR being certified. A captured request
can't be replayed (the nonce is spent) and can't be re-targeted at a
different key (the CSR digest wouldn't match).
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 that e.g. lost its challenge
still gets a cert eventually, just with human review.
CN handling for renewal is intentionally NOT the same as fresh
issuance: the renewed cert always keeps whatever CN the device's
CURRENT on-record cert already has. A renewal CSR's own CN (or any
other claimed identity) is never consulted -- renewal is about
extending validity / rotating keys, not about redefining who a
device is. Changing identity requires a fresh, humanly-approved
enrollment, not a renewal."""
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 store.is_revoked(device_id):
fall_back_to_manual("device is revoked")
return
existing_issued = store.list_issued().get(device_id)
if not existing_issued:
fall_back_to_manual("no prior issued cert on record")
return
not_after = datetime.datetime.fromisoformat(existing_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
if not nonce:
fall_back_to_manual("no challenge nonce supplied (old or malformed renewal request)")
return
# Cheap pre-check so we don't do signature work for a nonce that can't
# be valid. The atomic consume below is what actually enforces single use.
if not challenge_store.is_active(device_id, nonce):
fall_back_to_manual("no active challenge for this device, or the nonce is wrong, expired or already used")
return
try:
signature = base64.b64decode(signature_b64)
except Exception:
fall_back_to_manual("signature not valid base64")
return
# Rebuilt here from the CSR we actually received -- never from any
# digest or field the node sent alongside it.
try:
digest = csr_digest(csr_pem)
except ValueError:
fall_back_to_manual("CSR could not be parsed")
return
message = renewal_message(device_id, nonce, digest)
if not ca.verify_renewal_proof(existing_issued["cert"], message, signature):
fall_back_to_manual("proof-of-possession signature did not verify")
return
# Last gate before issuing. Invalid requests above never burn the nonce,
# and two concurrent requests with the same nonce can't both get here.
if not challenge_store.consume(device_id, nonce):
fall_back_to_manual("challenge was already used or has just expired")
return
# Past every check: keep the EXISTING cert's CN, full stop. Never
# derived from the new CSR for a renewal.
preserved_common_name = extract_cert_common_name(existing_issued["cert"]) or device_id
try:
_, new_not_after = finalize_issuance(device_id, csr_pem, preserved_common_name)
except ValueError as exc:
fall_back_to_manual(f"CSR rejected: {exc}")
return
log.info(
"auto-renewed cert for %s (proof verified), CN kept as %r, now valid until %s",
device_id, preserved_common_name, 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,
on_renew_begin=handle_renew_begin,
)
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():
pending = store.list_pending()
enriched = {}
for device_id, entry in pending.items():
enriched[device_id] = dict(entry)
# What CN WOULD be used if approved right now (from the CSR) --
# purely for display, not stored, since it's cheap to recompute
# and this way it's never stale.
enriched[device_id]["resolved_common_name"] = resolve_common_name(device_id, entry["csr"])
return jsonify(enriched)
@app.route("/api/issued")
def api_issued():
issued = store.list_issued()
enriched = {}
for device_id, entry in issued.items():
enriched[device_id] = dict(entry)
enriched[device_id]["common_name"] = extract_cert_common_name(entry["cert"])
return jsonify(enriched)
@app.route("/api/approve/<device_id>", 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
common_name = resolve_common_name(device_id, pending["csr"])
try:
_, not_after = finalize_issuance(device_id, pending["csr"], common_name, state=state)
except ValueError as exc:
return jsonify({"error": str(exc)}), 400
return jsonify({
"status": "issued", "device_id": device_id,
"common_name": common_name, "not_after": not_after,
})
@app.route("/api/reject/<device_id>", 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/<device_id>", 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)