198 lines
9.1 KiB
Python
198 lines
9.1 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-begin node -> here (payload ignored) asks for a renewal challenge
|
|
<prefix>/<device_id>/challenge here -> node {"nonce": "<hex>", "expires_in": <seconds>} (not retained)
|
|
<prefix>/<device_id>/renew node -> here {"csr": "<PEM>", "nonce": "<hex>", "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)
|
|
|
|
Renewal needs no clock on the node. The node asks for a challenge, gets a
|
|
single-use nonce back, and signs "renew-v1|<device_id>|<nonce>|<sha256 of
|
|
the CSR's DER>" 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,
|
|
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 time
|
|
|
|
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, on_renew_begin):
|
|
self.topic_prefix = topic_prefix.rstrip("/")
|
|
self.on_request = on_request # callback(device_id, csr_pem, 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:
|
|
self.client.username_pw_set(username, password or None)
|
|
self.client.on_connect = self._on_connect
|
|
self.client.on_disconnect = self._on_disconnect
|
|
self.client.on_message = self._on_message
|
|
|
|
self.host = host
|
|
self.port = port
|
|
|
|
def start(self):
|
|
# Returns immediately: the connect (and its retries) happen in the
|
|
# background, so a broker that isn't reachable YET -- e.g. Home
|
|
# Assistant just booted and Mosquitto hasn't started -- doesn't
|
|
# crash the whole add-on or block the web UI from coming up.
|
|
thread = threading.Thread(target=self._run, daemon=True, name="mqtt-worker")
|
|
thread.start()
|
|
|
|
def _run(self):
|
|
self.client.reconnect_delay_set(min_delay=1, max_delay=30)
|
|
delay = 1
|
|
while True:
|
|
try:
|
|
# This is the plain TCP connect. MQTT itself (CONNECT /
|
|
# CONNACK, auth) only starts once this succeeds.
|
|
self.client.connect(self.host, self.port, keepalive=60)
|
|
except OSError as exc:
|
|
# ConnectionRefusedError (nothing listening), gaierror
|
|
# (hostname doesn't resolve), timeouts, etc. all land here.
|
|
log.warning(
|
|
"cannot reach MQTT broker at %s:%s (%s: %s) - retrying in %ss. "
|
|
"Check the mqtt_host / mqtt_port options, and that Mosquitto is running.",
|
|
self.host, self.port, type(exc).__name__, exc, delay,
|
|
)
|
|
time.sleep(delay)
|
|
delay = min(delay * 2, 30)
|
|
continue
|
|
# Connected at the TCP level. From here paho handles drops and
|
|
# reconnects itself (using reconnect_delay_set above); this only
|
|
# returns if disconnect() is ever called explicitly.
|
|
self.client.loop_forever()
|
|
return
|
|
|
|
def _on_connect(self, client, userdata, flags, rc):
|
|
if rc != 0:
|
|
# The TCP connection worked but the BROKER said no -- a different
|
|
# failure from "connection refused". Usually bad credentials.
|
|
log.error(
|
|
"MQTT broker rejected the connection: %s "
|
|
"(check the mqtt_username / mqtt_password options)",
|
|
mqtt.connack_string(rc),
|
|
)
|
|
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, %s and %s",
|
|
request_topic, renew_begin_topic, renew_topic,
|
|
)
|
|
|
|
def _on_disconnect(self, client, userdata, rc):
|
|
if rc != 0:
|
|
log.warning("lost connection to MQTT broker (rc=%s); retrying automatically", rc)
|
|
|
|
def _on_message(self, client, userdata, msg):
|
|
parts = msg.topic.split("/")
|
|
if len(parts) < 2:
|
|
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:
|
|
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"]
|
|
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, 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"
|
|
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) |