initial commit
build-and-push / build (aarch64, linux/arm64) (push) Has been cancelled
build-and-push / build (amd64, linux/amd64) (push) Has been cancelled
build-and-push / build (armhf, linux/arm/v6) (push) Has been cancelled
build-and-push / build (armv7, linux/arm/v7) (push) Has been cancelled
build-and-push / build (i386, linux/386) (push) Has been cancelled

This commit is contained in:
2026-08-02 15:35:21 +03:30
commit 0e084adf8d
19 changed files with 1547 additions and 0 deletions
+151
View File
@@ -0,0 +1,151 @@
# Device enrollment protocol
This is the contract a node's firmware needs to implement to get a client
certificate from the add-on. It assumes the node can already reach the
MQTT broker (unauthenticated, or with a shared bootstrap username/password
— see "Security notes" below).
Default topic prefix is `cert/enroll`, configurable in the add-on options.
Replace `<device_id>` with a stable, unique identifier for the node (e.g.
its MAC address with colons stripped, or a serial number). This value is
used as both the MQTT topic segment and the certificate's Common Name /
SAN, so keep it short, DNS-safe, and unique on your network.
## 1. Generate a key pair and CSR (on-device, once)
The private key never leaves the device. Generate an RSA-2048 (or EC
P-256) key pair and a PKCS#10 CSR with:
- Common Name = `<device_id>`
- No need for extensions in the CSR itself; the add-on sets the ones that
matter (basic constraints, key usage, SAN) when it signs.
Persist the key pair to flash. If a cert is later lost or expires, reuse
the same key and just repeat step 2 — no need to regenerate the key.
## 2. Publish the request
Topic: `cert/enroll/<device_id>/request`
QoS: 1, retain: false
Payload (JSON):
```json
{
"csr": "-----BEGIN CERTIFICATE REQUEST-----\n...\n-----END CERTIFICATE REQUEST-----\n",
"meta": {
"model": "esp32-sensor-v2",
"fw_version": "1.4.0"
}
}
```
`meta` is optional and only shown to the human approving the request — put
anything there that helps you recognize the device in the UI.
## 3. Subscribe for the result, before or immediately after publishing
Subscribe to both of these (QoS 1) so you catch whichever response comes:
- `cert/enroll/<device_id>/issued` — retained. Payload:
```json
{
"cert": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n",
"ca": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n"
}
```
Because this is retained, if the device subscribes *after* a cert was
already issued (e.g. after a reboot), it will receive it immediately
without needing to re-request.
- `cert/enroll/<device_id>/rejected` — not retained. Payload:
```json
{ "reason": "human-readable reason" }
```
- `cert/enroll/<device_id>/revoked` — not retained, best-effort only.
Payload:
```json
{ "reason": "human-readable reason" }
```
Sent if you revoke a device's cert after it was issued. This is
informational — actual enforcement happens at the TLS layer via
Mosquitto's CRL check, which a revoked device will hit on its *next*
connection attempt regardless of whether it saw this message. Devices
aren't required to act on it, but it's a convenient hook if you want
firmware to, say, stop operating or blink an error LED immediately
rather than waiting for the next failed connection.
## 4. Install and reconnect
Store `cert` and `ca` to flash alongside the existing private key.
Reconnect to the broker using mutual TLS (client cert + key, broker CA
trust anchor = the same `ca`). Once confirmed working, you can stop
listening on the unauthenticated bootstrap connection for that device.
## 5. Renewal
Devices are trusted to renew themselves automatically once they're within
`renewal_window_days` (default 30) of `not_after` — **no human approval
needed** — but only by proving they still hold the private key matching
their *currently valid* cert. Anything that fails that proof, or is
requested too early, silently falls back to the normal manual-approval
queue (same as a first-time device), rather than being rejected outright.
Topic: `cert/enroll/<device_id>/renew`
QoS: 1, retain: false
Payload (JSON):
```json
{
"csr": "-----BEGIN CERTIFICATE REQUEST-----\n...\n-----END CERTIFICATE REQUEST-----\n",
"timestamp": 1785400000,
"signature": "<base64>",
"meta": { "...": "optional, same as the request topic" }
}
```
- `csr` — a fresh CSR. Reusing the same key pair is fine and simplest;
generating a new key pair here is also fine (and arguably better
hygiene) since this CSR only needs to be *valid*, not signed by
anything — the proof of identity comes from `signature` below, which
is signed by the **current, not-yet-expired** key, not the new one.
- `timestamp` — current Unix time (seconds), integer. Must be within 5
minutes of the add-on's clock or the renewal is rejected as stale
(replay protection) — keep device clocks roughly in sync (SNTP).
- `signature` — base64-encoded signature over the exact ASCII string
`"<device_id>|<timestamp>|renew"` (e.g. `"sensor-01|1785400000|renew"`),
produced with the device's **current** private key (the one matching
its currently valid, not-yet-expired cert — not the new key in `csr`,
if you generated one).
- RSA keys: PKCS#1 v1.5 padding, SHA-256.
- EC keys: ECDSA, SHA-256.
On success, the response arrives on the same `.../issued` topic as a
normal enrollment (retained, same payload shape) — no separate topic to
watch for renewals.
If nothing on the device changed, the simplest implementation is: every
boot, or on a periodic timer, check how close `not_after` (which you
should have stored from the last `issued` payload) is to now; if within
the renewal window, sign and publish a renewal request; watch `.../issued`
for the (possibly unretained, freshly-published) response same as usual.
## Security notes
- The bootstrap request (step 2) travels over an unauthenticated or
broker-credentialed-but-unencrypted connection — that's inherent to any
"first contact" enrollment flow. The mitigating control is that a human
must explicitly approve each device in the add-on UI before anything is
issued; nothing is auto-approved *on first enrollment*.
- Renewal (step 5) is the one place a cert gets issued without a human in
the loop, and it's gated entirely on a working proof-of-possession
signature — a device (or attacker) that doesn't already hold the
current private key cannot get a free renewal no matter what it sends;
it's routed to the manual queue exactly like a stranger would be.
- If you want defense in depth beyond human approval on first enrollment,
consider adding a shared enrollment secret that devices include in
`meta` and the add-on checks before showing a request as approvable
(not implemented in this scaffold, but ca.py/main.py are small — this
is a natural next add).
- Because the device generates its own key pair and only ever sends a
public-key CSR over the wire, the private key is never exposed to the
network or to the add-on, even to a passive eavesdropper on the
bootstrap connection.
+19
View File
@@ -0,0 +1,19 @@
ARG BUILD_FROM
FROM ${BUILD_FROM}
RUN apk add --no-cache python3 py3-pip
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --break-system-packages -r requirements.txt
COPY app/ /app/
COPY run.sh /run.sh
RUN chmod a+x /run.sh
LABEL \
io.hass.version="0.1.0" \
io.hass.type="addon" \
io.hass.arch="armhf|armv7|aarch64|amd64|i386"
CMD ["/run.sh"]
+103
View File
@@ -0,0 +1,103 @@
# MQTT Certificate Manager (Home Assistant add-on)
Issues and manages TLS client certificates for MQTT nodes from a local,
self-signed CA — no external CA or internet dependency.
## How it works
0. On first boot, the add-on also issues a TLS **server** certificate for
the broker itself (signed by the same local CA) and writes it — plus
the CA cert — into Home Assistant's shared `/ssl` folder. Open the
add-on's "Broker TLS certificate" section for the exact `certfile` /
`keyfile` / `cafile` values to paste into the Mosquitto add-on's
config, then set `require_certificate: true` there and restart
Mosquitto. The `broker_hostnames` option (comma-separated) controls
what hostnames/IPs the cert is valid for — add your LAN hostname or
static IP here if devices reach the broker by something other than
`core-mosquitto`.
1. A node generates its own key pair + CSR and publishes it over MQTT.
2. The add-on picks it up and lists it as a pending request in its web UI
(available as a Home Assistant sidebar panel via ingress).
3. You review and click Approve.
4. The add-on's local CA signs the cert and publishes it (+ the CA cert)
back to the node over a retained MQTT topic.
5. The node installs the cert and reconnects to the broker over mTLS.
6. If you later revoke a device's cert from the UI, the add-on rewrites
the CRL at `/ssl/mqtt-cert-manager-crl.pem` and clears the device's
retained MQTT cert. Point Mosquitto's `crlfile` option at that file —
it's only reloaded on **restart**, not live, so a revocation doesn't
take effect until Mosquitto restarts.
Full device-side wire protocol: see `DEVICE_PROTOCOL.md`.
## Installing this add-on
1. Copy this folder into your Home Assistant add-ons repository (or add
it as a local add-on under `/addons/mqtt_cert_manager` on HAOS).
2. In Settings → Add-ons → Add-on store → ⋮ → Repositories, add your repo
if it's not local, then install "MQTT Certificate Manager".
3. Configure the options (mqtt_host defaults to `core-mosquitto`, which is
correct if you're using the official Mosquitto broker add-on).
4. Start the add-on and open it from the sidebar.
## What's included in this scaffold
- `config.yaml` / `build.yaml` — add-on manifest, current (2026) HA base
image convention. **Double check `build.yaml` against
https://github.com/home-assistant/docker-base if your Supervisor
version is very new or old** — base image tags do change.
- `app/ca.py` — root CA generation + CSR signing (RSA-4096 root, 20-year
validity; issued certs default to 825 days, matching common CT/browser
practice, though these are just client certs so it's a soft ceiling you
control via the `cert_validity_days` option).
- `app/mqtt_worker.py` — subscribes for requests, publishes issued/rejected.
- `app/store.py` — flat JSON store for pending/issued state in `/data`.
- `app/main.py` + `app/templates`, `app/static` — Flask app and the
approve/reject UI.
## Access control
The web UI and its `/api/*` endpoints have **no login of their own**. They
rely entirely on two things, both required together:
1. `config.yaml` has no `ports:` entry, so Supervisor never exposes port
8099 to your LAN or host — the only path in is Supervisor's ingress
proxy, which requires an authenticated Home Assistant session.
2. `main.py` rejects any request whose source IP isn't Supervisor's fixed
internal proxy address (`172.30.32.2`), per HA's own guidance for
ingress-only add-ons. Without this, any other add-on on the same
internal Docker network could call `/api/approve/...` directly and
bypass HA login entirely.
If you ever add a `ports:` mapping for direct access (e.g. for local
testing outside HA), you must add real authentication first — the IP
guard alone won't help once the port is exposed to the LAN.
## Known gaps to close before production use
- **Mosquitto still requires a username/password per device even with a
client cert.** The official Mosquitto add-on's auth plugin doesn't
reliably support `use_identity_as_username` (cert-only auth) — you'll
need to give each device MQTT login credentials in addition to its
cert. The cert still buys you encryption + mutual authentication; it
just isn't a full substitute for a password on this particular broker
add-on.
- **Auto-renewal exists, but only for cert holders in good standing.**
Within `renewal_window_days` of expiry, a device can renew without a
human clicking Approve — but only by signing a proof-of-possession
message with its *current* private key (see `DEVICE_PROTOCOL.md` §5).
Anything that fails that check (wrong key, revoked, too early, stale
timestamp, never enrolled before) falls back to the normal manual
queue rather than being silently issued or silently dropped.
- **Revocation requires a Mosquitto restart to take effect.** CRL support
is in (`/api/revoke`, `write_crl()`), but there's no push mechanism to
restart Mosquitto automatically — you have to do it yourself after
revoking. No OCSP either; CRL-only.
- **No shared enrollment secret.** The human-approval step is the only
gate on the bootstrap channel right now; see the security note in
DEVICE_PROTOCOL.md if you want an extra layer.
- I haven't built or run this against a live Supervisor — treat it as a
solid, working starting point rather than a tested release. The Python
logic (CA, signing, MQTT topics) is self-contained and testable outside
Home Assistant if you want to validate it first with a local Mosquitto
broker.
+259
View File
@@ -0,0 +1,259 @@
"""
Local certificate authority for MQTT node client certs.
On first run, generates a self-signed root CA (key + cert) and stores it
under /data/ca/. All later runs reuse that CA so previously issued device
certs stay valid until they naturally expire.
"""
import datetime
import ipaddress
import os
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
from cryptography.x509.oid import NameOID
DATA_DIR = "/data"
CA_DIR = os.path.join(DATA_DIR, "ca")
CA_KEY_PATH = os.path.join(CA_DIR, "ca.key")
CA_CERT_PATH = os.path.join(CA_DIR, "ca.crt")
CA_COMMON_NAME = "Home Assistant Local MQTT CA"
CA_VALIDITY_YEARS = 20
class CertificateAuthority:
def __init__(self):
os.makedirs(CA_DIR, exist_ok=True)
if not (os.path.exists(CA_KEY_PATH) and os.path.exists(CA_CERT_PATH)):
self._generate_root_ca()
self._load_root_ca()
# -- setup ---------------------------------------------------------
def _generate_root_ca(self):
key = rsa.generate_private_key(public_exponent=65537, key_size=4096)
subject = issuer = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, CA_COMMON_NAME)]
)
now = datetime.datetime.now(datetime.timezone.utc)
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(issuer)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(days=1))
.not_valid_after(now + datetime.timedelta(days=365 * CA_VALIDITY_YEARS))
.add_extension(
x509.BasicConstraints(ca=True, path_length=0), critical=True
)
.add_extension(
x509.KeyUsage(
digital_signature=True,
key_cert_sign=True,
crl_sign=True,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
encipher_only=False,
decipher_only=False,
),
critical=True,
)
.add_extension(
x509.SubjectKeyIdentifier.from_public_key(key.public_key()),
critical=False,
)
.sign(key, hashes.SHA256())
)
with open(CA_KEY_PATH, "wb") as f:
f.write(
key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
)
os.chmod(CA_KEY_PATH, 0o600)
with open(CA_CERT_PATH, "wb") as f:
f.write(cert.public_bytes(serialization.Encoding.PEM))
def _load_root_ca(self):
with open(CA_KEY_PATH, "rb") as f:
self.key = serialization.load_pem_private_key(f.read(), password=None)
with open(CA_CERT_PATH, "rb") as f:
self.cert_pem = f.read()
self.cert = x509.load_pem_x509_certificate(self.cert_pem)
# -- signing ---------------------------------------------------------
def ca_cert_pem(self) -> str:
return self.cert_pem.decode()
def sign_csr(self, csr_pem: str, device_id: str, validity_days: int) -> str:
"""Validate and sign a device CSR. Returns the signed cert as PEM.
Raises ValueError on a malformed or untrustworthy CSR.
"""
try:
csr = x509.load_pem_x509_csr(csr_pem.encode())
except ValueError as exc:
raise ValueError(f"could not parse CSR: {exc}") from exc
if not csr.is_signature_valid:
raise ValueError("CSR signature is invalid")
now = datetime.datetime.now(datetime.timezone.utc)
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, device_id)])
builder = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(self.cert.subject)
.public_key(csr.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=5))
.not_valid_after(now + datetime.timedelta(days=validity_days))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(
x509.KeyUsage(
digital_signature=True,
key_encipherment=True,
content_commitment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
),
critical=True,
)
.add_extension(
x509.ExtendedKeyUsage([x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH]),
critical=False,
)
.add_extension(
x509.SubjectAlternativeName([x509.DNSName(device_id)]),
critical=False,
)
)
cert = builder.sign(self.key, hashes.SHA256())
return cert.public_bytes(serialization.Encoding.PEM).decode()
def issue_server_cert(self, hostnames: list[str], validity_days: int):
"""Generate a fresh key pair + server cert for the MQTT broker itself.
Unlike sign_csr, the add-on generates this key pair (the broker
needs the key file handed to it directly; there's no CSR step
since Mosquitto doesn't produce one). Returns (key_pem, cert_pem).
"""
if not hostnames:
raise ValueError("at least one hostname/IP is required")
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
now = datetime.datetime.now(datetime.timezone.utc)
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, hostnames[0])])
san_entries = []
for name in hostnames:
try:
san_entries.append(x509.IPAddress(ipaddress.ip_address(name)))
except ValueError:
san_entries.append(x509.DNSName(name))
cert = (
x509.CertificateBuilder()
.subject_name(subject)
.issuer_name(self.cert.subject)
.public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(now - datetime.timedelta(minutes=5))
.not_valid_after(now + datetime.timedelta(days=validity_days))
.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
.add_extension(
x509.KeyUsage(
digital_signature=True,
key_encipherment=True,
content_commitment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
),
critical=True,
)
.add_extension(
x509.ExtendedKeyUsage([x509.oid.ExtendedKeyUsageOID.SERVER_AUTH]),
critical=False,
)
.add_extension(x509.SubjectAlternativeName(san_entries), critical=False)
.sign(self.key, hashes.SHA256())
)
key_pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
).decode()
cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode()
return key_pem, cert_pem
def build_crl(self, revoked_entries: list) -> str:
"""Build a signed Certificate Revocation List.
revoked_entries: list of (serial_number: int, revoked_at: datetime)
tuples. Mosquitto's `crlfile` option points at this file's output
and rejects any client cert whose serial appears in it during the
TLS handshake — but only picks up changes on restart, not live.
"""
now = datetime.datetime.now(datetime.timezone.utc)
builder = (
x509.CertificateRevocationListBuilder()
.issuer_name(self.cert.subject)
.last_update(now)
.next_update(now + datetime.timedelta(days=7))
)
for serial, revoked_at in revoked_entries:
revoked_cert = (
x509.RevokedCertificateBuilder()
.serial_number(serial)
.revocation_date(revoked_at)
.build()
)
builder = builder.add_revoked_certificate(revoked_cert)
crl = builder.sign(private_key=self.key, algorithm=hashes.SHA256())
return crl.public_bytes(serialization.Encoding.PEM).decode()
def verify_renewal_proof(self, current_cert_pem: str, message: bytes, signature: bytes) -> bool:
"""Check that `signature` over `message` was produced by the
private key matching `current_cert_pem`'s public key.
This is the whole trust basis for skipping human approval on
renewal: it proves the requester currently holds the private key
for an already-issued, still-on-record cert — not just that they
claim to be that device. Returns False (never raises) on any
failure, since callers should treat "couldn't verify" and
"verification failed" identically: fall back to manual approval.
"""
try:
cert = x509.load_pem_x509_certificate(current_cert_pem.encode())
public_key = cert.public_key()
if isinstance(public_key, rsa.RSAPublicKey):
public_key.verify(signature, message, padding.PKCS1v15(), hashes.SHA256())
elif isinstance(public_key, ec.EllipticCurvePublicKey):
public_key.verify(signature, message, ec.ECDSA(hashes.SHA256()))
else:
return False
return True
except Exception:
return False
+316
View File
@@ -0,0 +1,316 @@
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/<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
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/<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)
+109
View File
@@ -0,0 +1,109 @@
"""
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)
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)
+142
View File
@@ -0,0 +1,142 @@
async function refreshPending() {
const res = await fetch("api/pending");
const data = await res.json();
const tbody = document.querySelector("#pending-table tbody");
const empty = document.getElementById("pending-empty");
tbody.innerHTML = "";
const ids = Object.keys(data);
empty.style.display = ids.length ? "none" : "block";
for (const deviceId of ids) {
const entry = data[deviceId];
const row = document.createElement("tr");
const requested = new Date(entry.requested_at * 1000).toLocaleString();
const meta = Object.entries(entry.meta || {}).map(([k, v]) => `${k}: ${v}`).join(", ");
row.innerHTML = `
<td>${deviceId}</td>
<td>${requested}</td>
<td>${meta || "-"}</td>
<td>
<button class="approve" data-id="${deviceId}">Approve</button>
<button class="reject" data-id="${deviceId}">Reject</button>
</td>`;
tbody.appendChild(row);
}
tbody.querySelectorAll(".approve").forEach((btn) =>
btn.addEventListener("click", () => approve(btn.dataset.id))
);
tbody.querySelectorAll(".reject").forEach((btn) =>
btn.addEventListener("click", () => reject(btn.dataset.id))
);
}
async function refreshIssued() {
const [issuedRes, revokedRes] = await Promise.all([fetch("api/issued"), fetch("api/revoked")]);
const data = await issuedRes.json();
const revoked = await revokedRes.json();
const tbody = document.querySelector("#issued-table tbody");
const empty = document.getElementById("issued-empty");
tbody.innerHTML = "";
const ids = Object.keys(data);
empty.style.display = ids.length ? "none" : "block";
for (const deviceId of ids) {
const entry = data[deviceId];
const row = document.createElement("tr");
const issued = new Date(entry.issued_at * 1000).toLocaleString();
const expires = new Date(entry.not_after).toLocaleDateString();
const isRevoked = Object.prototype.hasOwnProperty.call(revoked, deviceId);
const action = isRevoked
? `<span class="empty">revoked</span>`
: `<button class="revoke" data-id="${deviceId}">Revoke</button>`;
row.innerHTML = `<td>${deviceId}</td><td>${issued}</td><td>${expires}</td><td>${action}</td>`;
tbody.appendChild(row);
}
tbody.querySelectorAll(".revoke").forEach((btn) =>
btn.addEventListener("click", () => revoke(btn.dataset.id))
);
}
async function refreshRevoked() {
const res = await fetch("api/revoked");
const data = await res.json();
const tbody = document.querySelector("#revoked-table tbody");
const empty = document.getElementById("revoked-empty");
tbody.innerHTML = "";
const ids = Object.keys(data);
empty.style.display = ids.length ? "none" : "block";
for (const deviceId of ids) {
const entry = data[deviceId];
const row = document.createElement("tr");
const revokedAt = new Date(entry.revoked_at * 1000).toLocaleString();
row.innerHTML = `<td>${deviceId}</td><td>${revokedAt}</td><td>${entry.reason}</td>`;
tbody.appendChild(row);
}
}
async function approve(deviceId) {
const res = await fetch(`api/approve/${encodeURIComponent(deviceId)}`, { method: "POST" });
if (!res.ok) {
const err = await res.json();
alert(`Could not issue certificate: ${err.error}`);
}
await refresh();
}
async function reject(deviceId) {
await fetch(`api/reject/${encodeURIComponent(deviceId)}`, { method: "POST" });
await refresh();
}
async function revoke(deviceId) {
if (!confirm(`Revoke the certificate for "${deviceId}"? This can't be undone, and requires a Mosquitto restart to take effect.`)) return;
const res = await fetch(`api/revoke/${encodeURIComponent(deviceId)}`, { method: "POST" });
if (!res.ok) {
const err = await res.json();
alert(`Could not revoke: ${err.error}`);
}
await refresh();
}
async function refreshBrokerCert() {
const res = await fetch("api/broker-cert");
const data = await res.json();
const statusEl = document.getElementById("broker-cert-status");
const configEl = document.getElementById("broker-cert-config");
if (!data.info) {
statusEl.textContent = "Not yet issued.";
} else {
const expires = new Date(data.info.not_after).toLocaleDateString();
statusEl.textContent = `Covers: ${data.info.hostnames.join(", ")} — expires ${expires}`;
}
configEl.textContent =
`certfile: ${data.cert_filename}\n` +
`keyfile: ${data.key_filename}\n` +
`require_certificate: true\n` +
`cafile: ${data.ca_filename}`;
}
document.getElementById("reissue-broker-cert").addEventListener("click", async () => {
if (!confirm("Reissue the broker's TLS certificate? Mosquitto will need a restart to pick up the new files.")) return;
const res = await fetch("api/broker-cert/reissue", { method: "POST" });
if (!res.ok) {
const err = await res.json();
alert(`Could not reissue: ${err.error}`);
}
await refreshBrokerCert();
});
async function refresh() {
await refreshPending();
await refreshIssued();
await refreshRevoked();
await refreshBrokerCert();
}
refresh();
setInterval(refresh, 5000);
+19
View File
@@ -0,0 +1,19 @@
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
max-width: 800px;
margin: 2rem auto;
padding: 0 1rem;
color: #212121;
}
h1 { font-size: 1.4rem; font-weight: 500; }
h2 { font-size: 1.1rem; font-weight: 500; margin-top: 2rem; }
table { width: 100%; border-collapse: collapse; margin-top: 0.5rem; }
th, td { text-align: left; padding: 0.5rem; border-bottom: 1px solid #e0e0e0; font-size: 0.9rem; }
th { color: #757575; font-weight: 500; }
button { padding: 0.35rem 0.8rem; border-radius: 6px; border: none; cursor: pointer; font-size: 0.85rem; margin-right: 0.4rem; }
.approve { background: #43a047; color: white; }
.reject { background: #e53935; color: white; }
.empty { color: #757575; font-size: 0.9rem; }
.note { color: #757575; font-size: 0.85rem; margin-top: 0.25rem; }
pre { background: #f5f5f5; padding: 0.75rem; border-radius: 6px; font-size: 0.85rem; overflow-x: auto; }
code { background: #f5f5f5; padding: 0.1rem 0.3rem; border-radius: 4px; }
+117
View File
@@ -0,0 +1,117 @@
"""Simple JSON-file store for pending requests and issued cert records.
A real deployment could swap this for sqlite, but request volume here is
tiny (one entry per physical device) so a flat file is fine and easy to
inspect/back up.
"""
import json
import os
import threading
import time
STATE_PATH = "/data/state.json"
_lock = threading.Lock()
def _load():
if not os.path.exists(STATE_PATH):
return {"pending": {}, "issued": {}, "revoked": {}, "broker_cert": None}
with open(STATE_PATH, "r") as f:
state = json.load(f)
state.setdefault("broker_cert", None)
state.setdefault("revoked", {})
return state
def _save(state):
tmp_path = STATE_PATH + ".tmp"
with open(tmp_path, "w") as f:
json.dump(state, f, indent=2)
os.replace(tmp_path, STATE_PATH)
def add_pending(device_id: str, csr_pem: str, meta: dict):
with _lock:
state = _load()
state["pending"][device_id] = {
"csr": csr_pem,
"meta": meta or {},
"requested_at": time.time(),
}
_save(state)
def list_pending():
with _lock:
return _load()["pending"]
def pop_pending(device_id: str):
with _lock:
state = _load()
return state["pending"].pop(device_id, None), state
def list_issued():
with _lock:
return _load()["issued"]
def mark_issued(device_id: str, cert_pem: str, not_after: str, serial: int, state=None):
with _lock:
state = state or _load()
state["issued"][device_id] = {
"cert": cert_pem,
"not_after": not_after,
"issued_at": time.time(),
"serial": serial,
}
_save(state)
def reject_pending(device_id: str, reason: str):
with _lock:
state = _load()
state["pending"].pop(device_id, None)
_save(state)
def get_broker_cert():
with _lock:
return _load()["broker_cert"]
def set_broker_cert(hostnames: list, not_after: str):
with _lock:
state = _load()
state["broker_cert"] = {
"hostnames": hostnames,
"not_after": not_after,
"issued_at": time.time(),
}
_save(state)
def revoke_device(device_id: str, reason: str):
"""Move a device from issued -> revoked. Keeps the issued record too
(for audit history) but also records it separately so the CRL builder
has a fast list to work from. Returns the serial number, or None if
the device has no issued cert on record."""
with _lock:
state = _load()
issued = state["issued"].get(device_id)
if not issued:
return None
state["revoked"][device_id] = {
"serial": issued["serial"],
"reason": reason,
"revoked_at": time.time(),
}
_save(state)
return issued["serial"]
def list_revoked():
with _lock:
return _load()["revoked"]
@@ -0,0 +1,49 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MQTT Certificate Manager</title>
<link rel="stylesheet" href="static/style.css">
</head>
<body>
<h1>MQTT certificate manager</h1>
<section>
<h2>Pending requests</h2>
<table id="pending-table">
<thead><tr><th>Device</th><th>Requested</th><th>Info</th><th></th></tr></thead>
<tbody></tbody>
</table>
<p id="pending-empty" class="empty" style="display:none">No pending requests. Nodes that ask for a certificate will show up here.</p>
</section>
<section>
<h2>Issued certificates</h2>
<table id="issued-table">
<thead><tr><th>Device</th><th>Issued</th><th>Expires</th><th></th></tr></thead>
<tbody></tbody>
</table>
<p id="issued-empty" class="empty" style="display:none">No certificates issued yet.</p>
</section>
<section>
<h2>Revoked certificates</h2>
<p class="note">Revocation takes effect after Mosquitto is restarted — it reloads the CRL file on start, not live.</p>
<table id="revoked-table">
<thead><tr><th>Device</th><th>Revoked</th><th>Reason</th></tr></thead>
<tbody></tbody>
</table>
<p id="revoked-empty" class="empty" style="display:none">Nothing revoked.</p>
</section>
<section>
<h2>Broker TLS certificate</h2>
<div id="broker-cert-status"></div>
<p>Paste this into the Mosquitto add-on's config (files live in the shared <code>/ssl</code> folder):</p>
<pre id="broker-cert-config"></pre>
<button id="reissue-broker-cert">Reissue broker certificate</button>
</section>
<script src="static/app.js"></script>
</body>
</html>
+10
View File
@@ -0,0 +1,10 @@
# As of Supervisor 2026.04+, HA no longer injects BUILD_FROM automatically,
# so we pin it explicitly here. If your Supervisor is older/newer and this
# fails to build, check https://github.com/home-assistant/docker-base for the
# current recommended base image tag and update the line below.
build_from:
amd64: "ghcr.io/home-assistant/base:latest"
aarch64: "ghcr.io/home-assistant/base:latest"
armv7: "ghcr.io/home-assistant/base:latest"
armhf: "ghcr.io/home-assistant/base:latest"
i386: "ghcr.io/home-assistant/base:latest"
+53
View File
@@ -0,0 +1,53 @@
name: "MQTT Certificate Manager"
version: "0.3.0"
slug: "mqtt_cert_manager"
description: "Local CA that issues and manages TLS client certificates for MQTT nodes"
url: "https://gitea.viratak.com/eta/mqtt-cert-manager"
# Points Supervisor at a pre-built image instead of building locally on
# install. {arch} is substituted with each entry in "arch:" below (amd64,
# aarch64, ...) — Supervisor then pulls
# git.example.com/YOUR_USER/mqtt-cert-manager-amd64:0.1.0, etc.
# REPLACE git.example.com/YOUR_USER with your actual Gitea host + owner.
# Remove this line entirely to fall back to local building (e.g. while
# developing, before you've set up CI).
image: "gitea.viratak.com/eta/mqtt-cert-manager-{arch}"
arch:
- amd64
- aarch64
- armv7
- armhf
- i386
init: false
ingress: true
ingress_port: 8099
panel_icon: mdi:certificate
panel_title: "MQTT Certificates"
# /ssl is Supervisor's shared certificate folder — mapped here so this
# add-on can write the broker's server cert/key + our CA cert where the
# Mosquitto add-on's certfile/keyfile/cafile options can find them.
map:
- ssl:rw
# Persistent add-on storage (CA key/cert, issued cert records) lives in /data,
# which Supervisor maps automatically for every add-on — no extra "map:" entry needed.
options:
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
schema:
mqtt_host: str
mqtt_port: port
mqtt_username: str
mqtt_password: password
request_topic_prefix: str
cert_validity_days: int(30,3650)
broker_hostnames: str
renewal_window_days: int(1,365)
+3
View File
@@ -0,0 +1,3 @@
flask==3.0.3
paho-mqtt==1.6.1
cryptography==42.0.8
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
set -e
exec python3 /app/main.py