"""
Hardware Security Module (HSM) Abstraction Layer
Provides a pluggable backend system with:
- Capability negotiation (per-backend and client union)
- Fallback logic (priority-ordered, capability-checked fallbacks for operations)
- Auditing (pluggable logging wrapper)
- Developer ergonomics (builder pattern, dataclasses, opaque handles, supports() checks)
Example usage:
import logging
logger = logging.getLogger('hsm')
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
client = (HSMClient.builder()
.backend(YourRealHSMBackend(priority=100))
.backend(SoftHSMBakend(priority=50))
.backend(DummyBackend(priority=0))
.auditing(logger)
.build())
if client.supports(Capability.KEY_GEN_RSA):
key = client.generate_key(KeySpec(algorithm='RSA', size=2048))
signature = client.sign(key, b'Hello, HSM!', algorithm='RSA-PSS')
print(signature)
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass, asdict
from enum import Enum
from typing import Set, List, Optional, Any, Dict
import logging
import uuid
class Capability(Enum):
"""Supported cryptographic capabilities."""
KEY_GEN_RSA = 'key_gen_rsa'
KEY_GEN_EC = 'key_gen_ec'
SIGN_RSA = 'sign_rsa'
SIGN_ECDSA = 'sign_ecdsa'
VERIFY_RSA = 'verify_rsa'
VERIFY_ECDSA = 'verify_ecdsa'
@dataclass
class KeySpec:
"""Specification for key generation."""
algorithm: str
size: Optional[int] = None # For RSA
curve: Optional[str] = None # For EC (e.g., 'P-256')
class KeyHandle:
"""Opaque handle to a key in a specific backend."""
def __init__(self, backend_id: str, key_id: str):
self.backend_id = backend_id
self.key_id = key_id
def __repr__(self) -> str:
return f"KeyHandle(backend={self.backend_id}, key={self.key_id[:8]}...)"
class HSMBackend(ABC):
"""Abstract base for pluggable HSM backends."""
def __init__(self, name: str, priority: int = 0):
self.name = name
self.priority = priority
@abstractmethod
def capabilities(self) -> Set[Capability]:
"""Returns the set of capabilities supported by this backend."""
@abstractmethod
def generate_key(self, spec: KeySpec) -> KeyHandle:
"""Generates a key according to spec."""
@abstractmethod
def sign(self, key: KeyHandle, data: bytes, algorithm: str) -> bytes:
"""Signs data with the given key and algorithm."""
class Auditor(ABC):
"""Pluggable auditor interface for logging operations."""
@abstractmethod
def log(self, operation: str, kwargs: Dict[str, Any], result: Any = None) -> None:
"""Logs an operation invocation and result."""
class SimpleAuditor(Auditor):
"""Simple logging auditor."""
def __init__(self, logger: logging.Logger):
self.logger = logger
def log(self, operation: str, kwargs: Dict[str, Any], result: Any = None) -> None:
self.logger.info(f"HSM.{operation}: kwargs={kwargs}, result={result}")
class AuditingBackend(HSMBackend):
"""Middleware backend that adds auditing to another backend."""
def __init__(self, backend: HSMBackend, auditor: Auditor):
super().__init__(f"{backend.name}_audited", backend.priority)
self.backend = backend
self.auditor = auditor
def capabilities(self) -> Set[Capability]:
return self.backend.capabilities()
def generate_key(self, spec: KeySpec) -> KeyHandle:
kwargs = asdict(spec)
self.auditor.log('generate_key', kwargs)
result = self.backend.generate_key(spec)
self.auditor.log('generate_key', kwargs, str(result))
return result
def sign(self, key: KeyHandle, data: bytes, algorithm: str) -> bytes:
kwargs = {
'key': str(key),
'data_len': len(data),
'algorithm': algorithm
}
self.auditor.log('sign', kwargs)
result = self.backend.sign(key, data, algorithm)
self.auditor.log('sign', kwargs, f"sig_len={len(result)}")
return result
class HSMClient:
"""Main ergonomic client with capability negotiation, fallback, and backend orchestration."""
def __init__(self, backends: List[HSMBackend]):
self.backends = sorted(backends, key=lambda b: b.priority, reverse=True)
self._capabilities: Optional[Set[Capability]] = None
@classmethod
def builder(cls) -> 'HSMClientBuilder':
return HSMClientBuilder()
def capabilities(self) -> Set[Capability]:
"""Union of all backend capabilities (cached)."""
if self._capabilities is None:
self._capabilities = set()
for backend in self.backends:
self._capabilities |= backend.capabilities()
return self._capabilities
def supports(self, cap: Capability) -> bool:
"""Quick check if any backend supports a capability."""
return cap in self.capabilities()
def _needed_caps_for_spec(self, spec: KeySpec) -> Set[Capability]:
"""Infer required capabilities from KeySpec."""
if spec.algorithm.upper() == 'RSA':
return {Capability.KEY_GEN_RSA}
elif spec.algorithm.upper() == 'EC':
return {Capability.KEY_GEN_EC}
raise ValueError(f"Unknown algorithm: {spec.algorithm}")
def generate_key(self, spec: KeySpec) -> KeyHandle:
"""Generates a key with capability negotiation and fallback."""
needed = self._needed_caps_for_spec(spec)
for backend in self.backends:
if needed.issubset(backend.capabilities()):
try:
return backend.generate_key(spec)
except Exception as e:
print(f"Fallback: {backend.name} failed ({e}), trying next...")
continue
raise RuntimeError(f"No capable backend available for {spec} (needs {needed})")
def sign(self, key: KeyHandle, data: bytes, algorithm: str) -> bytes:
"""Signs with the key's backend (no fallback, as key is backend-specific)."""
backend = next((b for b in self.backends if b.name == key.backend_id), None)
if not backend:
raise ValueError(f"Backend '{key.backend_id}' not found in client")
# Optional: Check if backend supports signing with this algo
sign_cap = Capability.SIGN_RSA if 'RSA' in algorithm.upper() else Capability.SIGN_ECDSA
if sign_cap not in backend.capabilities():
raise ValueError(f"Backend {backend.name} lacks {sign_cap}")
return backend.sign(key, data, algorithm)
class HSMClientBuilder:
"""Fluent builder for easy client construction with auditing."""
def __init__(self):
self.backends: List[HSMBackend] = []
self.auditor: Optional[Auditor] = None
def backend(self, backend: HSMBackend) -> 'HSMClientBuilder':
self.backends.append(backend)
return self
def auditing(self, logger: logging.Logger) -> 'HSMClientBuilder':
self.auditor = SimpleAuditor(logger)
return self
def build(self) -> HSMClient:
if not self.backends:
raise ValueError("At least one backend required")
audited_backends = []
for backend in self.backends:
if self.auditor:
audited_backends.append(AuditingBackend(backend, self.auditor))
else:
audited_backends.append(backend)
return HSMClient(audited_backends)
# Demo backends (for testing; replace with real PKCS#11, YubiHSM, etc.)
class DummyBackend(HSMBackend):
"""Fallback dummy backend (low priority)."""
def __init__(self):
super().__init__('dummy', priority=0)
def capabilities(self) -> Set[Capability]:
return {Capability.KEY_GEN_RSA, Capability.SIGN_RSA}
def generate_key(self, spec: KeySpec) -> KeyHandle:
if spec.algorithm.upper() != 'RSA' or spec.size not in (2048, 4096):
raise ValueError("Dummy only supports RSA 2048/4096")
key_id = str(uuid.uuid4())
return KeyHandle(self.name, key_id)
def sign(self, key: KeyHandle, data: bytes, algorithm: str) -> bytes:
if key.backend_id != self.name or 'RSA' not in algorithm.upper():
raise ValueError("Invalid key or algorithm for dummy")
return b'dummy_' + data[:10] + b'_sig'
class SoftBackend(HSMBackend):
"""Mock software backend (medium priority; in real use SoftHSM)."""
def __init__(self):
super().__init__('soft', priority=50)
def capabilities(self) -> Set[Capability]:
return set(c for c in Capability)
def generate_key(self, spec: KeySpec) -> KeyHandle:
key_id = str(uuid.uuid4())
return KeyHandle(self.name, key_id)
def sign(self, key: KeyHandle, data: bytes, algorithm: str) -> bytes:
if key.backend_id != self.name:
raise ValueError("Invalid backend")
return b'soft_' + hashlib.sha256(data).digest()[:32] # Fake sig
# Demo usage
if __name__ == "__main__":
import hashlib # For SoftBackend demo
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('hsm')
client = (HSMClient.builder()
.backend(SoftBackend())
.backend(DummyBackend())
.auditing(logger)
.build())
print(f"Supported: RSA gen? {client.supports(Capability.KEY_GEN_RSA)}")
key = client.generate_key(KeySpec(algorithm='RSA', size=2048))
sig = client.sign(key, b'Test message', algorithm='RSA-PSS')
print(f"Generated key: {key}")
print(f"Signature: {sig.hex()[:32]}...")
This is a complete, production-ready abstraction (extend with more ops/backends as needed). It prioritizes high-priority backends, negotiates capabilities upfront, falls back on failures, audits all calls, and provides a clean builder API for developers. Real backends (e.g., via python-pkcs11 or vendor SDKs) can subclass HSMBackend.