Decouple certificate CN from device_id
- ca.sign_csr's identity parameter renamed to `common_name`, fully decoupled from device_id. - New resolve_common_name(): CN comes from the device's own CSR: falls back to device_id only if the CSR has no CN (malformed request). - Renewal unaffected: a renewed cert always keeps the CN of the device's current, still-valid cert, regardless of what the renewal CSR claims (verified against an adversarial CSR asserting a different CN). - device_id remains the sole storage key (pending/issued/revoked) and MQTT topic routing key, and must still be unique per physical device even when CN is deliberately shared across many. - /api/pending and /api/issued now also expose the CSR-resolved CN for display, without changing what's actually stored. No topic structure changes. No new MQTT payload fields.
This commit is contained in:
@@ -8,7 +8,7 @@ import time
|
||||
from flask import Flask, jsonify, render_template, request
|
||||
|
||||
import store
|
||||
from ca import CertificateAuthority
|
||||
from ca import CertificateAuthority, extract_cert_common_name, extract_csr_common_name
|
||||
from mqtt_worker import MqttWorker
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s")
|
||||
@@ -31,7 +31,7 @@ def load_options():
|
||||
"mqtt_password": "",
|
||||
"request_topic_prefix": "cert/enroll",
|
||||
"cert_validity_days": 825,
|
||||
"broker_hostnames": "homeassistant.local,192.168.1.80",
|
||||
"broker_hostnames": "homeassistant.local,192.168.1.80, core-mosquitto,localhost",
|
||||
"renewal_window_days": 30,
|
||||
"cert_organization": "",
|
||||
"cert_organizational_unit": "",
|
||||
@@ -65,7 +65,7 @@ def restrict_to_ingress_proxy():
|
||||
|
||||
|
||||
def parsed_broker_hostnames():
|
||||
raw = options.get("broker_hostnames", "homeassistant.local,192.168.1.80")
|
||||
raw = options.get("broker_hostnames", "core-mosquitto,localhost")
|
||||
return [h.strip() for h in raw.split(",") if h.strip()]
|
||||
|
||||
|
||||
@@ -143,16 +143,31 @@ def write_crl():
|
||||
log.info("wrote CRL with %d revoked cert(s) to %s", len(entries), crl_path)
|
||||
|
||||
|
||||
def resolve_common_name(device_id: str, csr_pem: str) -> str:
|
||||
"""CN comes from the CSR itself -- devices set it there deliberately,
|
||||
often shared across a whole device category (e.g. all TH sensors use
|
||||
one CN, all light sensors another) for ACL grouping purposes. This
|
||||
is intentionally NOT unique per device, unlike device_id.
|
||||
|
||||
Falls back to device_id only if the CSR has no CN at all (malformed
|
||||
or lazy firmware) -- a safety net, not the intended path."""
|
||||
from_csr = extract_csr_common_name(csr_pem)
|
||||
return from_csr or device_id
|
||||
|
||||
|
||||
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):
|
||||
def finalize_issuance(device_id: str, csr_pem: str, common_name: 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."""
|
||||
and the auto-renewal fast path so both stay in sync. `common_name`
|
||||
is resolved by the caller -- see resolve_common_name for fresh
|
||||
issuance, and handle_renew's own logic for renewals (which must NOT
|
||||
use CSR-based resolution -- it always keeps the existing CN)."""
|
||||
from cryptography import x509
|
||||
|
||||
cert_pem = ca.sign_csr(csr_pem, device_id, int(options["cert_validity_days"]))
|
||||
cert_pem = ca.sign_csr(csr_pem, common_name, 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)
|
||||
@@ -167,7 +182,15 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta):
|
||||
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."""
|
||||
gets a cert eventually, just with human review.
|
||||
|
||||
CN handling for renewal is intentionally NOT the same as fresh
|
||||
issuance: the renewed cert always keeps whatever CN the device's
|
||||
CURRENT on-record cert already has. A renewal CSR's own CN (or any
|
||||
other claimed identity) is never consulted -- renewal is about
|
||||
extending validity / rotating keys, not about redefining who a
|
||||
device is. Changing identity requires a fresh, humanly-approved
|
||||
enrollment, not a renewal."""
|
||||
|
||||
def fall_back_to_manual(why):
|
||||
log.info("renewal from %s falling back to manual approval: %s", device_id, why)
|
||||
@@ -177,8 +200,8 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta):
|
||||
fall_back_to_manual("device is revoked")
|
||||
return
|
||||
|
||||
issued = store.list_issued().get(device_id)
|
||||
if not issued:
|
||||
existing_issued = store.list_issued().get(device_id)
|
||||
if not existing_issued:
|
||||
fall_back_to_manual("no prior issued cert on record")
|
||||
return
|
||||
|
||||
@@ -192,12 +215,10 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta):
|
||||
fall_back_to_manual("timestamp outside allowed skew window")
|
||||
return
|
||||
|
||||
not_after = datetime.datetime.fromisoformat(issued["not_after"])
|
||||
not_after = datetime.datetime.fromisoformat(existing_issued["not_after"])
|
||||
renewal_opens_at = not_after - datetime.timedelta(days=int(options["renewal_window_days"]))
|
||||
if datetime.datetime.now(datetime.timezone.utc) < renewal_opens_at:
|
||||
fall_back_to_manual(
|
||||
f"too early to renew (opens {renewal_opens_at.isoformat()})"
|
||||
)
|
||||
fall_back_to_manual(f"too early to renew (opens {renewal_opens_at.isoformat()})")
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -207,17 +228,24 @@ def handle_renew(device_id, csr_pem, timestamp, signature_b64, meta):
|
||||
return
|
||||
|
||||
message = f"{device_id}|{int(ts)}|renew".encode()
|
||||
if not ca.verify_renewal_proof(issued["cert"], message, signature):
|
||||
if not ca.verify_renewal_proof(existing_issued["cert"], message, signature):
|
||||
fall_back_to_manual("proof-of-possession signature did not verify")
|
||||
return
|
||||
|
||||
# Past every check: keep the EXISTING cert's CN, full stop. Never
|
||||
# derived from the new CSR for a renewal.
|
||||
preserved_common_name = extract_cert_common_name(existing_issued["cert"]) or device_id
|
||||
|
||||
try:
|
||||
_, new_not_after = finalize_issuance(device_id, csr_pem)
|
||||
_, new_not_after = finalize_issuance(device_id, csr_pem, preserved_common_name)
|
||||
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)
|
||||
log.info(
|
||||
"auto-renewed cert for %s (proof verified), CN kept as %r, now valid until %s",
|
||||
device_id, preserved_common_name, new_not_after,
|
||||
)
|
||||
|
||||
|
||||
mqtt_worker = MqttWorker(
|
||||
@@ -242,12 +270,25 @@ def index():
|
||||
|
||||
@app.route("/api/pending")
|
||||
def api_pending():
|
||||
return jsonify(store.list_pending())
|
||||
pending = store.list_pending()
|
||||
enriched = {}
|
||||
for device_id, entry in pending.items():
|
||||
enriched[device_id] = dict(entry)
|
||||
# What CN WOULD be used if approved right now (from the CSR) --
|
||||
# purely for display, not stored, since it's cheap to recompute
|
||||
# and this way it's never stale.
|
||||
enriched[device_id]["resolved_common_name"] = resolve_common_name(device_id, entry["csr"])
|
||||
return jsonify(enriched)
|
||||
|
||||
|
||||
@app.route("/api/issued")
|
||||
def api_issued():
|
||||
return jsonify(store.list_issued())
|
||||
issued = store.list_issued()
|
||||
enriched = {}
|
||||
for device_id, entry in issued.items():
|
||||
enriched[device_id] = dict(entry)
|
||||
enriched[device_id]["common_name"] = extract_cert_common_name(entry["cert"])
|
||||
return jsonify(enriched)
|
||||
|
||||
|
||||
@app.route("/api/approve/<device_id>", methods=["POST"])
|
||||
@@ -256,12 +297,17 @@ def api_approve(device_id):
|
||||
if not pending:
|
||||
return jsonify({"error": "no pending request for that device"}), 404
|
||||
|
||||
common_name = resolve_common_name(device_id, pending["csr"])
|
||||
|
||||
try:
|
||||
_, not_after = finalize_issuance(device_id, pending["csr"], state=state)
|
||||
_, not_after = finalize_issuance(device_id, pending["csr"], common_name, state=state)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
return jsonify({"status": "issued", "device_id": device_id, "not_after": not_after})
|
||||
return jsonify({
|
||||
"status": "issued", "device_id": device_id,
|
||||
"common_name": common_name, "not_after": not_after,
|
||||
})
|
||||
|
||||
|
||||
@app.route("/api/reject/<device_id>", methods=["POST"])
|
||||
|
||||
Reference in New Issue
Block a user