use std::collections::HashMap;
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Debug)]
pub struct HsmStubError {
pub message: String,
pub error_code: u32,
pub timestamp: u64,
pub security_level: SecurityLevel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SecurityLevel {
#[default]
Info,
Warning,
Error,
Critical,
}
impl HsmStubError {
pub fn feature_disabled() -> Self {
Self {
message: "This feature is disabled in the current configuration".to_string(),
error_code: 1001,
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::from_secs(0))
.as_secs(),
security_level: SecurityLevel::Warning,
}
}
pub fn with_security_level(msg: &str, level: SecurityLevel) -> Self {
Self {
message: msg.to_string(),
error_code: match level {
SecurityLevel::Info => 1000,
SecurityLevel::Warning => 2000,
SecurityLevel::Error => 3000,
SecurityLevel::Critical => 4000,
},
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::from_secs(0))
.as_secs(),
security_level: level,
}
}
pub fn is_critical(&self) -> bool {
self.security_level == SecurityLevel::Critical
}
}
impl fmt::Display for HsmStubError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "HSM functionality not available: {}", self.message)
}
}
impl std::error::Error for HsmStubError {}
pub fn hsm_stub_error(msg: &str) -> HsmStubError {
HsmStubError {
message: format!("HSM support disabled: {msg}"),
error_code: 1001,
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or(Duration::from_secs(0))
.as_secs(),
security_level: SecurityLevel::Warning,
}
}
pub fn hsm_critical_error(msg: &str) -> HsmStubError {
HsmStubError::with_security_level(msg, SecurityLevel::Critical)
}
#[derive(Debug)]
pub struct HsmManager {
initialization_attempted: AtomicBool,
config: HashMap<String, String>,
}
impl HsmManager {
pub fn new(config: HashMap<String, String>) -> Result<Self, HsmStubError> {
if let Some(security_mode) = config.get("security_mode") {
if security_mode == "enforce" {
return Err(hsm_critical_error(
"Security mode 'enforce' requires full HSM implementation",
));
}
}
Ok(Self {
initialization_attempted: AtomicBool::new(false),
config,
})
}
pub async fn initialize(&self) -> Result<(), HsmStubError> {
self.initialization_attempted.store(true, Ordering::SeqCst);
Err(hsm_stub_error("HSM functionality is disabled"))
}
pub async fn get_status(&self) -> Result<HsmStatus, HsmStubError> {
if !self.initialization_attempted.load(Ordering::SeqCst) {
return Err(hsm_stub_error(
"HSM not initialized. Call initialize() first",
));
}
Err(hsm_stub_error("HSM functionality is disabled"))
}
pub fn validate_config(&self) -> Result<bool, HsmStubError> {
if let Some(provider) = self.config.get("provider") {
match provider.as_str() {
"software" | "hardware" | "simulator" | "pkcs11" | "tpm" | "ledger" => Ok(true),
_ => Err(hsm_stub_error("Invalid HSM provider specified")),
}
} else {
Err(hsm_stub_error(
"Missing required 'provider' config parameter",
))
}
}
}
#[derive(Debug, Clone)]
pub struct HsmStatus {
pub provider_name: String,
pub available: bool,
pub security_level: SecurityLevel,
pub last_checked: u64,
pub secure_boot_verified: bool,
}
#[derive(Debug, Clone)]
pub enum KeyType {
Rsa,
Ec,
Aes,
Hmac,
}
#[derive(Debug, Clone)]
pub enum SigningAlgorithm {
RsaSha256,
EcdsaP256,
}
pub trait HsmProvider: Send + Sync {
fn is_available(&self) -> bool {
false
}
fn provider_name(&self) -> &str;
fn security_level(&self) -> SecurityLevel {
SecurityLevel::Info
}
}
#[derive(Debug, Clone, Default)]
pub struct BitcoinHsmProvider;
impl BitcoinHsmProvider {
pub fn new() -> Self {
BitcoinHsmProvider
}
pub fn validate_security(&self) -> Result<(), HsmStubError> {
Ok(())
}
}
impl HsmProvider for BitcoinHsmProvider {
fn provider_name(&self) -> &str {
"bitcoin_hsm"
}
fn security_level(&self) -> SecurityLevel {
SecurityLevel::Critical }
}
#[derive(Debug, Clone, Default)]
pub struct SoftwareHsmProvider;
impl SoftwareHsmProvider {
pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
Err(hsm_stub_error(
"SoftwareHsmProvider is disabled in this build",
))
}
}
impl HsmProvider for SoftwareHsmProvider {
fn provider_name(&self) -> &str {
"software_hsm"
}
fn security_level(&self) -> SecurityLevel {
SecurityLevel::Warning }
}
#[derive(Debug, Clone, Default)]
pub struct SimulatorHsmProvider;
impl SimulatorHsmProvider {
pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
Err(hsm_stub_error(
"SimulatorHsmProvider is disabled in this build",
))
}
}
#[derive(Debug, Clone, Default)]
pub struct HardwareHsmProvider;
impl HardwareHsmProvider {
pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
Err(hsm_stub_error(
"HardwareHsmProvider is disabled in this build",
))
}
}
#[derive(Debug, Clone, Default)]
pub struct Pkcs11HsmProvider;
impl Pkcs11HsmProvider {
pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
Err(hsm_stub_error(
"Pkcs11HsmProvider is disabled in this build",
))
}
}
#[derive(Debug, Clone, Default)]
pub struct TpmHsmProvider;
impl TpmHsmProvider {
pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
Err(hsm_stub_error("TpmHsmProvider is disabled in this build"))
}
}
#[derive(Debug, Clone, Default)]
pub struct LedgerHsmProvider;
impl LedgerHsmProvider {
pub fn new(_config: &impl std::fmt::Debug) -> Result<Self, HsmStubError> {
Err(hsm_stub_error(
"LedgerHsmProvider is disabled in this build",
))
}
}
#[derive(Debug, Clone, Default)]
pub struct HsmConfig {
pub provider_type: String,
pub security_level: SecurityLevel,
pub parameters: HashMap<String, String>,
pub enforce_secure_boot: bool,
}
impl HsmConfig {
pub fn new(provider: &str) -> Self {
HsmConfig {
provider_type: provider.to_string(),
..Default::default()
}
}
pub fn with_param(mut self, key: &str, value: &str) -> Self {
self.parameters.insert(key.to_string(), value.to_string());
self
}
pub fn with_security_level(mut self, level: SecurityLevel) -> Self {
self.security_level = level;
self
}
pub fn enforce_secure_boot(mut self) -> Self {
self.enforce_secure_boot = true;
self
}
}