264 lines
10 KiB
Python
264 lines
10 KiB
Python
"""
|
|
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 = ec.generate_private_key(ec.SECP256R1())
|
|
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 = ec.generate_private_key(ec.SECP256R1())
|
|
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 only applies to RSA (key-transport)
|
|
# keys; it's meaningless for an ECDSA key and shouldn't
|
|
# be set here now that this is EC. ECDHE cipher suites
|
|
# use ephemeral keys for the actual exchange — this
|
|
# cert's key is only ever used to sign, not encipher.
|
|
key_encipherment=False,
|
|
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 |