Source code for fleetmesh_node.keystore.enclave

"""Enclave-shaped DID keystore: WebAuthn/COSE wire formats over a software key.

What this module does:
1. Generates a P-256 (or secp256k1) key with `cryptography`, holds it in process
   memory and writes it to disk as `priv_hex` under the node directory.
2. Produces WebAuthn-shaped structures - `authenticatorData`, `clientDataJSON`,
   COSE EC2 keys - and a self-signed attestation statement, with no external
   dependency beyond `cryptography`.
3. `EnclaveKeystore`: a drop-in for `Keystore` that tags the events it signs
   `['enclave', hardware_tier, pubkey_multibase, attestation_sig_hex]` and adds
   the key to the DID document's verification methods.

What it does not do, stated plainly so nobody relies on it:
- No Secure Enclave, TPM or FIDO authenticator API is driven. The key never
  leaves software. `detect_hardware_enclave()` only reports the platform
  (`apple-secure-enclave` on Darwin/arm64 means "this host has one", not "the
  key is in it"); on every other host the tier reads `emulated-enclave`.
- The attestation is self-asserted: the statement is signed by the same
  software key it attests, and `user_presence` / `user_verified` are fixed
  `True` with no biometric or presence check behind them. A peer verifying
  it learns only that the ECDSA signature is valid.

Verifiers must treat the `enclave` tag as a key-format hint, not as hardware
provenance. A real hardware backend (and honest tier names) is tracked in
docs/architecture-review-2026-10-06.md R8.
"""
from __future__ import annotations

import base64
import hashlib
import json
import os
import platform
import stat
import struct
import time
from typing import Any, Mapping, Optional, Sequence, Union

from fleetmesh_core.wire.cbor import CBORError, cbor_decode, cbor_encode

# The CBOR codec lived in this module; fleetmesh_node/tests/test_enclave.py and anything
# else that reached it here still can.
_CBOR_REEXPORTS = (CBORError, cbor_decode, cbor_encode)

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, utils

from fleetmesh_core.crypto import crypto, keys
from fleetmesh_core.storage import store as store_mod
from fleetmesh_core.wire.interfaces import NostrEvent

DEFAULT_RP_ID: str = 'meshnode.example.org'
DEFAULT_ORIGIN: str = 'https://meshnode.example.org'

# Multikey multicodec prefix for P-256 public key (0x1200 in varint = 0x80, 0x24)
P256_MULTIKEY_PREFIX: str = 'f8024'
SECP256K1_MULTIKEY_PREFIX: str = keys.PREFIX['node']  # fe70102


# ---------------------------------------------------------------------------
# Hardware Enclave Environment Detection
# ---------------------------------------------------------------------------

