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
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:
@@ -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
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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);
|
||||
@@ -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; }
|
||||
@@ -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>
|
||||
Reference in New Issue
Block a user