From e5478ed5ef3570ccb748ff2719fed6072404d23b Mon Sep 17 00:00:00 2001 From: Saman Sajedi Date: Wed, 14 Oct 2026 15:42:58 +0330 Subject: [PATCH] mcm renewal - Changed certificate renwal procedure --- mqtt-cert-manager/CHANGELOG.md | 4 ++ mqtt-cert-manager/app/challenges.py | 101 +++++++++++++++++++++++++++ mqtt-cert-manager/app/main.py | 84 ++++++++++++++++------ mqtt-cert-manager/app/mqtt_worker.py | 53 ++++++++++++-- mqtt-cert-manager/config.yaml | 2 +- 5 files changed, 216 insertions(+), 28 deletions(-) create mode 100644 mqtt-cert-manager/app/challenges.py diff --git a/mqtt-cert-manager/CHANGELOG.md b/mqtt-cert-manager/CHANGELOG.md index 93bd17a..2a75d52 100644 --- a/mqtt-cert-manager/CHANGELOG.md +++ b/mqtt-cert-manager/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.6.0 + +- Changed certificate renwal procedure + ## 0.5.2 - Improved logging and error handling diff --git a/mqtt-cert-manager/app/challenges.py b/mqtt-cert-manager/app/challenges.py new file mode 100644 index 0000000..c724010 --- /dev/null +++ b/mqtt-cert-manager/app/challenges.py @@ -0,0 +1,101 @@ +""" +Server-issued challenges for certificate renewal. + +Why this exists: a node with no trustworthy clock can't produce a timestamp +the server can check, so freshness has to come from the server instead. +For each renewal the server hands the node a random, single-use, short-lived +nonce, and the node signs that nonce together with a digest of its new CSR. +A captured renewal message is useless afterwards: the nonce is gone, and +swapping in a different CSR breaks the signature. + +State is in memory only. If the add-on restarts, outstanding challenges are +simply lost and the node asks for a new one. +""" +import hashlib +import hmac +import secrets +import threading +import time + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization + +CHALLENGE_TTL_SECONDS = 120 + +# Prefix on everything a node signs for renewal. It keeps a renewal +# signature from being valid in any other protocol that reuses the key. +RENEWAL_CONTEXT = "renew-v1" + + +def csr_digest(csr_pem: str) -> str: + """SHA-256 (hex) of the CSR's DER encoding. Raises ValueError if the CSR + doesn't parse. + + The DER form is hashed, not the PEM text, so line endings or whitespace + that differ between the node and the server don't change the result.""" + csr = x509.load_pem_x509_csr(csr_pem.encode()) + return hashlib.sha256(csr.public_bytes(serialization.Encoding.DER)).hexdigest() + + +def renewal_message(device_id: str, nonce: str, digest: str) -> bytes: + """The exact bytes a node signs to prove a renewal request.""" + return f"{RENEWAL_CONTEXT}|{device_id}|{nonce}|{digest}".encode() + + +class ChallengeStore: + """One active challenge per device. Thread-safe.""" + + def __init__(self, ttl: int = CHALLENGE_TTL_SECONDS, clock=time.monotonic): + self._ttl = ttl + self._clock = clock + self._lock = threading.Lock() + self._active = {} # device_id -> (nonce, expires_at) + + def _prune(self, now): + for device_id in [d for d, (_, exp) in self._active.items() if now >= exp]: + del self._active[device_id] + + def issue(self, device_id: str): + """Return (nonce, seconds_left) for this device. + + If the device already has an unexpired challenge, that same one is + returned instead of minting another. A node that missed the first + message can simply ask again, and nobody else can invalidate a + device's challenge by asking for a new one.""" + with self._lock: + now = self._clock() + self._prune(now) + current = self._active.get(device_id) + if current: + return current[0], max(1, int(current[1] - now)) + nonce = secrets.token_hex(32) + self._active[device_id] = (nonce, now + self._ttl) + return nonce, self._ttl + + def is_active(self, device_id: str, nonce) -> bool: + """Cheap non-consuming check, used to skip signature work for nonces + that can't possibly be valid. consume() is the real gate.""" + with self._lock: + current = self._active.get(device_id) + if not current or not isinstance(nonce, str): + return False + stored, expires_at = current + if self._clock() >= expires_at: + return False + return hmac.compare_digest(stored.encode(), nonce.encode()) + + def consume(self, device_id: str, nonce) -> bool: + """Atomically check and burn the nonce. True only for the first caller + presenting this device's current, unexpired nonce.""" + with self._lock: + current = self._active.get(device_id) + if not current: + return False + stored, expires_at = current + if self._clock() >= expires_at: + del self._active[device_id] + return False + if not isinstance(nonce, str) or not hmac.compare_digest(stored.encode(), nonce.encode()): + return False + del self._active[device_id] + return True \ No newline at end of file diff --git a/mqtt-cert-manager/app/main.py b/mqtt-cert-manager/app/main.py index 107145f..e555fe9 100644 --- a/mqtt-cert-manager/app/main.py +++ b/mqtt-cert-manager/app/main.py @@ -4,12 +4,12 @@ import json import logging import os import sys -import time 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") @@ -31,7 +31,10 @@ 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 + +# 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(): @@ -186,14 +189,41 @@ def finalize_issuance(device_id: str, csr_pem: str, common_name: str, state=None 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. +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 device_id in store.list_revoked(): + 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 with e.g. clock skew still - gets a cert eventually, just with human review. + 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 @@ -216,33 +246,46 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta): 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(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 - message = f"{device_id}|{int(ts)}|renew".encode() + # 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 @@ -267,6 +310,7 @@ mqtt_worker = MqttWorker( topic_prefix=options["request_topic_prefix"], on_request=handle_request, on_renew=handle_renew, + on_renew_begin=handle_renew_begin, ) mqtt_worker.start() @@ -375,4 +419,4 @@ def api_broker_cert_reissue(): if __name__ == "__main__": - app.run(host="0.0.0.0", port=8099) + app.run(host="0.0.0.0", port=8099) \ No newline at end of file diff --git a/mqtt-cert-manager/app/mqtt_worker.py b/mqtt-cert-manager/app/mqtt_worker.py index 1a05d7d..489fe45 100644 --- a/mqtt-cert-manager/app/mqtt_worker.py +++ b/mqtt-cert-manager/app/mqtt_worker.py @@ -3,11 +3,18 @@ MQTT side of the enrollment protocol. Topics (prefix is configurable, default "cert/enroll"): //request node -> here {"csr": "", "meta": {...}} - //renew node -> here {"csr": "", "timestamp": , "signature": "", "meta": {...}} + //renew-begin node -> here (payload ignored) asks for a renewal challenge + //challenge here -> node {"nonce": "", "expires_in": } (not retained) + //renew node -> here {"csr": "", "nonce": "", "signature": "", "meta": {...}} //issued here -> node {"cert": "", "ca": ""} (retained) //rejected here -> node {"reason": "..."} //revoked here -> node {"reason": "..."} (best-effort notice; see DEVICE_PROTOCOL.md) +Renewal needs no clock on the node. The node asks for a challenge, gets a +single-use nonce back, and signs "renew-v1|||" with its CURRENT key. See challenges.py and +RENEWAL_PROTOCOL.md. + device_id is expected to be unique per physical device (not a shared bootstrap identity) -- that's what makes per-device topics work without any extra filtering in the payload. The cert's CN is a separate concern, @@ -30,10 +37,11 @@ log = logging.getLogger("mqtt_worker") class MqttWorker: - def __init__(self, host, port, username, password, topic_prefix, on_request, on_renew): + def __init__(self, host, port, username, password, topic_prefix, on_request, on_renew, on_renew_begin): self.topic_prefix = topic_prefix.rstrip("/") self.on_request = on_request # callback(device_id, csr_pem, meta) - self.on_renew = on_renew # callback(device_id, csr_pem, timestamp, signature_b64, meta) + self.on_renew_begin = on_renew_begin # callback(device_id) + self.on_renew = on_renew # callback(device_id, csr_pem, nonce, signature_b64, meta) self.client = mqtt.Client(client_id="mqtt-cert-manager") if username: @@ -89,10 +97,15 @@ class MqttWorker: ) return request_topic = f"{self.topic_prefix}/+/request" + renew_begin_topic = f"{self.topic_prefix}/+/renew-begin" renew_topic = f"{self.topic_prefix}/+/renew" client.subscribe(request_topic, qos=1) + client.subscribe(renew_begin_topic, qos=1) client.subscribe(renew_topic, qos=1) - log.info("connected to broker, subscribed to %s and %s", request_topic, renew_topic) + log.info( + "connected to broker, subscribed to %s, %s and %s", + request_topic, renew_begin_topic, renew_topic, + ) def _on_disconnect(self, client, userdata, rc): if rc != 0: @@ -104,11 +117,21 @@ class MqttWorker: return device_id, kind = parts[-2], parts[-1] + if kind == "renew-begin": + # Nothing in this payload is used, so don't insist on valid JSON + # (a node may well send an empty message). + log.info("renewal challenge requested by %s", device_id) + self.on_renew_begin(device_id) + return + try: payload = json.loads(msg.payload.decode()) except ValueError as exc: log.warning("malformed payload from %s on %s: %s", device_id, msg.topic, exc) return + if not isinstance(payload, dict): + log.warning("malformed payload from %s on %s: expected a JSON object", device_id, msg.topic) + return if kind == "request": try: @@ -122,13 +145,29 @@ class MqttWorker: elif kind == "renew": try: csr_pem = payload["csr"] - timestamp = payload["timestamp"] signature_b64 = payload["signature"] except KeyError as exc: log.warning("malformed renewal from %s: missing %s", device_id, exc) return + if not isinstance(csr_pem, str): + log.warning("malformed renewal from %s: csr must be a string", device_id) + return + nonce = payload.get("nonce") + if nonce is None and "timestamp" in payload: + log.warning( + "renewal from %s uses the old timestamp format, which is no longer " + "supported; it will go to manual approval", device_id, + ) log.info("renewal request received from %s", device_id) - self.on_renew(device_id, csr_pem, timestamp, signature_b64, payload.get("meta", {})) + self.on_renew(device_id, csr_pem, nonce, signature_b64, payload.get("meta", {})) + + def publish_challenge(self, device_id: str, nonce: str, expires_in: int): + # Deliberately NOT retained: a retained challenge would be handed to + # any later subscriber long after it expired. + topic = f"{self.topic_prefix}/{device_id}/challenge" + payload = json.dumps({"nonce": nonce, "expires_in": expires_in}) + self.client.publish(topic, payload, qos=1, retain=False) + log.info("published renewal challenge for %s (valid %ss)", device_id, expires_in) def publish_issued(self, device_id: str, cert_pem: str, ca_pem: str): topic = f"{self.topic_prefix}/{device_id}/issued" @@ -156,4 +195,4 @@ class MqttWorker: # retained message on the broker (per MQTT spec). issued_topic = f"{self.topic_prefix}/{device_id}/issued" self.client.publish(issued_topic, payload=b"", qos=1, retain=True) - log.info("published revocation for %s and cleared retained cert", device_id) + log.info("published revocation for %s and cleared retained cert", device_id) \ No newline at end of file diff --git a/mqtt-cert-manager/config.yaml b/mqtt-cert-manager/config.yaml index bf94864..69c8e0b 100644 --- a/mqtt-cert-manager/config.yaml +++ b/mqtt-cert-manager/config.yaml @@ -1,5 +1,5 @@ name: "MQTT Certificate Manager" -version: "0.5.2" +version: "0.6.0" slug: "mqtt_cert_manager" description: "Local CA that issues and manages TLS client certificates for MQTT nodes" url: "https://gitea.viratak.com/bitopa/virarepo/src/branch/main/mqtt-cert-manager"