[docs]def detect_hardware_enclave() -> Mapping[str, Any]: """Detect available hardware security enclave capabilities on the host.""" system = platform.system() machine = platform.machine() is_apple_silicon = (system == 'Darwin' and machine in ('arm64', 'aarch64')) has_secure_enclave = is_apple_silicon # Check for biometric / Touch ID hardware on macOS has_biometrics = False if is_apple_silicon: # On Apple Silicon Macs, Secure Enclave and Touch ID / Secure Keybox are built-in has_biometrics = True tier = 'apple-secure-enclave' if has_secure_enclave else 'emulated-enclave' return { 'platform': f"{system} {machine}", 'has_secure_enclave': has_secure_enclave, 'has_biometrics': has_biometrics, 'hardware_tier': tier, 'supported_curves': ['p256', 'secp256k1'], 'supported_formats': ['asn1-der', 'raw-p1363', 'webauthn-cose'], }
# --------------------------------------------------------------------------- # Minimal Self-Contained CBOR / COSE Serializer # --------------------------------------------------------------------------- # --------------------------------------------------------------------------- # Enclave Key & Cryptographic Signing # ---------------------------------------------------------------------------
[docs]class EnclaveSignature: """Hardware enclave signature with attestation metadata."""
[docs] def __init__( self, raw_signature: bytes, der_signature: bytes, attestation: Mapping[str, Any], ) -> None: self.raw_signature: bytes = raw_signature # 64-byte r || s self.der_signature: bytes = der_signature # ASN.1 DER format self.attestation: Mapping[str, Any] = attestation
@property def hex(self) -> str: return self.raw_signature.hex()
[docs] def to_dict(self) -> Mapping[str, Any]: return { 'signature_raw': self.raw_signature.hex(), 'signature_der': self.der_signature.hex(), 'attestation': self.attestation, }
[docs]class EnclaveKey: """Hardware Enclave-protected asymmetric keypair."""
[docs] def __init__( self, key_id: str, priv_key: Union[ec.EllipticCurvePrivateKey, str], key_type: str = 'p256', # 'p256' or 'secp256k1' hardware_tier: Optional[str] = None, ) -> None: self.key_id: str = key_id self.key_type: str = key_type detected = detect_hardware_enclave() self.hardware_tier: str = hardware_tier or detected['hardware_tier'] if isinstance(priv_key, str): # Hex seed / private scalar self._sec_hex: str = priv_key.lower() if self.key_type == 'secp256k1': self.priv: Any = ec.derive_private_key(int(self._sec_hex, 16), ec.SECP256K1()) else: self.priv = ec.derive_private_key(int(self._sec_hex, 16), ec.SECP256R1()) else: self.priv = priv_key num = self.priv.private_numbers().private_value self._sec_hex = '%064x' % num self.pub = self.priv.public_key() nums = self.pub.public_numbers() self.x_bytes: bytes = nums.x.to_bytes(32, 'big') self.y_bytes: bytes = nums.y.to_bytes(32, 'big') # Compressed public key (33 bytes) prefix = b'\x02' if nums.y % 2 == 0 else b'\x03' self.compressed_pubkey: bytes = prefix + self.x_bytes self.uncompressed_pubkey: bytes = b'\x04' + self.x_bytes + self.y_bytes # Multikey Multibase 'f' string if self.key_type == 'p256': self.multikey: str = P256_MULTIKEY_PREFIX + self.compressed_pubkey.hex() else: self.multikey = SECP256K1_MULTIKEY_PREFIX + self.x_bytes.hex()
@property def public_key_hex(self) -> str: return self.compressed_pubkey.hex() @property def x_only_hex(self) -> str: return self.x_bytes.hex()
[docs] def cose_key(self) -> dict[int, Any]: """Convert public key into standard COSE_Key structure (RFC 8152).""" return { 1: 2, # kty: EC2 3: -7, # alg: ES256 -1: 1, # crv: P-256 -2: self.x_bytes, -3: self.y_bytes, }
[docs] def sign(self, message: bytes, challenge: Optional[bytes] = None) -> EnclaveSignature: """Sign message inside enclave isolation, returning signature + hardware attestation.""" # Compute signature der = self.priv.sign(message, ec.ECDSA(hashes.SHA256())) r, s = utils.decode_dss_signature(der) raw64 = r.to_bytes(32, 'big') + s.to_bytes(32, 'big') # Generate hardware attestation now = int(time.time()) chal_hex = challenge.hex() if challenge else hashlib.sha256(message).hexdigest() attestation_payload = { 'key_id': self.key_id, 'key_type': self.key_type, 'hardware_tier': self.hardware_tier, 'timestamp': now, 'challenge': chal_hex, 'public_key_multibase': self.multikey, 'user_presence': True, 'user_verified': True, } # Attestation signature over key_id + timestamp + challenge attest_bytes = f"{self.key_id}:{now}:{chal_hex}".encode('utf-8') attest_der = self.priv.sign(attest_bytes, ec.ECDSA(hashes.SHA256())) attestation_payload['attestation_signature'] = attest_der.hex() return EnclaveSignature(raw_signature=raw64, der_signature=der, attestation=attestation_payload)
[docs] def verify(self, message: bytes, signature_bytes: bytes) -> bool: """Verify signature (either 64-byte raw or DER format) against this key.""" der: bytes if len(signature_bytes) == 64: r = int.from_bytes(signature_bytes[:32], 'big') s = int.from_bytes(signature_bytes[32:], 'big') der = utils.encode_dss_signature(r, s) else: der = signature_bytes try: self.pub.verify(der, message, ec.ECDSA(hashes.SHA256())) return True except (InvalidSignature, ValueError): return False
[docs] @classmethod def generate(cls, key_type: str = 'p256', hardware_tier: Optional[str] = None) -> EnclaveKey: kid = os.urandom(16).hex() curve_type = ec.SECP256K1() if key_type == 'secp256k1' else ec.SECP256R1() priv = ec.generate_private_key(curve_type) return cls(key_id=kid, priv_key=priv, key_type=key_type, hardware_tier=hardware_tier)
# --------------------------------------------------------------------------- # W3C WebAuthn Level 3 Passkey Credential Provider # ---------------------------------------------------------------------------
[docs]class WebAuthnCredential: """W3C WebAuthn Level 3 Passkey Credential."""
[docs] def __init__( self, credential_id: bytes, rp_id: str, user_name: str, enclave_key: EnclaveKey, sign_count: int = 0, ) -> None: self.credential_id: bytes = credential_id self.rp_id: str = rp_id self.user_name: str = user_name self.key: EnclaveKey = enclave_key self.sign_count: int = sign_count
@property def credential_id_hex(self) -> str: return self.credential_id.hex() @property def credential_id_b64(self) -> str: return base64.urlsafe_b64encode(self.credential_id).decode('ascii').rstrip('=')
[docs] def make_attestation_object(self) -> bytes: """Produce WebAuthn attestationObject (CBOR map: fmt, authData, attStmt).""" rp_id_hash = hashlib.sha256(self.rp_id.encode('utf-8')).digest() # Flags: UP (0x01) | UV (0x04) | AT (0x40) = 0x45 flags = 0x45 sign_count_bytes = struct.pack('>I', self.sign_count) aaguid = bytes.fromhex('a1b2c3d4e5f60718293a4b5c6d7e8f90') id_len = struct.pack('>H', len(self.credential_id)) cose_bytes = cbor_encode(self.key.cose_key()) auth_data = rp_id_hash + bytes([flags]) + sign_count_bytes + aaguid + id_len + self.credential_id + cose_bytes # Attestation statement (fmt: packed) att_stmt = {'alg': -7, 'sig': self.key.sign(auth_data).der_signature} attestation_obj = { 'fmt': 'packed', 'authData': auth_data, 'attStmt': att_stmt, } return cbor_encode(attestation_obj)
[docs] def create_assertion( self, challenge: bytes, origin: str = DEFAULT_ORIGIN, user_verification: bool = True, ) -> Mapping[str, Any]: """Produce WebAuthn authentication assertion (response to navigator.credentials.get).""" self.sign_count += 1 rp_id_hash = hashlib.sha256(self.rp_id.encode('utf-8')).digest() # Flags: UP (0x01) + (UV (0x04) if user_verification else 0) flags = 0x01 | (0x04 if user_verification else 0) sign_count_bytes = struct.pack('>I', self.sign_count) auth_data = rp_id_hash + bytes([flags]) + sign_count_bytes chal_b64 = base64.urlsafe_b64encode(challenge).decode('ascii').rstrip('=') client_data = { 'type': 'webauthn.get', 'challenge': chal_b64, 'origin': origin, 'crossOrigin': False, } client_data_json = json.dumps(client_data, separators=(',', ':')).encode('utf-8') client_data_hash = hashlib.sha256(client_data_json).digest() # WebAuthn signature is over authData || sha256(clientDataJSON) signed_bytes = auth_data + client_data_hash sig_der = self.key.priv.sign(signed_bytes, ec.ECDSA(hashes.SHA256())) return { 'id': self.credential_id_b64, 'rawId': self.credential_id.hex(), 'response': { 'authenticatorData': auth_data.hex(), 'clientDataJSON': client_data_json.decode('utf-8'), 'signature': sig_der.hex(), }, 'type': 'public-key', }
[docs] def verify_assertion( self, assertion: Mapping[str, Any], expected_challenge: bytes, expected_origin: str = DEFAULT_ORIGIN, ) -> bool: """Verify WebAuthn authentication assertion against credential public key.""" resp = assertion.get('response', {}) auth_data = bytes.fromhex(resp['authenticatorData']) client_data_json = resp['clientDataJSON'].encode('utf-8') sig_der = bytes.fromhex(resp['signature']) # Check clientDataJSON cd = json.loads(client_data_json.decode('utf-8')) if cd.get('type') != 'webauthn.get': return False if cd.get('origin') != expected_origin: return False # Verify challenge expected_chal_b64 = base64.urlsafe_b64encode(expected_challenge).decode('ascii').rstrip('=') if cd.get('challenge') != expected_chal_b64: return False # Verify RP ID Hash expected_rp_hash = hashlib.sha256(self.rp_id.encode('utf-8')).digest() if auth_data[:32] != expected_rp_hash: return False # Verify Flags: UP (Bit 0) must be 1 flags = auth_data[32] if not (flags & 0x01): return False # Verify signature over authData + sha256(clientDataJSON) client_data_hash = hashlib.sha256(client_data_json).digest() signed_bytes = auth_data + client_data_hash try: self.key.pub.verify(sig_der, signed_bytes, ec.ECDSA(hashes.SHA256())) return True except (InvalidSignature, ValueError): return False
[docs] @classmethod def register( cls, rp_id: str = DEFAULT_RP_ID, user_name: str = 'meshnode-operator', hardware_tier: Optional[str] = None, ) -> WebAuthnCredential: cred_id = os.urandom(32) key = EnclaveKey.generate(key_type='p256', hardware_tier=hardware_tier) return cls(credential_id=cred_id, rp_id=rp_id, user_name=user_name, enclave_key=key)
# --------------------------------------------------------------------------- # EnclaveKeystore: Hardware-Attested Node Identity # ---------------------------------------------------------------------------
[docs]class EnclaveKeystore: """Hardware-Enclave augmented Keystore implementing KeyStoreProtocol.""" FILE: str = 'keys.json'
[docs] def __init__( self, node_sk: str, agreement_seed: bytes, transport_seed: bytes, enclave_key: Optional[EnclaveKey] = None, hardware_tier: Optional[str] = None, ) -> None: try: value = int(node_sk, 16) except (TypeError, ValueError): raise ValueError('node_sk is 64 hex characters') if not isinstance(node_sk, str) or len(node_sk) != 64 or not (1 <= value < crypto.N): raise ValueError('node_sk must be a 32-byte scalar in [1, N)') if len(agreement_seed) != 32 or len(transport_seed) != 32: raise ValueError('agreement and transport seeds are 32 bytes') self.node_sk: str = node_sk self.node_pk: str = crypto.pubkey(node_sk) self.did: str = 'did:nostr:' + self.node_pk self.agreement_priv, self.agreement_pub = keys.agreement_keypair(agreement_seed) self.transport_priv, self.transport_pub = keys.transport_keypair(transport_seed) self._seeds: tuple[bytes, bytes] = (agreement_seed, transport_seed) self.enclave_key: EnclaveKey = enclave_key or EnclaveKey.generate(key_type='p256', hardware_tier=hardware_tier) self.hardware_tier: str = self.enclave_key.hardware_tier
[docs] def multikeys(self) -> dict[str, str]: """Multikeys for node descriptor and DID document, including hardware enclave key.""" return { 'node': keys.multikey('node', bytes.fromhex(self.node_pk)), 'agreement': keys.multikey('agreement', keys.raw_public(self.agreement_pub)), 'transport': keys.multikey('transport', keys.raw_public(self.transport_pub)), 'enclave': self.enclave_key.multikey, }
[docs] def kid(self, which: str = 'agreement') -> str: kid_map = { 'agreement': 'agree', 'transport': 'wire', 'node': 'nostr', 'enclave': 'enclave', } name = kid_map.get(which, which) return f"{self.did}#{name}"
[docs] def sign_event_with_attestation( self, created_at: int, kind: int, tags: Sequence[Sequence[str]], content: str, ) -> NostrEvent: """Create signed Nostr event with attached in-band hardware enclave attestation tag.""" # Compute commitment hash over original event structure without the enclave tag commit_bytes = json.dumps([ 0, self.node_pk, created_at, kind, list(tags), content, ], separators=(',', ':'), ensure_ascii=False).encode('utf-8') commit_hash = hashlib.sha256(commit_bytes).digest() # Enclave signs the commitment hash enclave_sig = self.enclave_key.sign(commit_hash) # Enclave tag includes: ['enclave', tier, multikey, sig_hex, commit_hash_hex] enclave_tag = [ 'enclave', self.hardware_tier, self.enclave_key.multikey, enclave_sig.hex, commit_hash.hex(), ] augmented_tags = list(tags) + [enclave_tag] # Sign final event with node_sk return store_mod.make_signed_event(self.node_sk, created_at, kind, augmented_tags, content)
[docs] def attest_event(self, event: NostrEvent | Mapping[str, Any]) -> Mapping[str, Any]: """Produce detached hardware attestation receipt over an already-formed event ID.""" event_id = event['id'] sig = self.enclave_key.sign(bytes.fromhex(event_id)) return { 'event_id': event_id, 'hardware_tier': self.hardware_tier, 'multikey': self.enclave_key.multikey, 'signature': sig.hex, 'attestation': sig.attestation, }
# ---- Persistence ----
[docs] def save(self, directory: str | os.PathLike[str]) -> str: os.makedirs(directory, mode=0o700, exist_ok=True) path = os.path.join(directory, self.FILE) if os.path.exists(path): raise FileExistsError(f"{path} exists; a node does not overwrite its own keys") body = json.dumps({ 'format': 'meshnode-keys/2-enclave', 'node_sk': self.node_sk, 'agreement_seed': self._seeds[0].hex(), 'transport_seed': self._seeds[1].hex(), 'node_pk': self.node_pk, 'did': self.did, 'enclave': { 'key_id': self.enclave_key.key_id, 'key_type': self.enclave_key.key_type, 'hardware_tier': self.enclave_key.hardware_tier, 'priv_hex': self.enclave_key._sec_hex, 'multikey': self.enclave_key.multikey, }, }, indent=2) fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, 'w', encoding='utf-8') as f: f.write(body + '\n') return path
[docs] @classmethod def load(cls, directory: str | os.PathLike[str]) -> EnclaveKeystore: path = os.path.join(directory, cls.FILE) mode = stat.S_IMODE(os.stat(path).st_mode) if mode & 0o077: raise PermissionError(f"{path} is readable by others (mode {oct(mode)}); refusing to load") with open(path, encoding='utf-8') as _fh: d = json.load(_fh) fmt = d.get('format') enclave_key = None if fmt == 'meshnode-keys/2-enclave' and 'enclave' in d: enc_d = d['enclave'] enclave_key = EnclaveKey( key_id=enc_d['key_id'], priv_key=enc_d['priv_hex'], key_type=enc_d.get('key_type', 'p256'), hardware_tier=enc_d.get('hardware_tier'), ) return cls( node_sk=d['node_sk'], agreement_seed=bytes.fromhex(d['agreement_seed']), transport_seed=bytes.fromhex(d['transport_seed']), enclave_key=enclave_key, )
[docs] @classmethod def generate(cls, hardware_tier: Optional[str] = None, key_type: str = 'p256') -> EnclaveKeystore: sk = os.urandom(32).hex() while not (1 <= int(sk, 16) < crypto.N): sk = os.urandom(32).hex() enclave_key = EnclaveKey.generate(key_type=key_type, hardware_tier=hardware_tier) return cls(sk, keys.fresh_seed(), keys.fresh_seed(), enclave_key=enclave_key)
[docs] @classmethod def load_or_generate(cls, directory: str | os.PathLike[str]) -> EnclaveKeystore: if os.path.exists(os.path.join(directory, cls.FILE)): return cls.load(directory) ks = cls.generate() ks.save(directory) return ks
# --------------------------------------------------------------------------- # Enclave Attestation Verification # ---------------------------------------------------------------------------
[docs]def verify_enclave_attestation(event: NostrEvent | Mapping[str, Any]) -> tuple[bool, str]: """Verify the hardware enclave attestation tag of a Nostr event.""" tags = event.get('tags', []) enclave_tags = [t for t in tags if t and t[0] == 'enclave'] if not enclave_tags: return False, "no enclave tag present" t = enclave_tags[0] if len(t) < 4: return False, "malformed enclave tag: expected ['enclave', tier, multikey, signature]" tier = t[1] pubkey_mb = t[2] sig_hex = t[3] try: sig_bytes = bytes.fromhex(sig_hex) except Exception: return False, "invalid signature hex encoding" # Extract public key from multikey if pubkey_mb.startswith(P256_MULTIKEY_PREFIX): raw_pub = bytes.fromhex(pubkey_mb[len(P256_MULTIKEY_PREFIX):]) try: pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), raw_pub) except Exception as e: return False, f"invalid P-256 public key in multibase: {e}" elif pubkey_mb.startswith(SECP256K1_MULTIKEY_PREFIX): raw_pub = bytes.fromhex(pubkey_mb[len(SECP256K1_MULTIKEY_PREFIX):]) try: # 32-byte x-only, prepend 0x02 even-y full_compressed = b'\x02' + raw_pub pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), full_compressed) except Exception as e: return False, f"invalid secp256k1 public key in multibase: {e}" else: return False, f"unsupported enclave multikey prefix: {pubkey_mb[:6]}" commit_hex = t[4] if len(t) > 4 else None if commit_hex: # Recompute commitment hash over tags excluding 'enclave' orig_tags = [tag for tag in tags if tag and tag[0] != 'enclave'] recomputed_bytes = json.dumps([ 0, event['pubkey'], event['created_at'], event['kind'], orig_tags, event['content'], ], separators=(',', ':'), ensure_ascii=False).encode('utf-8') msg = hashlib.sha256(recomputed_bytes).digest() if msg.hex() != commit_hex: return False, "enclave commitment hash mismatch" else: # Fall back to verifying over event ID event_id = event.get('id', '') if not event_id: return False, "event missing id" msg = bytes.fromhex(event_id) # Convert raw 64-byte signature to DER if len(sig_bytes) == 64: r = int.from_bytes(sig_bytes[:32], 'big') s = int.from_bytes(sig_bytes[32:], 'big') der_sig = utils.encode_dss_signature(r, s) else: der_sig = sig_bytes try: pub.verify(der_sig, msg, ec.ECDSA(hashes.SHA256())) return True, f"hardware attestation verified ({tier})" except (InvalidSignature, ValueError) as e: return False, f"attestation signature invalid: {e}"
[docs]def verify_signature( message: bytes, multikey_str: str, signature_bytes: bytes, ) -> tuple[bool, str]: """Verify an arbitrary message signature against an enclave multikey.""" if multikey_str.startswith(P256_MULTIKEY_PREFIX): raw_pub = bytes.fromhex(multikey_str[len(P256_MULTIKEY_PREFIX):]) try: pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), raw_pub) except Exception as e: return False, f"invalid P-256 public key in multibase: {e}" elif multikey_str.startswith(SECP256K1_MULTIKEY_PREFIX): raw_pub = bytes.fromhex(multikey_str[len(SECP256K1_MULTIKEY_PREFIX):]) try: full_compressed = b'\x02' + raw_pub pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), full_compressed) except Exception as e: return False, f"invalid secp256k1 public key in multibase: {e}" else: return False, f"unsupported enclave multikey prefix: {multikey_str[:6]}" if len(signature_bytes) == 64: r = int.from_bytes(signature_bytes[:32], 'big') s = int.from_bytes(signature_bytes[32:], 'big') der_sig = utils.encode_dss_signature(r, s) else: der_sig = signature_bytes try: pub.verify(der_sig, message, ec.ECDSA(hashes.SHA256())) return True, "signature verified" except (InvalidSignature, ValueError) as e: return False, f"signature invalid: {e}"
[docs]def verify_detached_attestation( event_id: str, multikey_str: str, signature_hex: str, hardware_tier: str = 'hardware-enclave', ) -> tuple[bool, str]: """Verify a detached hardware attestation receipt over an event ID.""" try: sig_bytes = bytes.fromhex(signature_hex) msg_bytes = bytes.fromhex(event_id) except Exception: return False, "invalid hex in event_id or signature" ok_v, reason = verify_signature(msg_bytes, multikey_str, sig_bytes) if ok_v: return True, f"detached hardware attestation verified ({hardware_tier})" return False, f"detached attestation invalid: {reason}"