| 1 |
use crate::algorithms::{AeadAlgorithm, HpkeAlgorithm, KdfAlgorithm, KemAlgorithm}; |
| 2 |
use crate::crypto; |
| 3 |
use crate::crypto::{secret_box, PublicKey}; |
| 4 |
use crate::protected_mem::Vault; |
| 5 |
use std::collections::HashMap; |
| 6 |
use std::sync::{Arc, RwLock}; |
| 7 |
use std::time::{Duration, Instant}; |
| 8 |
use uuid::Uuid; |
| 9 |
|
| 10 |
#[cfg(not(test))] |
| 11 |
const REAPER_INTERVAL_SECS: u64 = 60; |
| 12 |
#[cfg(test)] |
| 13 |
const REAPER_INTERVAL_SECS: u64 = 1; |
| 14 |
|
| 15 |
/// Represents the purpose of the Key and its associated algorithms. |
| 16 |
#[derive(Clone)] |
| 17 |
pub enum KeySpec { |
| 18 |
/// Represents the composite key used by the Key Protection Service for the decaps-and-encrypt flow. |
| 19 |
KemWithBindingPub { |
| 20 |
/// The KEM and binding public keys share the same algorithm suite. |
| 21 |
algo: HpkeAlgorithm, |
| 22 |
/// The KEM public key |
| 23 |
kem_public_key: PublicKey, |
| 24 |
/// Binding public key for HPKE encrypt after decaps |
| 25 |
binding_public_key: PublicKey, |
| 26 |
}, |
| 27 |
Binding { |
| 28 |
algo: HpkeAlgorithm, |
| 29 |
/// The Binding key-pair |
| 30 |
binding_public_key: PublicKey, |
| 31 |
}, |
| 32 |
} |
| 33 |
|
| 34 |
/// Internal Rust struct to hold the Key Metadata |
| 35 |
#[derive(Clone)] |
| 36 |
pub struct KeyMetadata { |
| 37 |
/// UUID key handle for internal tracking |
| 38 |
pub id: Uuid, |
| 39 |
pub created_at: Instant, |
| 40 |
/// TTL-bound deletion time |
| 41 |
pub delete_after: Instant, |
| 42 |
/// (non-secret) Cryptographic material |
| 43 |
pub spec: KeySpec, |
| 44 |
} |
| 45 |
|
| 46 |
/// Internal struct to hold the Key Metadata and the secret key material. |
| 47 |
pub struct KeyRecord { |
| 48 |
pub meta: KeyMetadata, |
| 49 |
/// memfd_secrets backed secret key-material |
| 50 |
private_key: Vault, |
| 51 |
} |
| 52 |
|
| 53 |
pub type KeyHandle = Uuid; |
| 54 |
|
| 55 |
/// Thread-safe registry for storing encryption keys. |
| 56 |
#[derive(Default, Clone)] |
| 57 |
pub struct KeyRegistry { |
| 58 |
keys: Arc<RwLock<HashMap<KeyHandle, Arc<KeyRecord>>>>, |
| 59 |
} |
| 60 |
|
| 61 |
impl KeyRegistry { |
| 62 |
pub fn add_key(&self, record: KeyRecord) { |
| 63 |
let mut keys = self.keys.write().unwrap(); |
| 64 |
keys.insert(record.meta.id, Arc::new(record)); |
| 65 |
} |
| 66 |
|
| 67 |
pub fn remove_key(&self, id: &KeyHandle) -> Option<Arc<KeyRecord>> { |
| 68 |
let mut keys = self.keys.write().unwrap(); |
| 69 |
keys.remove(id) |
| 70 |
} |
| 71 |
|
| 72 |
pub fn get_key(&self, id: &KeyHandle) -> Option<Arc<KeyRecord>> { |
| 73 |
let keys = self.keys.read().unwrap(); |
| 74 |
keys.get(id).and_then(|record| { |
| 75 |
if record.meta.delete_after > Instant::now() { |
| 76 |
Some(Arc::clone(record)) |
| 77 |
} else { |
| 78 |
None |
| 79 |
} |
| 80 |
}) |
| 81 |
} |
| 82 |
|
| 83 |
/// Spawns a background reaper thread to walk through the KeyRegistry every 60s and sanitize expired keys. |
| 84 |
pub fn start_reaper( |
| 85 |
&self, |
| 86 |
stop_signal: Arc<std::sync::atomic::AtomicBool>, |
| 87 |
) -> std::thread::JoinHandle<()> { |
| 88 |
let keys_clone = Arc::clone(&self.keys); |
| 89 |
std::thread::spawn(move || loop { |
| 90 |
std::thread::sleep(Duration::from_secs(REAPER_INTERVAL_SECS)); |
| 91 |
if stop_signal.load(std::sync::atomic::Ordering::Relaxed) { |
| 92 |
break; |
| 93 |
} |
| 94 |
let now = Instant::now(); |
| 95 |
if let Ok(mut keys) = keys_clone.write() { |
| 96 |
keys.retain(|_, key| key.meta.delete_after > now); |
| 97 |
} |
| 98 |
}) |
| 99 |
} |
| 100 |
|
| 101 |
/// Lists all Keys with pagination support. |
| 102 |
pub fn list_all_keys(&self, offset: usize, limit: usize) -> (Vec<KeyMetadata>, usize) { |
| 103 |
let keys = self.keys.read().unwrap(); |
| 104 |
let now = Instant::now(); |
| 105 |
let mut refs: Vec<&Arc<KeyRecord>> = keys |
| 106 |
.values() |
| 107 |
.filter(|record| record.meta.delete_after > now) |
| 108 |
.collect(); |
| 109 |
let total_count = refs.len(); |
| 110 |
|
| 111 |
// Sort for stable pagination: created_at, then id |
| 112 |
refs.sort_by(|a, b| { |
| 113 |
a.meta |
| 114 |
.created_at |
| 115 |
.cmp(&b.meta.created_at) |
| 116 |
.then(a.meta.id.cmp(&b.meta.id)) |
| 117 |
}); |
| 118 |
|
| 119 |
let page = refs |
| 120 |
.into_iter() |
| 121 |
.skip(offset) |
| 122 |
.take(limit) |
| 123 |
.map(|r| r.meta.clone()) |
| 124 |
.collect(); |
| 125 |
|
| 126 |
(page, total_count) |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
impl KeyRecord { |
| 131 |
/// Returns the private key material. |
| 132 |
pub fn get_private_key(&self) -> crypto::PrivateKey { |
| 133 |
crypto::PrivateKey::from(self.private_key.get_secret()) |
| 134 |
} |
| 135 |
|
| 136 |
/// Creates a new long-term Binding key. |
| 137 |
pub fn create_binding_key( |
| 138 |
algo: HpkeAlgorithm, |
| 139 |
expiry: Duration, |
| 140 |
) -> Result<Self, crypto::Error> { |
| 141 |
Self::create_key_internal(algo, expiry, |algo, pub_key| KeySpec::Binding { |
| 142 |
algo, |
| 143 |
binding_public_key: pub_key, |
| 144 |
}) |
| 145 |
} |
| 146 |
|
| 147 |
/// Creates a new ephemeral KEM key bound to an existing Binding key. |
| 148 |
pub fn create_bound_kem_key( |
| 149 |
algo: HpkeAlgorithm, |
| 150 |
binding_public_key: PublicKey, |
| 151 |
expiry: Duration, |
| 152 |
) -> Result<Self, crypto::Error> { |
| 153 |
// Validate that the binding key is compatible with the algorithm suite. |
| 154 |
// Currently only X25519 is supported. |
| 155 |
match (&binding_public_key, KemAlgorithm::try_from(algo.kem)) { |
| 156 |
(PublicKey::X25519(_), Ok(KemAlgorithm::DhkemX25519HkdfSha256)) => (), |
| 157 |
_ => return Err(crypto::Error::InvalidKey), |
| 158 |
} |
| 159 |
|
| 160 |
Self::create_key_internal(algo, expiry, move |algo, pub_key| { |
| 161 |
KeySpec::KemWithBindingPub { |
| 162 |
algo, |
| 163 |
kem_public_key: pub_key, |
| 164 |
binding_public_key, |
| 165 |
} |
| 166 |
}) |
| 167 |
} |
| 168 |
|
| 169 |
fn create_key_internal<F>( |
| 170 |
algo: HpkeAlgorithm, |
| 171 |
expiry: Duration, |
| 172 |
spec_builder: F, |
| 173 |
) -> Result<Self, crypto::Error> |
| 174 |
where |
| 175 |
F: FnOnce(HpkeAlgorithm, PublicKey) -> KeySpec, |
| 176 |
{ |
| 177 |
let ( |
| 178 |
Ok(KemAlgorithm::DhkemX25519HkdfSha256), |
| 179 |
Ok(KdfAlgorithm::HkdfSha256), |
| 180 |
Ok(AeadAlgorithm::Aes256Gcm), |
| 181 |
) = ( |
| 182 |
KemAlgorithm::try_from(algo.kem), |
| 183 |
KdfAlgorithm::try_from(algo.kdf), |
| 184 |
AeadAlgorithm::try_from(algo.aead), |
| 185 |
) |
| 186 |
else { |
| 187 |
return Err(crypto::Error::UnsupportedAlgorithm); |
| 188 |
}; |
| 189 |
|
| 190 |
let (pub_key, priv_key) = crypto::generate_keypair(KemAlgorithm::DhkemX25519HkdfSha256)?; |
| 191 |
|
| 192 |
let id = Uuid::new_v4(); |
| 193 |
let vault = Vault::new(secret_box::SecretBox::from(priv_key)) |
| 194 |
.map_err(|_| crypto::Error::CryptoError)?; |
| 195 |
|
| 196 |
let now = Instant::now(); |
| 197 |
let delete_after = now |
| 198 |
.checked_add(expiry) |
| 199 |
.ok_or(crypto::Error::UnsupportedAlgorithm)?; |
| 200 |
|
| 201 |
let record = KeyRecord { |
| 202 |
meta: KeyMetadata { |
| 203 |
id, |
| 204 |
created_at: now, |
| 205 |
delete_after, |
| 206 |
spec: spec_builder(algo, pub_key), |
| 207 |
}, |
| 208 |
private_key: vault, |
| 209 |
}; |
| 210 |
|
| 211 |
Ok(record) |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
#[cfg(test)] |
| 216 |
mod tests { |
| 217 |
use super::*; |
| 218 |
use crate::algorithms::{AeadAlgorithm, KdfAlgorithm, KemAlgorithm}; |
| 219 |
|
| 220 |
#[test] |
| 221 |
fn test_create_binding_key_success() { |
| 222 |
let algo = HpkeAlgorithm { |
| 223 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 224 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 225 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 226 |
}; |
| 227 |
let expiry = Duration::from_secs(3600); |
| 228 |
|
| 229 |
let result = KeyRecord::create_binding_key(algo.clone(), expiry); |
| 230 |
|
| 231 |
assert!(result.is_ok()); |
| 232 |
let record = result.unwrap(); |
| 233 |
|
| 234 |
// Check metadata |
| 235 |
assert!(!record.meta.id.is_nil()); |
| 236 |
assert!(record.meta.delete_after > record.meta.created_at); |
| 237 |
|
| 238 |
// Check spec |
| 239 |
if let KeySpec::Binding { |
| 240 |
algo: a, |
| 241 |
binding_public_key: pk, |
| 242 |
} = record.meta.spec |
| 243 |
{ |
| 244 |
assert_eq!(a.kem, algo.kem); |
| 245 |
assert_eq!(pk.as_bytes().len(), 32); |
| 246 |
} else { |
| 247 |
panic!("Unexpected KeySpec variant"); |
| 248 |
} |
| 249 |
} |
| 250 |
|
| 251 |
#[test] |
| 252 |
fn test_create_bound_kem_success() { |
| 253 |
let algo = HpkeAlgorithm { |
| 254 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 255 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 256 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 257 |
}; |
| 258 |
let binding_pubkey = PublicKey::try_from([42u8; 32].to_vec()).unwrap(); |
| 259 |
let expiry = Duration::from_secs(3600); |
| 260 |
|
| 261 |
let result = KeyRecord::create_bound_kem_key(algo.clone(), binding_pubkey.clone(), expiry); |
| 262 |
|
| 263 |
assert!(result.is_ok()); |
| 264 |
let record = result.unwrap(); |
| 265 |
|
| 266 |
if let KeySpec::KemWithBindingPub { |
| 267 |
algo: a, |
| 268 |
kem_public_key: kpk, |
| 269 |
binding_public_key: bpk, |
| 270 |
} = record.meta.spec |
| 271 |
{ |
| 272 |
assert_eq!(a.kem, algo.kem); |
| 273 |
assert_eq!(kpk.as_bytes().len(), 32); |
| 274 |
assert_eq!(bpk, binding_pubkey); |
| 275 |
} else { |
| 276 |
panic!("Unexpected KeySpec variant"); |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
#[test] |
| 281 |
fn test_add_key() { |
| 282 |
let registry = KeyRegistry::default(); |
| 283 |
let algo = HpkeAlgorithm { |
| 284 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 285 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 286 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 287 |
}; |
| 288 |
|
| 289 |
let record = KeyRecord::create_binding_key(algo, Duration::from_secs(3600)) |
| 290 |
.expect("failed to create key"); |
| 291 |
|
| 292 |
let id = record.meta.id; |
| 293 |
registry.add_key(record); |
| 294 |
|
| 295 |
// Access private field for testing |
| 296 |
let keys = registry.keys.read().unwrap(); |
| 297 |
assert!(keys.contains_key(&id)); |
| 298 |
assert_eq!(keys.get(&id).unwrap().meta.id, id); |
| 299 |
} |
| 300 |
|
| 301 |
#[test] |
| 302 |
fn test_remove_key() { |
| 303 |
use memmap2::MmapMut; |
| 304 |
use std::os::unix::io::{AsRawFd, FromRawFd}; |
| 305 |
|
| 306 |
let registry = KeyRegistry::default(); |
| 307 |
let algo = HpkeAlgorithm { |
| 308 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 309 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 310 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 311 |
}; |
| 312 |
|
| 313 |
let record = KeyRecord::create_binding_key(algo, Duration::from_secs(3600)) |
| 314 |
.expect("failed to create key"); |
| 315 |
|
| 316 |
let id = record.meta.id; |
| 317 |
registry.add_key(record); |
| 318 |
|
| 319 |
let removed = registry.remove_key(&id).expect("Key should be present"); |
| 320 |
|
| 321 |
// Prepare spy mapping to check for zeroization after drop |
| 322 |
let fd = removed.private_key.as_raw_fd(); |
| 323 |
let len = removed.private_key.get_secret().as_slice().len(); |
| 324 |
|
| 325 |
let spy = unsafe { |
| 326 |
let fd_dup = libc::dup(fd); |
| 327 |
let file = std::fs::File::from_raw_fd(fd_dup); |
| 328 |
MmapMut::map_mut(&file).expect("Failed to map spy") |
| 329 |
}; |
| 330 |
|
| 331 |
// Verify spy sees the data before drop |
| 332 |
assert_eq!(&spy[..len], removed.private_key.get_secret().as_slice()); |
| 333 |
assert!(!spy[..len].iter().all(|&b| b == 0)); |
| 334 |
|
| 335 |
drop(removed); |
| 336 |
|
| 337 |
// Verify zeroization |
| 338 |
assert!( |
| 339 |
spy[..len].iter().all(|&b| b == 0), |
| 340 |
"Key material was not zeroized on drop" |
| 341 |
); |
| 342 |
|
| 343 |
assert!(registry.remove_key(&id).is_none()); |
| 344 |
} |
| 345 |
|
| 346 |
#[test] |
| 347 |
fn test_get_key_liveness() { |
| 348 |
let registry = KeyRegistry::default(); |
| 349 |
let algo = HpkeAlgorithm { |
| 350 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 351 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 352 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 353 |
}; |
| 354 |
|
| 355 |
// Key that expires in 0 seconds (already expired) |
| 356 |
let record = KeyRecord::create_binding_key(algo, Duration::from_secs(0)) |
| 357 |
.expect("failed to create key"); |
| 358 |
|
| 359 |
let id = record.meta.id; |
| 360 |
registry.add_key(record); |
| 361 |
|
| 362 |
// Should be None because it's expired |
| 363 |
assert!(registry.get_key(&id).is_none()); |
| 364 |
|
| 365 |
// Key that is still alive |
| 366 |
let record2 = KeyRecord::create_binding_key(algo, Duration::from_secs(3600)) |
| 367 |
.expect("failed to create key"); |
| 368 |
|
| 369 |
let id2 = record2.meta.id; |
| 370 |
registry.add_key(record2); |
| 371 |
assert!(registry.get_key(&id2).is_some()); |
| 372 |
} |
| 373 |
|
| 374 |
#[test] |
| 375 |
fn test_reaper_functionality() { |
| 376 |
let registry = KeyRegistry::default(); |
| 377 |
let algo = HpkeAlgorithm { |
| 378 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 379 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 380 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 381 |
}; |
| 382 |
|
| 383 |
// Create keys that expire in 2 seconds (reaper test interval is 1s in test) |
| 384 |
let binding_pubkey = PublicKey::try_from([42u8; 32].to_vec()).unwrap(); |
| 385 |
let expiry = Duration::from_secs(4); |
| 386 |
let kem_record = |
| 387 |
KeyRecord::create_bound_kem_key(algo.clone(), binding_pubkey.clone(), expiry) |
| 388 |
.expect("failed to create key"); |
| 389 |
let binding_record = KeyRecord::create_binding_key(algo.clone(), expiry) |
| 390 |
.expect("failed to create binding key"); |
| 391 |
|
| 392 |
let kem_id = kem_record.meta.id; |
| 393 |
let binding_id = binding_record.meta.id; |
| 394 |
registry.add_key(kem_record); |
| 395 |
registry.add_key(binding_record); |
| 396 |
|
| 397 |
// Start reaper |
| 398 |
let stop_signal = Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 399 |
let handle = registry.start_reaper(stop_signal.clone()); |
| 400 |
|
| 401 |
// Wait for < expiry (1s) - keys should still be there |
| 402 |
std::thread::sleep(Duration::from_secs(1)); |
| 403 |
assert!(registry.get_key(&kem_id).is_some()); |
| 404 |
assert!(registry.get_key(&binding_id).is_some()); |
| 405 |
|
| 406 |
// Wait for > expiry (6s total) - keys should be gone (reaper runs every 1s) |
| 407 |
std::thread::sleep(Duration::from_secs(6)); |
| 408 |
|
| 409 |
// Check raw storage directly to verify reaper removed it, |
| 410 |
// as get_key() also filters by expiry. |
| 411 |
{ |
| 412 |
let keys = registry.keys.read().unwrap(); |
| 413 |
assert!( |
| 414 |
!keys.contains_key(&kem_id), |
| 415 |
"KEM key should have been removed by reaper" |
| 416 |
); |
| 417 |
assert!( |
| 418 |
!keys.contains_key(&binding_id), |
| 419 |
"Binding key should have been removed by reaper" |
| 420 |
); |
| 421 |
} |
| 422 |
|
| 423 |
// Clean up |
| 424 |
stop_signal.store(true, std::sync::atomic::Ordering::Relaxed); |
| 425 |
handle.join().unwrap(); |
| 426 |
} |
| 427 |
|
| 428 |
#[test] |
| 429 |
fn test_list_all_keys_filters_expired() { |
| 430 |
let registry = KeyRegistry::default(); |
| 431 |
let algo = HpkeAlgorithm { |
| 432 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 433 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 434 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 435 |
}; |
| 436 |
|
| 437 |
// Key that expires in 0 seconds (already expired) |
| 438 |
let record1 = KeyRecord::create_binding_key(algo.clone(), Duration::from_secs(0)) |
| 439 |
.expect("failed to create key"); |
| 440 |
|
| 441 |
// Key that expires in 3600 seconds (not expired) |
| 442 |
let record2 = KeyRecord::create_binding_key(algo.clone(), Duration::from_secs(3600)) |
| 443 |
.expect("failed to create key"); |
| 444 |
|
| 445 |
let id2 = record2.meta.id; |
| 446 |
registry.add_key(record1); |
| 447 |
registry.add_key(record2); |
| 448 |
|
| 449 |
let (keys, total_count) = registry.list_all_keys(0, 10); |
| 450 |
assert_eq!(total_count, 1); |
| 451 |
assert_eq!(keys.len(), 1); |
| 452 |
assert_eq!(keys[0].id, id2); |
| 453 |
} |
| 454 |
} |