9472cfff8d
- ca.sign_csr's identity parameter renamed to `common_name`, fully decoupled from device_id. - New resolve_common_name(): CN comes from the device's own CSR: falls back to device_id only if the CSR has no CN (malformed request). - Renewal unaffected: a renewed cert always keeps the CN of the device's current, still-valid cert, regardless of what the renewal CSR claims (verified against an adversarial CSR asserting a different CN). - device_id remains the sole storage key (pending/issued/revoked) and MQTT topic routing key, and must still be unique per physical device even when CN is deliberately shared across many. - /api/pending and /api/issued now also expose the CSR-resolved CN for display, without changing what's actually stored. No topic structure changes. No new MQTT payload fields.
117 lines
5.0 KiB
Python
117 lines
5.0 KiB
Python
"""
|
|
MQTT side of the enrollment protocol.
|
|
|
|
Topics (prefix is configurable, default "cert/enroll"):
|
|
<prefix>/<device_id>/request node -> here {"csr": "<PEM>", "meta": {...}}
|
|
<prefix>/<device_id>/renew node -> here {"csr": "<PEM>", "timestamp": <int>, "signature": "<base64>", "meta": {...}}
|
|
<prefix>/<device_id>/issued here -> node {"cert": "<PEM>", "ca": "<PEM>"} (retained)
|
|
<prefix>/<device_id>/rejected here -> node {"reason": "..."}
|
|
<prefix>/<device_id>/revoked here -> node {"reason": "..."} (best-effort notice; see DEVICE_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,
|
|
set from the CSR by main.py/ca.py, and may deliberately be shared across
|
|
many devices (e.g. one CN per device category) -- that has no bearing on
|
|
topic routing here.
|
|
|
|
See DEVICE_PROTOCOL.md for the full spec devices should implement.
|
|
"""
|
|
import json
|
|
import logging
|
|
import threading
|
|
|
|
import paho.mqtt.client as mqtt
|
|
|
|
import store
|
|
|
|
log = logging.getLogger("mqtt_worker")
|
|
|
|
|
|
class MqttWorker:
|
|
def __init__(self, host, port, username, password, topic_prefix, on_request, on_renew):
|
|
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.client = mqtt.Client(client_id="mqtt-cert-manager")
|
|
if username:
|
|
self.client.username_pw_set(username, password or None)
|
|
self.client.on_connect = self._on_connect
|
|
self.client.on_message = self._on_message
|
|
|
|
self.host = host
|
|
self.port = port
|
|
|
|
def start(self):
|
|
self.client.connect(self.host, self.port, keepalive=60)
|
|
thread = threading.Thread(target=self.client.loop_forever, daemon=True)
|
|
thread.start()
|
|
|
|
def _on_connect(self, client, userdata, flags, rc):
|
|
request_topic = f"{self.topic_prefix}/+/request"
|
|
renew_topic = f"{self.topic_prefix}/+/renew"
|
|
client.subscribe(request_topic, qos=1)
|
|
client.subscribe(renew_topic, qos=1)
|
|
log.info("connected to broker, subscribed to %s and %s", request_topic, renew_topic)
|
|
|
|
def _on_message(self, client, userdata, msg):
|
|
parts = msg.topic.split("/")
|
|
if len(parts) < 2:
|
|
return
|
|
device_id, kind = parts[-2], parts[-1]
|
|
|
|
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 kind == "request":
|
|
try:
|
|
csr_pem = payload["csr"]
|
|
except KeyError as exc:
|
|
log.warning("malformed request from %s: missing %s", device_id, exc)
|
|
return
|
|
log.info("enrollment request received from %s", device_id)
|
|
self.on_request(device_id, csr_pem, payload.get("meta", {}))
|
|
|
|
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
|
|
log.info("renewal request received from %s", device_id)
|
|
self.on_renew(device_id, csr_pem, timestamp, signature_b64, payload.get("meta", {}))
|
|
|
|
def publish_issued(self, device_id: str, cert_pem: str, ca_pem: str):
|
|
topic = f"{self.topic_prefix}/{device_id}/issued"
|
|
payload = json.dumps({"cert": cert_pem, "ca": ca_pem})
|
|
self.client.publish(topic, payload, qos=1, retain=True)
|
|
log.info("published issued cert for %s", device_id)
|
|
|
|
def publish_rejected(self, device_id: str, reason: str):
|
|
topic = f"{self.topic_prefix}/{device_id}/rejected"
|
|
self.client.publish(topic, json.dumps({"reason": reason}), qos=1, retain=False)
|
|
log.info("published rejection for %s: %s", device_id, reason)
|
|
|
|
def publish_revoked(self, device_id: str, reason: str):
|
|
"""Notify the device (if online) and clear the retained cert so a
|
|
rebooting/reconnecting device doesn't pick the old cert back up.
|
|
|
|
This is best-effort, not the actual enforcement mechanism — that's
|
|
the CRL Mosquitto checks during the TLS handshake. A device that's
|
|
offline or already mid-handshake won't see this message.
|
|
"""
|
|
revoked_topic = f"{self.topic_prefix}/{device_id}/revoked"
|
|
self.client.publish(revoked_topic, json.dumps({"reason": reason}), qos=1, retain=False)
|
|
|
|
# Publishing an empty, retained payload deletes the previous
|
|
# 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)
|