""" Server-issued challenges for certificate renewal. Why this exists: a node with no trustworthy clock can't produce a timestamp the server can check, so freshness has to come from the server instead. For each renewal the server hands the node a random, single-use, short-lived nonce, and the node signs that nonce together with a digest of its new CSR. A captured renewal message is useless afterwards: the nonce is gone, and swapping in a different CSR breaks the signature. State is in memory only. If the add-on restarts, outstanding challenges are simply lost and the node asks for a new one. """ import hashlib import hmac import secrets import threading import time from cryptography import x509 from cryptography.hazmat.primitives import serialization CHALLENGE_TTL_SECONDS = 120 # Prefix on everything a node signs for renewal. It keeps a renewal # signature from being valid in any other protocol that reuses the key. RENEWAL_CONTEXT = "renew-v1" def csr_digest(csr_pem: str) -> str: """SHA-256 (hex) of the CSR's DER encoding. Raises ValueError if the CSR doesn't parse. The DER form is hashed, not the PEM text, so line endings or whitespace that differ between the node and the server don't change the result.""" csr = x509.load_pem_x509_csr(csr_pem.encode()) return hashlib.sha256(csr.public_bytes(serialization.Encoding.DER)).hexdigest() def renewal_message(device_id: str, nonce: str, digest: str) -> bytes: """The exact bytes a node signs to prove a renewal request.""" return f"{RENEWAL_CONTEXT}|{device_id}|{nonce}|{digest}".encode() class ChallengeStore: """One active challenge per device. Thread-safe.""" def __init__(self, ttl: int = CHALLENGE_TTL_SECONDS, clock=time.monotonic): self._ttl = ttl self._clock = clock self._lock = threading.Lock() self._active = {} # device_id -> (nonce, expires_at) def _prune(self, now): for device_id in [d for d, (_, exp) in self._active.items() if now >= exp]: del self._active[device_id] def issue(self, device_id: str): """Return (nonce, seconds_left) for this device. If the device already has an unexpired challenge, that same one is returned instead of minting another. A node that missed the first message can simply ask again, and nobody else can invalidate a device's challenge by asking for a new one.""" with self._lock: now = self._clock() self._prune(now) current = self._active.get(device_id) if current: return current[0], max(1, int(current[1] - now)) nonce = secrets.token_hex(32) self._active[device_id] = (nonce, now + self._ttl) return nonce, self._ttl def is_active(self, device_id: str, nonce) -> bool: """Cheap non-consuming check, used to skip signature work for nonces that can't possibly be valid. consume() is the real gate.""" with self._lock: current = self._active.get(device_id) if not current or not isinstance(nonce, str): return False stored, expires_at = current if self._clock() >= expires_at: return False return hmac.compare_digest(stored.encode(), nonce.encode()) def consume(self, device_id: str, nonce) -> bool: """Atomically check and burn the nonce. True only for the first caller presenting this device's current, unexpired nonce.""" with self._lock: current = self._active.get(device_id) if not current: return False stored, expires_at = current if self._clock() >= expires_at: del self._active[device_id] return False if not isinstance(nonce, str) or not hmac.compare_digest(stored.encode(), nonce.encode()): return False del self._active[device_id] return True