| 1 |
use km_common::algorithms::HpkeAlgorithm; |
| 2 |
use km_common::crypto::PublicKey; |
| 3 |
use km_common::key_types::{KeyRecord, KeyRegistry, KeySpec}; |
| 4 |
use prost::Message; |
| 5 |
use std::slice; |
| 6 |
use std::sync::Arc; |
| 7 |
use std::sync::LazyLock; |
| 8 |
use std::sync::atomic::AtomicBool; |
| 9 |
use std::time::{Duration, Instant}; |
| 10 |
use uuid::Uuid; |
| 11 |
|
| 12 |
static KEY_REGISTRY: LazyLock<KeyRegistry> = LazyLock::new(|| { |
| 13 |
let registry = KeyRegistry::default(); |
| 14 |
registry.start_reaper(Arc::new(AtomicBool::new(false))); |
| 15 |
registry |
| 16 |
}); |
| 17 |
|
| 18 |
/// Internal function to generate a KEM keypair and store it in the registry. |
| 19 |
fn generate_kem_keypair_internal( |
| 20 |
algo: HpkeAlgorithm, |
| 21 |
binding_pubkey: PublicKey, |
| 22 |
expiry_secs: u64, |
| 23 |
) -> Result<(uuid::Uuid, PublicKey), i32> { |
| 24 |
let result = |
| 25 |
KeyRecord::create_bound_kem_key(algo, binding_pubkey, Duration::from_secs(expiry_secs)); |
| 26 |
|
| 27 |
match result { |
| 28 |
Ok(record) => { |
| 29 |
let id = record.meta.id; |
| 30 |
let pubkey = match &record.meta.spec { |
| 31 |
KeySpec::KemWithBindingPub { kem_public_key, .. } => kem_public_key.clone(), |
| 32 |
_ => return Err(-1), |
| 33 |
}; |
| 34 |
KEY_REGISTRY.add_key(record); |
| 35 |
Ok((id, pubkey)) |
| 36 |
} |
| 37 |
Err(_) => Err(-1), |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
/// Generates a new KEM keypair associated with a binding public key. |
| 42 |
/// |
| 43 |
/// ## Arguments |
| 44 |
/// * `algo_ptr` - A pointer to the serialized HPKE algorithm proto bytes. |
| 45 |
/// * `algo_len` - The length of the serialized HPKE algorithm proto bytes. |
| 46 |
/// * `binding_pubkey` - A pointer to the binding public key bytes. |
| 47 |
/// * `binding_pubkey_len` - The length of the binding public key. |
| 48 |
/// * `expiry_secs` - The expiration time of the key in seconds from now. |
| 49 |
/// * `out_uuid` - A pointer to a 16-byte buffer where the key UUID will be written. |
| 50 |
/// * `out_pubkey` - A pointer to a buffer where the public key will be written. |
| 51 |
/// * `out_pubkey_len` - The size of `out_pubkey` buffer. |
| 52 |
/// |
| 53 |
/// ## Safety |
| 54 |
/// This function is unsafe because it dereferences the provided raw pointers. |
| 55 |
/// The caller must ensure that: |
| 56 |
/// * `algo_ptr` points to a valid buffer of at least `algo_len` bytes. |
| 57 |
/// * `binding_pubkey` points to a valid buffer of at least `binding_pubkey_len` bytes. |
| 58 |
/// * `out_uuid` is either null or points to a valid 16-byte buffer. |
| 59 |
/// * `out_pubkey` is either null or points to a valid buffer of at least `*out_pubkey_len` bytes. |
| 60 |
/// * `out_pubkey_len` is either null or points to a valid `usize`. |
| 61 |
/// |
| 62 |
/// ## Returns |
| 63 |
/// * `0` on success. |
| 64 |
/// * `-1` if an error occurred during key generation or if `binding_pubkey` is null/empty. |
| 65 |
/// * `-2` if the `out_pubkey` buffer size does not match the key size. |
| 66 |
|
| 67 |
#[unsafe(no_mangle)] |
| 68 |
pub unsafe extern "C" fn key_manager_generate_kem_keypair( |
| 69 |
algo_ptr: *const u8, |
| 70 |
algo_len: usize, |
| 71 |
binding_pubkey: *const u8, |
| 72 |
binding_pubkey_len: usize, |
| 73 |
expiry_secs: u64, |
| 74 |
out_uuid: *mut u8, |
| 75 |
out_pubkey: *mut u8, |
| 76 |
out_pubkey_len: usize, |
| 77 |
) -> i32 { |
| 78 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 79 |
// Safety Invariant Checks |
| 80 |
if binding_pubkey.is_null() |
| 81 |
|| binding_pubkey_len == 0 |
| 82 |
|| out_pubkey.is_null() |
| 83 |
|| out_uuid.is_null() |
| 84 |
|| algo_ptr.is_null() |
| 85 |
|| algo_len == 0 |
| 86 |
{ |
| 87 |
return -1; |
| 88 |
} |
| 89 |
|
| 90 |
// Convert to Safe Types |
| 91 |
let binding_pubkey_slice = |
| 92 |
unsafe { slice::from_raw_parts(binding_pubkey, binding_pubkey_len) }; |
| 93 |
let algo_slice = unsafe { slice::from_raw_parts(algo_ptr, algo_len) }; |
| 94 |
let out_uuid = unsafe { slice::from_raw_parts_mut(out_uuid, 16) }; |
| 95 |
let out_pubkey = unsafe { slice::from_raw_parts_mut(out_pubkey, out_pubkey_len) }; |
| 96 |
|
| 97 |
let binding_pubkey = match PublicKey::try_from(binding_pubkey_slice.to_vec()) { |
| 98 |
Ok(pk) => pk, |
| 99 |
Err(_) => return -1, |
| 100 |
}; |
| 101 |
|
| 102 |
let algo = match HpkeAlgorithm::decode(algo_slice) { |
| 103 |
Ok(a) => a, |
| 104 |
Err(_) => return -1, |
| 105 |
}; |
| 106 |
|
| 107 |
// Call Safe Internal Function |
| 108 |
match generate_kem_keypair_internal(algo, binding_pubkey, expiry_secs) { |
| 109 |
Ok((id, pubkey)) => { |
| 110 |
if out_pubkey_len != pubkey.as_bytes().len() { |
| 111 |
return -2; |
| 112 |
} |
| 113 |
out_uuid.copy_from_slice(id.as_bytes()); |
| 114 |
out_pubkey.copy_from_slice(pubkey.as_bytes()); |
| 115 |
0 // Success |
| 116 |
} |
| 117 |
Err(e) => e, |
| 118 |
} |
| 119 |
})) |
| 120 |
.unwrap_or(-1) |
| 121 |
} |
| 122 |
|
| 123 |
/// Destroys the KEM key associated with the given UUID. |
| 124 |
/// |
| 125 |
/// ## Arguments |
| 126 |
/// * `uuid_bytes` - A pointer to a 16-byte buffer containing the key UUID. |
| 127 |
/// |
| 128 |
/// ## Safety |
| 129 |
/// This function is unsafe because it dereferences the provided raw pointer. |
| 130 |
/// The caller must ensure that `uuid_bytes` points to a valid 16-byte buffer. |
| 131 |
/// |
| 132 |
/// ## Returns |
| 133 |
/// * `0` on success. |
| 134 |
/// * `-1` if the UUID pointer is null or the key was not found. |
| 135 |
#[unsafe(no_mangle)] |
| 136 |
pub unsafe extern "C" fn key_manager_destroy_kem_key(uuid_bytes: *const u8) -> i32 { |
| 137 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 138 |
if uuid_bytes.is_null() { |
| 139 |
return -1; |
| 140 |
} |
| 141 |
let uuid = unsafe { |
| 142 |
let mut bytes = [0u8; 16]; |
| 143 |
std::ptr::copy_nonoverlapping(uuid_bytes, bytes.as_mut_ptr(), 16); |
| 144 |
Uuid::from_bytes(bytes) |
| 145 |
}; |
| 146 |
|
| 147 |
match KEY_REGISTRY.remove_key(&uuid) { |
| 148 |
Some(_) => 0, // Success |
| 149 |
None => -1, // Not found |
| 150 |
} |
| 151 |
})) |
| 152 |
.unwrap_or(-1) |
| 153 |
} |
| 154 |
|
| 155 |
/// Internal function to decapsulate and reseal a shared secret. |
| 156 |
fn decap_and_seal_internal( |
| 157 |
uuid: Uuid, |
| 158 |
encapsulated_key: &[u8], |
| 159 |
aad: &[u8], |
| 160 |
out_encapsulated_key: &mut [u8], |
| 161 |
out_ciphertext: &mut [u8], |
| 162 |
) -> Result<(), i32> { |
| 163 |
// Get key record from registry |
| 164 |
let Some(key_record) = KEY_REGISTRY.get_key(&uuid) else { |
| 165 |
Err(-1)? // Key not found |
| 166 |
}; |
| 167 |
|
| 168 |
let KeySpec::KemWithBindingPub { |
| 169 |
algo: hpke_algo, |
| 170 |
binding_public_key, |
| 171 |
.. |
| 172 |
} = &key_record.meta.spec |
| 173 |
else { |
| 174 |
Err(-1)? // Invalid key type |
| 175 |
}; |
| 176 |
|
| 177 |
let priv_key = key_record.get_private_key(); |
| 178 |
|
| 179 |
// Decapsulate |
| 180 |
let shared_secret = match km_common::crypto::decaps(&priv_key, encapsulated_key) { |
| 181 |
Ok(s) => s, |
| 182 |
Err(_) => return Err(-3), |
| 183 |
}; |
| 184 |
|
| 185 |
// Seal |
| 186 |
match km_common::crypto::hpke_seal(binding_public_key, &shared_secret, aad, hpke_algo) { |
| 187 |
Ok((enc, ct)) => { |
| 188 |
if out_encapsulated_key.len() != enc.len() || out_ciphertext.len() != ct.len() { |
| 189 |
return Err(-2); |
| 190 |
} |
| 191 |
out_encapsulated_key.copy_from_slice(&enc); |
| 192 |
out_ciphertext.copy_from_slice(&ct); |
| 193 |
Ok(()) |
| 194 |
} |
| 195 |
Err(_) => Err(-4), |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
pub const MAX_ALGORITHM_LEN: usize = 128; |
| 200 |
pub const MAX_PUBLIC_KEY_LEN: usize = 2048; |
| 201 |
|
| 202 |
#[repr(C)] |
| 203 |
pub struct KpsKeyInfo { |
| 204 |
pub uuid: [u8; 16], |
| 205 |
pub algorithm: [u8; MAX_ALGORITHM_LEN], |
| 206 |
pub algorithm_len: usize, |
| 207 |
pub pub_key: [u8; MAX_PUBLIC_KEY_LEN], |
| 208 |
pub pub_key_len: usize, |
| 209 |
pub binding_pub_key: [u8; MAX_PUBLIC_KEY_LEN], |
| 210 |
pub binding_pub_key_len: usize, |
| 211 |
pub remaining_lifespan_secs: u64, |
| 212 |
} |
| 213 |
|
| 214 |
impl Default for KpsKeyInfo { |
| 215 |
fn default() -> Self { |
| 216 |
KpsKeyInfo { |
| 217 |
uuid: [0; 16], |
| 218 |
algorithm: [0; MAX_ALGORITHM_LEN], |
| 219 |
algorithm_len: 0, |
| 220 |
pub_key: [0; MAX_PUBLIC_KEY_LEN], |
| 221 |
pub_key_len: 0, |
| 222 |
binding_pub_key: [0; MAX_PUBLIC_KEY_LEN], |
| 223 |
binding_pub_key_len: 0, |
| 224 |
remaining_lifespan_secs: 0, |
| 225 |
} |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
fn enumerate_kem_keys_internal( |
| 230 |
entries: &mut [KpsKeyInfo], |
| 231 |
offset: usize, |
| 232 |
) -> Result<(usize, bool), i32> { |
| 233 |
let (metas, total_count) = KEY_REGISTRY.list_all_keys(offset, entries.len()); |
| 234 |
let count = metas.len(); |
| 235 |
let has_more = offset + count < total_count; |
| 236 |
|
| 237 |
for (entry, meta) in entries.iter_mut().zip(metas.into_iter()) { |
| 238 |
let KeySpec::KemWithBindingPub { |
| 239 |
algo, |
| 240 |
kem_public_key: pub_key, |
| 241 |
binding_public_key: binding_pub_key, |
| 242 |
.. |
| 243 |
} = &meta.spec |
| 244 |
else { |
| 245 |
return Err(-1); // Implementation error, KPS should only contain KEM keys. |
| 246 |
}; |
| 247 |
|
| 248 |
let algo_bytes = algo.encode_to_vec(); |
| 249 |
|
| 250 |
if pub_key.as_bytes().len() > MAX_PUBLIC_KEY_LEN || algo_bytes.len() > MAX_ALGORITHM_LEN { |
| 251 |
debug_assert!( |
| 252 |
false, |
| 253 |
"Implementation error: Key size exceeds buffer limits! (algo={}, pub={})", |
| 254 |
algo_bytes.len(), |
| 255 |
pub_key.as_bytes().len() |
| 256 |
); |
| 257 |
return Err(-2); // Buffer Limit Exceeded |
| 258 |
} |
| 259 |
if binding_pub_key.as_bytes().len() > MAX_PUBLIC_KEY_LEN { |
| 260 |
debug_assert!( |
| 261 |
false, |
| 262 |
"Implementation error: Binding Key size exceeds buffer limits! (bpk={})", |
| 263 |
binding_pub_key.as_bytes().len() |
| 264 |
); |
| 265 |
return Err(-2); |
| 266 |
} |
| 267 |
|
| 268 |
let now = Instant::now(); |
| 269 |
let remaining = meta.delete_after.saturating_duration_since(now).as_secs(); |
| 270 |
|
| 271 |
*entry = KpsKeyInfo::default(); |
| 272 |
|
| 273 |
entry.uuid.copy_from_slice(meta.id.as_bytes()); |
| 274 |
|
| 275 |
entry.algorithm[..algo_bytes.len()].copy_from_slice(&algo_bytes); |
| 276 |
entry.algorithm_len = algo_bytes.len(); |
| 277 |
|
| 278 |
entry.pub_key[..pub_key.as_bytes().len()].copy_from_slice(pub_key.as_bytes()); |
| 279 |
entry.pub_key_len = pub_key.as_bytes().len(); |
| 280 |
|
| 281 |
entry.binding_pub_key[..binding_pub_key.as_bytes().len()] |
| 282 |
.copy_from_slice(binding_pub_key.as_bytes()); |
| 283 |
entry.binding_pub_key_len = binding_pub_key.as_bytes().len(); |
| 284 |
|
| 285 |
entry.remaining_lifespan_secs = remaining; |
| 286 |
} |
| 287 |
|
| 288 |
Ok((count, has_more)) |
| 289 |
} |
| 290 |
|
| 291 |
#[unsafe(no_mangle)] |
| 292 |
pub unsafe extern "C" fn key_manager_enumerate_kem_keys( |
| 293 |
out_entries: *mut KpsKeyInfo, |
| 294 |
max_entries: usize, |
| 295 |
offset: usize, |
| 296 |
out_has_more: Option<&mut bool>, |
| 297 |
) -> i32 { |
| 298 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 299 |
if out_entries.is_null() { |
| 300 |
return -1; |
| 301 |
} |
| 302 |
|
| 303 |
let entries = unsafe { slice::from_raw_parts_mut(out_entries, max_entries) }; |
| 304 |
|
| 305 |
match enumerate_kem_keys_internal(entries, offset) { |
| 306 |
Ok((count, has_more)) => { |
| 307 |
if let Some(has_more_ref) = out_has_more { |
| 308 |
*has_more_ref = has_more; |
| 309 |
} |
| 310 |
count as i32 |
| 311 |
} |
| 312 |
Err(e) => e, |
| 313 |
} |
| 314 |
})) |
| 315 |
.unwrap_or(-1) |
| 316 |
} |
| 317 |
|
| 318 |
/// Decapsulates a shared secret using a stored KEM key and immediately reseals it using the associated binding public key. |
| 319 |
/// |
| 320 |
/// ## Arguments |
| 321 |
/// * `uuid_bytes` - A pointer to the 16-byte UUID of the KEM key. |
| 322 |
/// * `encapsulated_key` - A pointer to the encapsulated key bytes (ciphertext from client). |
| 323 |
/// * `encapsulated_key_len` - The length of the encapsulated key. |
| 324 |
/// * `aad` - A pointer to the Additional Authenticated Data (AAD) for the sealing operation. |
| 325 |
/// * `aad_len` - The length of the AAD. |
| 326 |
/// * `out_encapsulated_key` - A pointer to a buffer where the new encapsulated key will be written. |
| 327 |
/// * `out_encapsulated_key_len` - The size of `out_encapsulated_key`. |
| 328 |
/// * `out_ciphertext` - A pointer to a buffer where the sealed ciphertext will be written. |
| 329 |
/// * `out_ciphertext_len` -The size of `out_ciphertext`. |
| 330 |
/// |
| 331 |
/// ## Safety |
| 332 |
/// This function is unsafe because it dereferences raw pointers. The caller must ensure that: |
| 333 |
/// * `uuid_bytes` points to a valid 16-byte buffer. |
| 334 |
/// * `encapsulated_key` points to a valid buffer of `encapsulated_key_len` bytes. |
| 335 |
/// * `aad` is either null or points to a valid buffer of `aad_len` bytes. |
| 336 |
/// * `out_encapsulated_key` points to a valid buffer of `out_encapsulated_key_len` bytes. |
| 337 |
/// * `out_ciphertext` points to a valid buffer of `out_ciphertext_len` bytes. |
| 338 |
/// |
| 339 |
/// ## Returns |
| 340 |
/// * `0` on success. |
| 341 |
/// * `-1` if arguments are invalid or key is not found. |
| 342 |
/// * `-2` if output buffers are too small. |
| 343 |
/// * `-3` if decapsulation fails. |
| 344 |
/// * `-4` if sealing (HPKE encryption) fails. |
| 345 |
#[unsafe(no_mangle)] |
| 346 |
pub unsafe extern "C" fn key_manager_decap_and_seal( |
| 347 |
uuid_bytes: *const u8, |
| 348 |
encapsulated_key: *const u8, |
| 349 |
encapsulated_key_len: usize, |
| 350 |
aad: *const u8, |
| 351 |
aad_len: usize, |
| 352 |
out_encapsulated_key: *mut u8, |
| 353 |
out_encapsulated_key_len: usize, |
| 354 |
out_ciphertext: *mut u8, |
| 355 |
out_ciphertext_len: usize, |
| 356 |
) -> i32 { |
| 357 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 358 |
if uuid_bytes.is_null() |
| 359 |
|| encapsulated_key.is_null() |
| 360 |
|| encapsulated_key_len == 0 |
| 361 |
|| out_encapsulated_key.is_null() |
| 362 |
|| out_encapsulated_key_len == 0 |
| 363 |
|| out_ciphertext.is_null() |
| 364 |
|| out_ciphertext_len == 0 |
| 365 |
{ |
| 366 |
return -1; |
| 367 |
} |
| 368 |
|
| 369 |
// Convert to Safe Types |
| 370 |
let uuid_slice = unsafe { slice::from_raw_parts(uuid_bytes, 16) }; |
| 371 |
let enc_key_slice = |
| 372 |
unsafe { slice::from_raw_parts(encapsulated_key, encapsulated_key_len) }; |
| 373 |
let aad_slice = if !aad.is_null() && aad_len > 0 { |
| 374 |
unsafe { slice::from_raw_parts(aad, aad_len) } |
| 375 |
} else { |
| 376 |
&[] |
| 377 |
}; |
| 378 |
let out_encapsulated_key_slice = |
| 379 |
unsafe { slice::from_raw_parts_mut(out_encapsulated_key, out_encapsulated_key_len) }; |
| 380 |
let out_ciphertext_slice = |
| 381 |
unsafe { slice::from_raw_parts_mut(out_ciphertext, out_ciphertext_len) }; |
| 382 |
|
| 383 |
let uuid = match Uuid::from_slice(uuid_slice) { |
| 384 |
Ok(u) => u, |
| 385 |
Err(_) => return -1, |
| 386 |
}; |
| 387 |
|
| 388 |
// Call Safe Internal Function |
| 389 |
match decap_and_seal_internal( |
| 390 |
uuid, |
| 391 |
enc_key_slice, |
| 392 |
aad_slice, |
| 393 |
out_encapsulated_key_slice, |
| 394 |
out_ciphertext_slice, |
| 395 |
) { |
| 396 |
Ok(_) => 0, // Success |
| 397 |
Err(e) => e, |
| 398 |
} |
| 399 |
})) |
| 400 |
.unwrap_or(-1) |
| 401 |
} |
| 402 |
|
| 403 |
/// Internal function to retrieve a KEM key's public keys and expiration. |
| 404 |
fn get_kem_key_internal(uuid: Uuid) -> Result<(HpkeAlgorithm, PublicKey, PublicKey, u64), i32> { |
| 405 |
let record = KEY_REGISTRY.get_key(&uuid).ok_or(-1)?; |
| 406 |
match &record.meta.spec { |
| 407 |
KeySpec::KemWithBindingPub { |
| 408 |
algo, |
| 409 |
kem_public_key, |
| 410 |
binding_public_key, |
| 411 |
.. |
| 412 |
} => { |
| 413 |
let remaining = record |
| 414 |
.meta |
| 415 |
.delete_after |
| 416 |
.saturating_duration_since(std::time::Instant::now()); |
| 417 |
Ok(( |
| 418 |
algo.clone(), |
| 419 |
kem_public_key.clone(), |
| 420 |
binding_public_key.clone(), |
| 421 |
remaining.as_secs(), |
| 422 |
)) |
| 423 |
} |
| 424 |
_ => Err(-1), |
| 425 |
} |
| 426 |
} |
| 427 |
|
| 428 |
/// Retrieves the KEM and binding public keys associated with the given UUID. |
| 429 |
/// |
| 430 |
/// ## Arguments |
| 431 |
/// * `uuid_bytes` - A pointer to a 16-byte buffer containing the key UUID. |
| 432 |
/// * `out_kem_pubkey` - A pointer to a buffer where the KEM public key will be written. |
| 433 |
/// * `out_kem_pubkey_len` - The size of `out_kem_pubkey` buffer. |
| 434 |
/// * `out_binding_pubkey` - A pointer to a buffer where the binding public key will be written. |
| 435 |
/// * `out_binding_pubkey_len` - The size of `out_binding_pubkey` buffer. |
| 436 |
/// * `out_algo` - A pointer to a buffer where the serialized HPKE algorithm proto bytes will be written. |
| 437 |
/// * `out_algo_len` - A pointer to a `usize` that contains the size of `out_algo` buffer. On success, updated with actual size. |
| 438 |
/// * `out_remaining_lifespan_secs` - A pointer to a u64 where the remaining lifespan in seconds will be written. |
| 439 |
/// |
| 440 |
/// ## Safety |
| 441 |
/// This function is unsafe because it dereferences raw pointers. |
| 442 |
/// |
| 443 |
/// ## Returns |
| 444 |
/// * `0` on success. |
| 445 |
/// * `-1` if arguments are invalid or key is not found. |
| 446 |
/// * `-2` if any output buffer is too small. |
| 447 |
#[unsafe(no_mangle)] |
| 448 |
pub unsafe extern "C" fn key_manager_get_kem_key( |
| 449 |
uuid_bytes: *const u8, |
| 450 |
out_kem_pubkey: *mut u8, |
| 451 |
out_kem_pubkey_len: usize, |
| 452 |
out_binding_pubkey: *mut u8, |
| 453 |
out_binding_pubkey_len: usize, |
| 454 |
out_algo: *mut u8, |
| 455 |
out_algo_len: *mut usize, |
| 456 |
out_remaining_lifespan_secs: *mut u64, |
| 457 |
) -> i32 { |
| 458 |
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 459 |
if uuid_bytes.is_null() |
| 460 |
|| out_kem_pubkey.is_null() |
| 461 |
|| out_kem_pubkey_len == 0 |
| 462 |
|| out_binding_pubkey.is_null() |
| 463 |
|| out_binding_pubkey_len == 0 |
| 464 |
|| out_algo.is_null() |
| 465 |
|| out_algo_len.is_null() |
| 466 |
|| out_remaining_lifespan_secs.is_null() |
| 467 |
{ |
| 468 |
return -1; |
| 469 |
} |
| 470 |
|
| 471 |
// Convert to Safe Types first |
| 472 |
let uuid_slice = unsafe { std::slice::from_raw_parts(uuid_bytes, 16) }; |
| 473 |
let out_kem_pubkey_slice = |
| 474 |
unsafe { std::slice::from_raw_parts_mut(out_kem_pubkey, out_kem_pubkey_len) }; |
| 475 |
let out_binding_pubkey_slice = |
| 476 |
unsafe { std::slice::from_raw_parts_mut(out_binding_pubkey, out_binding_pubkey_len) }; |
| 477 |
let out_remaining_lifespan_secs_ref = unsafe { &mut *out_remaining_lifespan_secs }; |
| 478 |
let out_algo_len_ref = unsafe { &mut *out_algo_len }; |
| 479 |
let out_algo_slice = unsafe { std::slice::from_raw_parts_mut(out_algo, *out_algo_len_ref) }; |
| 480 |
|
| 481 |
let uuid = match Uuid::from_slice(uuid_slice) { |
| 482 |
Ok(u) => u, |
| 483 |
Err(_) => return -1, |
| 484 |
}; |
| 485 |
|
| 486 |
// Call Safe Internal Function |
| 487 |
match get_kem_key_internal(uuid) { |
| 488 |
Ok((algo, kem_pubkey, binding_pubkey, remaining_secs)) => { |
| 489 |
let algo_bytes = algo.encode_to_vec(); |
| 490 |
if out_kem_pubkey_slice.len() != kem_pubkey.as_bytes().len() |
| 491 |
|| out_binding_pubkey_slice.len() != binding_pubkey.as_bytes().len() |
| 492 |
|| *out_algo_len_ref < algo_bytes.len() |
| 493 |
{ |
| 494 |
return -2; |
| 495 |
} |
| 496 |
|
| 497 |
out_kem_pubkey_slice.copy_from_slice(kem_pubkey.as_bytes()); |
| 498 |
out_binding_pubkey_slice.copy_from_slice(binding_pubkey.as_bytes()); |
| 499 |
out_algo_slice[..algo_bytes.len()].copy_from_slice(&algo_bytes); |
| 500 |
*out_algo_len_ref = algo_bytes.len(); |
| 501 |
*out_remaining_lifespan_secs_ref = remaining_secs; |
| 502 |
0 // Success |
| 503 |
} |
| 504 |
Err(e) => e, |
| 505 |
} |
| 506 |
})) |
| 507 |
.unwrap_or(-1) |
| 508 |
} |
| 509 |
|
| 510 |
#[cfg(test)] |
| 511 |
mod tests { |
| 512 |
use super::*; |
| 513 |
use km_common::algorithms::{AeadAlgorithm, KdfAlgorithm, KemAlgorithm}; |
| 514 |
use prost::Message; |
| 515 |
|
| 516 |
struct KeyCleanup(Uuid); |
| 517 |
impl Drop for KeyCleanup { |
| 518 |
fn drop(&mut self) { |
| 519 |
let _ = KEY_REGISTRY.remove_key(&self.0); |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
#[test] |
| 524 |
fn test_create_kem_key_success_and_zeroization() { |
| 525 |
let binding_pubkey = [1u8; 32]; |
| 526 |
let algo = HpkeAlgorithm { |
| 527 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 528 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 529 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 530 |
}; |
| 531 |
|
| 532 |
let result = generate_kem_keypair_internal( |
| 533 |
algo, |
| 534 |
PublicKey::try_from(binding_pubkey.to_vec()).unwrap(), |
| 535 |
3600, |
| 536 |
); |
| 537 |
assert!(result.is_ok()); |
| 538 |
|
| 539 |
let (id, _) = result.unwrap(); |
| 540 |
let _cleanup = KeyCleanup(id); |
| 541 |
|
| 542 |
// Verify UUID is present |
| 543 |
assert!(!id.is_nil()); |
| 544 |
} |
| 545 |
|
| 546 |
#[test] |
| 547 |
fn test_generate_kem_keypair_ffi_success() { |
| 548 |
let binding_pubkey = [1u8; 32]; |
| 549 |
let mut uuid_bytes = [0u8; 16]; |
| 550 |
let mut pubkey_bytes = [0u8; 32]; |
| 551 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 552 |
let algo = HpkeAlgorithm { |
| 553 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 554 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 555 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 556 |
}; |
| 557 |
let algo_bytes = algo.encode_to_vec(); |
| 558 |
|
| 559 |
let result = unsafe { |
| 560 |
key_manager_generate_kem_keypair( |
| 561 |
algo_bytes.as_ptr(), |
| 562 |
algo_bytes.len(), |
| 563 |
binding_pubkey.as_ptr(), |
| 564 |
binding_pubkey.len(), |
| 565 |
3600, |
| 566 |
uuid_bytes.as_mut_ptr(), |
| 567 |
pubkey_bytes.as_mut_ptr(), |
| 568 |
pubkey_len, |
| 569 |
) |
| 570 |
}; |
| 571 |
|
| 572 |
assert_eq!(result, 0); |
| 573 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 574 |
|
| 575 |
assert_ne!(uuid_bytes, [0u8; 16]); |
| 576 |
assert_eq!(pubkey_len, 32); // X25519 public key is 32 bytes |
| 577 |
assert_ne!(&pubkey_bytes[..32], &[0u8; 32]); |
| 578 |
} |
| 579 |
|
| 580 |
#[test] |
| 581 |
fn test_generate_kem_keypair_invalid_algo() { |
| 582 |
let binding_pubkey = [1u8; 32]; |
| 583 |
let mut uuid_bytes = [0u8; 16]; |
| 584 |
let mut pubkey_bytes = [0u8; 32]; |
| 585 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 586 |
// Invalid protobuf bytes |
| 587 |
let algo_bytes = vec![0xFF, 0xFF]; |
| 588 |
|
| 589 |
let result = unsafe { |
| 590 |
key_manager_generate_kem_keypair( |
| 591 |
algo_bytes.as_ptr(), |
| 592 |
algo_bytes.len(), |
| 593 |
binding_pubkey.as_ptr(), |
| 594 |
binding_pubkey.len(), |
| 595 |
3600, |
| 596 |
uuid_bytes.as_mut_ptr(), |
| 597 |
pubkey_bytes.as_mut_ptr(), |
| 598 |
pubkey_len, |
| 599 |
) |
| 600 |
}; |
| 601 |
|
| 602 |
assert_eq!(result, -1); |
| 603 |
assert_eq!(uuid_bytes, [0u8; 16]); |
| 604 |
} |
| 605 |
|
| 606 |
#[test] |
| 607 |
fn test_generate_kem_keypair_invalid_pubkey_len() { |
| 608 |
let binding_pubkey = [1u8; 32]; |
| 609 |
let mut uuid_bytes = [0u8; 16]; |
| 610 |
let mut pubkey_bytes = [0u8; 64]; |
| 611 |
let pubkey_len: usize = pubkey_bytes.len(); |
| 612 |
let algo = HpkeAlgorithm { |
| 613 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 614 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 615 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 616 |
}; |
| 617 |
let algo_bytes = algo.encode_to_vec(); |
| 618 |
|
| 619 |
let result = unsafe { |
| 620 |
key_manager_generate_kem_keypair( |
| 621 |
algo_bytes.as_ptr(), |
| 622 |
algo_bytes.len(), |
| 623 |
binding_pubkey.as_ptr(), |
| 624 |
binding_pubkey.len(), |
| 625 |
3600, |
| 626 |
uuid_bytes.as_mut_ptr(), |
| 627 |
pubkey_bytes.as_mut_ptr(), |
| 628 |
pubkey_len, |
| 629 |
) |
| 630 |
}; |
| 631 |
|
| 632 |
assert_eq!(result, -2); |
| 633 |
assert_eq!(uuid_bytes, [0u8; 16]); // Should remain untouched/zero |
| 634 |
assert_eq!(&pubkey_bytes[..32], &[0u8; 32]); // Should remain untouched/zero |
| 635 |
} |
| 636 |
|
| 637 |
#[test] |
| 638 |
fn test_generate_kem_keypair_null_binding_key() { |
| 639 |
let mut uuid_bytes = [0u8; 16]; |
| 640 |
let algo = HpkeAlgorithm { |
| 641 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 642 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 643 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 644 |
}; |
| 645 |
let algo_bytes = algo.encode_to_vec(); |
| 646 |
|
| 647 |
let result = unsafe { |
| 648 |
key_manager_generate_kem_keypair( |
| 649 |
algo_bytes.as_ptr(), |
| 650 |
algo_bytes.len(), |
| 651 |
std::ptr::null(), // Null ptr |
| 652 |
32, |
| 653 |
3600, |
| 654 |
uuid_bytes.as_mut_ptr(), |
| 655 |
std::ptr::null_mut(), |
| 656 |
0, |
| 657 |
) |
| 658 |
}; |
| 659 |
|
| 660 |
assert_eq!(result, -1); |
| 661 |
} |
| 662 |
|
| 663 |
#[test] |
| 664 |
fn test_generate_kem_keypair_empty_binding_key_len() { |
| 665 |
let binding_pubkey = [1u8; 32]; |
| 666 |
let mut uuid_bytes = [0u8; 16]; |
| 667 |
let algo = HpkeAlgorithm { |
| 668 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 669 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 670 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 671 |
}; |
| 672 |
let algo_bytes = algo.encode_to_vec(); |
| 673 |
|
| 674 |
let result = unsafe { |
| 675 |
key_manager_generate_kem_keypair( |
| 676 |
algo_bytes.as_ptr(), |
| 677 |
algo_bytes.len(), |
| 678 |
binding_pubkey.as_ptr(), |
| 679 |
0, // Empty length |
| 680 |
3600, |
| 681 |
uuid_bytes.as_mut_ptr(), |
| 682 |
std::ptr::null_mut(), |
| 683 |
0, |
| 684 |
) |
| 685 |
}; |
| 686 |
|
| 687 |
assert_eq!(result, -1); |
| 688 |
} |
| 689 |
|
| 690 |
#[test] |
| 691 |
fn test_destroy_kem_key_success() { |
| 692 |
let binding_pubkey = [1u8; 32]; |
| 693 |
let mut uuid_bytes = [0u8; 16]; |
| 694 |
let mut pubkey_bytes = [0u8; 32]; |
| 695 |
let pubkey_len = pubkey_bytes.len(); |
| 696 |
let algo = HpkeAlgorithm { |
| 697 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 698 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 699 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 700 |
}; |
| 701 |
let algo_bytes = algo.encode_to_vec(); |
| 702 |
unsafe { |
| 703 |
let res = key_manager_generate_kem_keypair( |
| 704 |
algo_bytes.as_ptr(), |
| 705 |
algo_bytes.len(), |
| 706 |
binding_pubkey.as_ptr(), |
| 707 |
binding_pubkey.len(), |
| 708 |
3600, |
| 709 |
uuid_bytes.as_mut_ptr(), |
| 710 |
pubkey_bytes.as_mut_ptr(), |
| 711 |
pubkey_len, |
| 712 |
); |
| 713 |
assert_eq!(res, 0); |
| 714 |
} |
| 715 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 716 |
|
| 717 |
let result = unsafe { key_manager_destroy_kem_key(uuid_bytes.as_ptr()) }; |
| 718 |
assert_eq!(result, 0); |
| 719 |
|
| 720 |
// Second destroy should fail |
| 721 |
let result = unsafe { key_manager_destroy_kem_key(uuid_bytes.as_ptr()) }; |
| 722 |
assert_eq!(result, -1); |
| 723 |
} |
| 724 |
|
| 725 |
#[test] |
| 726 |
fn test_destroy_kem_key_not_found() { |
| 727 |
let uuid_bytes = [0u8; 16]; |
| 728 |
let result = unsafe { key_manager_destroy_kem_key(uuid_bytes.as_ptr()) }; |
| 729 |
assert_eq!(result, -1); |
| 730 |
} |
| 731 |
|
| 732 |
#[test] |
| 733 |
fn test_destroy_kem_key_null_ptr() { |
| 734 |
let result = unsafe { key_manager_destroy_kem_key(std::ptr::null()) }; |
| 735 |
assert_eq!(result, -1); |
| 736 |
} |
| 737 |
|
| 738 |
#[test] |
| 739 |
fn test_enumerate_kem_keys_null_pointers() { |
| 740 |
let result = unsafe { key_manager_enumerate_kem_keys(std::ptr::null_mut(), 10, 0, None) }; |
| 741 |
assert_eq!(result, -1); |
| 742 |
} |
| 743 |
|
| 744 |
#[test] |
| 745 |
fn test_enumerate_kem_keys_after_generate() { |
| 746 |
let binding_pubkey = [7u8; 32]; |
| 747 |
let mut uuid_bytes = [0u8; 16]; |
| 748 |
let mut pubkey_bytes = [0u8; 32]; |
| 749 |
let pubkey_len: usize = 32; |
| 750 |
let algo = HpkeAlgorithm { |
| 751 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 752 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 753 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 754 |
}; |
| 755 |
// MUST encode to bytes |
| 756 |
let algo_bytes = algo.encode_to_vec(); |
| 757 |
|
| 758 |
// Generate a key first. |
| 759 |
let rc = unsafe { |
| 760 |
key_manager_generate_kem_keypair( |
| 761 |
algo_bytes.as_ptr(), |
| 762 |
algo_bytes.len(), |
| 763 |
binding_pubkey.as_ptr(), |
| 764 |
binding_pubkey.len(), |
| 765 |
3600, |
| 766 |
uuid_bytes.as_mut_ptr(), |
| 767 |
pubkey_bytes.as_mut_ptr(), |
| 768 |
pubkey_len, |
| 769 |
) |
| 770 |
}; |
| 771 |
assert_eq!(rc, 0); |
| 772 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 773 |
|
| 774 |
// Enumerate. |
| 775 |
let mut entries: Vec<KpsKeyInfo> = Vec::with_capacity(256); |
| 776 |
// Initialize with default/zero values. Note: Arrays are larger now. |
| 777 |
entries.resize_with(100, || KpsKeyInfo { |
| 778 |
uuid: [0; 16], |
| 779 |
algorithm: [0; MAX_ALGORITHM_LEN], |
| 780 |
algorithm_len: 0, |
| 781 |
pub_key: [0; MAX_PUBLIC_KEY_LEN], |
| 782 |
pub_key_len: 0, |
| 783 |
binding_pub_key: [0; MAX_PUBLIC_KEY_LEN], |
| 784 |
binding_pub_key_len: 0, |
| 785 |
remaining_lifespan_secs: 0, |
| 786 |
}); |
| 787 |
let mut has_more = false; |
| 788 |
|
| 789 |
let rc = unsafe { |
| 790 |
// max_entries=100, offset=0 |
| 791 |
key_manager_enumerate_kem_keys( |
| 792 |
entries.as_mut_ptr(), |
| 793 |
entries.len(), |
| 794 |
0, |
| 795 |
Some(&mut has_more), |
| 796 |
) |
| 797 |
}; |
| 798 |
assert!(rc >= 1); |
| 799 |
let count = rc as usize; |
| 800 |
|
| 801 |
// Find our key in the results. |
| 802 |
let mut found = false; |
| 803 |
for i in 0..count { |
| 804 |
if entries[i].uuid == uuid_bytes { |
| 805 |
found = true; |
| 806 |
let encoded_algo = &entries[i].algorithm[..entries[i].algorithm_len]; |
| 807 |
let decoded_algo = HpkeAlgorithm::decode(encoded_algo).unwrap(); |
| 808 |
assert_eq!(decoded_algo.kem, KemAlgorithm::DhkemX25519HkdfSha256 as i32); |
| 809 |
assert_eq!(entries[i].pub_key_len, 32); |
| 810 |
assert!(entries[i].remaining_lifespan_secs > 0); |
| 811 |
break; |
| 812 |
} |
| 813 |
} |
| 814 |
assert!(found, "generated key not found in enumerate results"); |
| 815 |
} |
| 816 |
|
| 817 |
#[test] |
| 818 |
fn test_enumerate_kem_keys_has_more() { |
| 819 |
// Assume there is at least one key from initialization/other tests or we'll generate one |
| 820 |
let mut uuid_bytes = [0u8; 16]; |
| 821 |
let mut pubkey_bytes = [0u8; 32]; |
| 822 |
let algo = HpkeAlgorithm { |
| 823 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 824 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 825 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 826 |
}; |
| 827 |
let algo_bytes = algo.encode_to_vec(); |
| 828 |
|
| 829 |
// Let's explicitly generate a key so we know there's at least one in the registry |
| 830 |
unsafe { |
| 831 |
key_manager_generate_kem_keypair( |
| 832 |
algo_bytes.as_ptr(), |
| 833 |
algo_bytes.len(), |
| 834 |
[7u8; 32].as_ptr(), // fake binding key |
| 835 |
32, |
| 836 |
3600, |
| 837 |
uuid_bytes.as_mut_ptr(), |
| 838 |
pubkey_bytes.as_mut_ptr(), |
| 839 |
32, |
| 840 |
); |
| 841 |
} |
| 842 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 843 |
|
| 844 |
let mut entries: Vec<KpsKeyInfo> = Vec::with_capacity(256); |
| 845 |
entries.resize_with(100, || KpsKeyInfo { |
| 846 |
uuid: [0; 16], |
| 847 |
algorithm: [0; MAX_ALGORITHM_LEN], |
| 848 |
algorithm_len: 0, |
| 849 |
pub_key: [0; MAX_PUBLIC_KEY_LEN], |
| 850 |
pub_key_len: 0, |
| 851 |
binding_pub_key: [0; MAX_PUBLIC_KEY_LEN], |
| 852 |
binding_pub_key_len: 0, |
| 853 |
remaining_lifespan_secs: 0, |
| 854 |
}); |
| 855 |
|
| 856 |
// 1. Ask for 0 entries. We should get has_more = true. |
| 857 |
let mut has_more = false; |
| 858 |
let rc = unsafe { |
| 859 |
key_manager_enumerate_kem_keys(entries.as_mut_ptr(), 0, 0, Some(&mut has_more)) |
| 860 |
}; |
| 861 |
assert_eq!(rc, 0); |
| 862 |
assert!( |
| 863 |
has_more, |
| 864 |
"has_more should be true when max_entries is 0 and keys exist" |
| 865 |
); |
| 866 |
|
| 867 |
// 2. Ask for 100 entries (which should cover all generated keys). has_more = false. |
| 868 |
has_more = true; // reset to true to ensure it gets set to false |
| 869 |
let rc = unsafe { |
| 870 |
key_manager_enumerate_kem_keys( |
| 871 |
entries.as_mut_ptr(), |
| 872 |
entries.len(), |
| 873 |
0, |
| 874 |
Some(&mut has_more), |
| 875 |
) |
| 876 |
}; |
| 877 |
assert!(rc >= 1); |
| 878 |
assert!( |
| 879 |
!has_more, |
| 880 |
"has_more should be false when all keys are retrieved" |
| 881 |
); |
| 882 |
} |
| 883 |
|
| 884 |
#[test] |
| 885 |
fn test_decap_and_seal_success() { |
| 886 |
// 1. Setup binding key (receiver for seal) |
| 887 |
let binding_kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 888 |
let (binding_pk, binding_sk) = |
| 889 |
km_common::crypto::generate_keypair(binding_kem_algo).unwrap(); |
| 890 |
|
| 891 |
// 2. Generate KEM key in registry |
| 892 |
let mut uuid_bytes = [0u8; 16]; |
| 893 |
let mut kem_pubkey_bytes = [0u8; 32]; |
| 894 |
let kem_pubkey_len = 32; |
| 895 |
let algo = HpkeAlgorithm { |
| 896 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 897 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 898 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 899 |
}; |
| 900 |
let algo_bytes = algo.encode_to_vec(); |
| 901 |
unsafe { |
| 902 |
key_manager_generate_kem_keypair( |
| 903 |
algo_bytes.as_ptr(), |
| 904 |
algo_bytes.len(), |
| 905 |
binding_pk.as_bytes().as_ptr(), |
| 906 |
binding_pk.as_bytes().len(), |
| 907 |
3600, |
| 908 |
uuid_bytes.as_mut_ptr(), |
| 909 |
kem_pubkey_bytes.as_mut_ptr(), |
| 910 |
kem_pubkey_len, |
| 911 |
) |
| 912 |
}; |
| 913 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 914 |
|
| 915 |
// 3. Generate a "client" ciphertext/encapsulation targeting KEM key. |
| 916 |
let aad = b"test_aad"; |
| 917 |
// We use `encap` to act as the client to generate a valid encapsulation |
| 918 |
let pub_key_obj = PublicKey::try_from(kem_pubkey_bytes.to_vec()).unwrap(); |
| 919 |
let (client_shared_secret, client_enc) = km_common::crypto::encap(&pub_key_obj).unwrap(); |
| 920 |
|
| 921 |
// Call `decap_and_seal`. |
| 922 |
let mut out_enc_key = [0u8; 32]; |
| 923 |
let out_enc_key_len = 32; |
| 924 |
let mut out_ct = [0u8; 48]; // 32 bytes secret + 16 tag |
| 925 |
let out_ct_len = 48; |
| 926 |
|
| 927 |
let result = unsafe { |
| 928 |
key_manager_decap_and_seal( |
| 929 |
uuid_bytes.as_ptr(), |
| 930 |
client_enc.as_ptr(), |
| 931 |
client_enc.len(), |
| 932 |
aad.as_ptr(), |
| 933 |
aad.len(), |
| 934 |
out_enc_key.as_mut_ptr(), |
| 935 |
out_enc_key_len, |
| 936 |
out_ct.as_mut_ptr(), |
| 937 |
out_ct_len, |
| 938 |
) |
| 939 |
}; |
| 940 |
|
| 941 |
assert_eq!(result, 0); |
| 942 |
|
| 943 |
// 4. Verify we can decrypt the result using binding_sk |
| 944 |
let recovered_shared_secret = |
| 945 |
km_common::crypto::hpke_open(&binding_sk, &out_enc_key, &out_ct, aad, &algo) |
| 946 |
.expect("Failed to decrypt the resealed secret"); |
| 947 |
|
| 948 |
assert_eq!(recovered_shared_secret.as_slice().len(), 32); |
| 949 |
|
| 950 |
// 5. Verify the recovered secret matches what decaps would produce |
| 951 |
// And also matches the original client shared secret |
| 952 |
assert_eq!( |
| 953 |
recovered_shared_secret.as_slice(), |
| 954 |
client_shared_secret.as_slice(), |
| 955 |
"Recovered secret mismatch" |
| 956 |
); |
| 957 |
} |
| 958 |
|
| 959 |
#[test] |
| 960 |
fn test_decap_and_seal_invalid_uuid() { |
| 961 |
let mut out_enc_key = [0u8; 32]; |
| 962 |
let out_enc_key_len = 32; |
| 963 |
let mut out_ct = [0u8; 48]; |
| 964 |
let out_ct_len = 48; |
| 965 |
|
| 966 |
let result = unsafe { |
| 967 |
key_manager_decap_and_seal( |
| 968 |
[0u8; 16].as_ptr(), |
| 969 |
[0u8; 32].as_ptr(), |
| 970 |
32, |
| 971 |
std::ptr::null(), |
| 972 |
0, |
| 973 |
out_enc_key.as_mut_ptr(), |
| 974 |
out_enc_key_len, |
| 975 |
out_ct.as_mut_ptr(), |
| 976 |
out_ct_len, |
| 977 |
) |
| 978 |
}; |
| 979 |
|
| 980 |
assert_eq!(result, -1); |
| 981 |
} |
| 982 |
|
| 983 |
#[test] |
| 984 |
fn test_decap_and_seal_null_args() { |
| 985 |
let mut out_enc_key = [0u8; 32]; |
| 986 |
let out_enc_key_len = 32; |
| 987 |
|
| 988 |
let result = unsafe { |
| 989 |
key_manager_decap_and_seal( |
| 990 |
std::ptr::null(), |
| 991 |
std::ptr::null(), |
| 992 |
0, |
| 993 |
std::ptr::null(), |
| 994 |
0, |
| 995 |
out_enc_key.as_mut_ptr(), |
| 996 |
out_enc_key_len, |
| 997 |
std::ptr::null_mut(), |
| 998 |
0, |
| 999 |
) |
| 1000 |
}; |
| 1001 |
|
| 1002 |
assert_eq!(result, -1); |
| 1003 |
} |
| 1004 |
|
| 1005 |
#[test] |
| 1006 |
fn test_decap_and_seal_decaps_fail() { |
| 1007 |
// 1. Setup binding key |
| 1008 |
let binding_kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 1009 |
let (binding_pk, _) = km_common::crypto::generate_keypair(binding_kem_algo).unwrap(); |
| 1010 |
|
| 1011 |
// 2. Generate KEM key |
| 1012 |
let mut uuid_bytes = [0u8; 16]; |
| 1013 |
let mut kem_pubkey_bytes = [0u8; 32]; |
| 1014 |
let kem_pubkey_len = 32; |
| 1015 |
let algo = HpkeAlgorithm { |
| 1016 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 1017 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 1018 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 1019 |
}; |
| 1020 |
let algo_bytes = algo.encode_to_vec(); |
| 1021 |
let res = unsafe { |
| 1022 |
key_manager_generate_kem_keypair( |
| 1023 |
algo_bytes.as_ptr(), |
| 1024 |
algo_bytes.len(), |
| 1025 |
binding_pk.as_bytes().as_ptr(), |
| 1026 |
binding_pk.as_bytes().len(), |
| 1027 |
3600, |
| 1028 |
uuid_bytes.as_mut_ptr(), |
| 1029 |
kem_pubkey_bytes.as_mut_ptr(), |
| 1030 |
kem_pubkey_len, |
| 1031 |
) |
| 1032 |
}; |
| 1033 |
assert_eq!(res, 0); |
| 1034 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 1035 |
|
| 1036 |
// 3. Call with invalid encapsulated key (wrong length for X25519) |
| 1037 |
let mut out_enc_key = [0u8; 32]; |
| 1038 |
let out_enc_key_len = 32; |
| 1039 |
let mut out_ct = [0u8; 48]; |
| 1040 |
let out_ct_len = 48; |
| 1041 |
|
| 1042 |
let result = unsafe { |
| 1043 |
key_manager_decap_and_seal( |
| 1044 |
uuid_bytes.as_ptr(), |
| 1045 |
[0u8; 31].as_ptr(), |
| 1046 |
31, |
| 1047 |
std::ptr::null(), |
| 1048 |
0, |
| 1049 |
out_enc_key.as_mut_ptr(), |
| 1050 |
out_enc_key_len, |
| 1051 |
out_ct.as_mut_ptr(), |
| 1052 |
out_ct_len, |
| 1053 |
) |
| 1054 |
}; |
| 1055 |
|
| 1056 |
assert_eq!(result, -3); |
| 1057 |
} |
| 1058 |
|
| 1059 |
#[test] |
| 1060 |
fn test_decap_and_seal_buffer_too_small() { |
| 1061 |
// 1. Setup binding key |
| 1062 |
let binding_kem_algo = KemAlgorithm::DhkemX25519HkdfSha256; |
| 1063 |
let (binding_pk, _) = km_common::crypto::generate_keypair(binding_kem_algo).unwrap(); |
| 1064 |
|
| 1065 |
// 2. Generate KEM key |
| 1066 |
let mut uuid_bytes = [0u8; 16]; |
| 1067 |
let mut kem_pubkey_bytes = [0u8; 32]; |
| 1068 |
let kem_pubkey_len = 32; |
| 1069 |
let algo = HpkeAlgorithm { |
| 1070 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 1071 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 1072 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 1073 |
}; |
| 1074 |
|
| 1075 |
let algo_bytes = algo.encode_to_vec(); |
| 1076 |
let res = unsafe { |
| 1077 |
key_manager_generate_kem_keypair( |
| 1078 |
algo_bytes.as_ptr(), |
| 1079 |
algo_bytes.len(), |
| 1080 |
binding_pk.as_bytes().as_ptr(), |
| 1081 |
binding_pk.as_bytes().len(), |
| 1082 |
3600, |
| 1083 |
uuid_bytes.as_mut_ptr(), |
| 1084 |
kem_pubkey_bytes.as_mut_ptr(), |
| 1085 |
kem_pubkey_len, |
| 1086 |
) |
| 1087 |
}; |
| 1088 |
assert_eq!(res, 0, "Setup failed: key generation returned error"); |
| 1089 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 1090 |
|
| 1091 |
// 3. Generate valid client encapsulation |
| 1092 |
let pub_key_obj = PublicKey::try_from(kem_pubkey_bytes.to_vec()).unwrap(); |
| 1093 |
let pt = km_common::crypto::secret_box::SecretBox::new(b"secret".to_vec()); |
| 1094 |
let (client_enc, _) = km_common::crypto::hpke_seal(&pub_key_obj, &pt, b"", &algo).unwrap(); |
| 1095 |
|
| 1096 |
// 4. Call with small output buffers |
| 1097 |
let mut out_enc_key = [0u8; 31]; // Small |
| 1098 |
let out_enc_key_len = 31; |
| 1099 |
let mut out_ct = [0u8; 47]; // Small |
| 1100 |
let out_ct_len = 47; |
| 1101 |
|
| 1102 |
let result = unsafe { |
| 1103 |
key_manager_decap_and_seal( |
| 1104 |
uuid_bytes.as_ptr(), |
| 1105 |
client_enc.as_ptr(), |
| 1106 |
client_enc.len(), |
| 1107 |
std::ptr::null(), |
| 1108 |
0, |
| 1109 |
out_enc_key.as_mut_ptr(), |
| 1110 |
out_enc_key_len, |
| 1111 |
out_ct.as_mut_ptr(), |
| 1112 |
out_ct_len, |
| 1113 |
) |
| 1114 |
}; |
| 1115 |
|
| 1116 |
assert_eq!(result, -2); |
| 1117 |
} |
| 1118 |
|
| 1119 |
#[test] |
| 1120 |
fn test_get_kem_key_success() { |
| 1121 |
let binding_pubkey = [42u8; 32]; |
| 1122 |
let mut uuid_bytes = [0u8; 16]; |
| 1123 |
let mut generated_kem_pubkey_bytes = [0u8; 32]; |
| 1124 |
let pubkey_len = generated_kem_pubkey_bytes.len(); |
| 1125 |
let algo = HpkeAlgorithm { |
| 1126 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 1127 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 1128 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 1129 |
}; |
| 1130 |
let algo_bytes = algo.encode_to_vec(); |
| 1131 |
|
| 1132 |
// Generate a key to retrieve. |
| 1133 |
let res = unsafe { |
| 1134 |
key_manager_generate_kem_keypair( |
| 1135 |
algo_bytes.as_ptr(), |
| 1136 |
algo_bytes.len(), |
| 1137 |
binding_pubkey.as_ptr(), |
| 1138 |
binding_pubkey.len(), |
| 1139 |
3600, |
| 1140 |
uuid_bytes.as_mut_ptr(), |
| 1141 |
generated_kem_pubkey_bytes.as_mut_ptr(), |
| 1142 |
pubkey_len, |
| 1143 |
) |
| 1144 |
}; |
| 1145 |
assert_eq!(res, 0); |
| 1146 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 1147 |
|
| 1148 |
// Now, retrieve it. |
| 1149 |
let mut retrieved_kem_pubkey_bytes = [0u8; 32]; |
| 1150 |
let mut retrieved_binding_pubkey_bytes = [0u8; 32]; |
| 1151 |
let mut retrieved_algo_bytes = [0u8; 128]; |
| 1152 |
let mut retrieved_algo_len: usize = retrieved_algo_bytes.len(); |
| 1153 |
let mut remaining_lifespan_secs: u64 = 0; |
| 1154 |
|
| 1155 |
let result = unsafe { |
| 1156 |
key_manager_get_kem_key( |
| 1157 |
uuid_bytes.as_ptr(), |
| 1158 |
retrieved_kem_pubkey_bytes.as_mut_ptr(), |
| 1159 |
retrieved_kem_pubkey_bytes.len(), |
| 1160 |
retrieved_binding_pubkey_bytes.as_mut_ptr(), |
| 1161 |
retrieved_binding_pubkey_bytes.len(), |
| 1162 |
retrieved_algo_bytes.as_mut_ptr(), |
| 1163 |
&mut retrieved_algo_len, |
| 1164 |
&mut remaining_lifespan_secs, |
| 1165 |
) |
| 1166 |
}; |
| 1167 |
|
| 1168 |
assert_eq!(result, 0); |
| 1169 |
assert_eq!(generated_kem_pubkey_bytes, retrieved_kem_pubkey_bytes); |
| 1170 |
assert_eq!(binding_pubkey, retrieved_binding_pubkey_bytes); |
| 1171 |
assert_eq!(algo_bytes, &retrieved_algo_bytes[..retrieved_algo_len]); |
| 1172 |
assert!(remaining_lifespan_secs > 0); |
| 1173 |
assert!(remaining_lifespan_secs <= 3600); |
| 1174 |
} |
| 1175 |
|
| 1176 |
#[test] |
| 1177 |
fn test_get_kem_key_not_found() { |
| 1178 |
let uuid_bytes = [42u8; 16]; // Some non-existent UUID. |
| 1179 |
let mut kem_pubkey_bytes = [0u8; 32]; |
| 1180 |
let mut binding_pubkey_bytes = [0u8; 32]; |
| 1181 |
let mut retrieved_algo_bytes = [0u8; 128]; |
| 1182 |
let mut retrieved_algo_len: usize = retrieved_algo_bytes.len(); |
| 1183 |
let mut remaining_lifespan_secs: u64 = 0; |
| 1184 |
|
| 1185 |
let result = unsafe { |
| 1186 |
key_manager_get_kem_key( |
| 1187 |
uuid_bytes.as_ptr(), |
| 1188 |
kem_pubkey_bytes.as_mut_ptr(), |
| 1189 |
kem_pubkey_bytes.len(), |
| 1190 |
binding_pubkey_bytes.as_mut_ptr(), |
| 1191 |
binding_pubkey_bytes.len(), |
| 1192 |
retrieved_algo_bytes.as_mut_ptr(), |
| 1193 |
&mut retrieved_algo_len, |
| 1194 |
&mut remaining_lifespan_secs, |
| 1195 |
) |
| 1196 |
}; |
| 1197 |
assert_eq!(result, -1); |
| 1198 |
} |
| 1199 |
|
| 1200 |
#[test] |
| 1201 |
fn test_get_kem_key_invalid_buffer_len() { |
| 1202 |
let binding_pubkey = [42u8; 32]; |
| 1203 |
let mut uuid_bytes = [0u8; 16]; |
| 1204 |
let mut generated_kem_pubkey_bytes = [0u8; 32]; |
| 1205 |
let pubkey_len = generated_kem_pubkey_bytes.len(); |
| 1206 |
let algo = HpkeAlgorithm { |
| 1207 |
kem: KemAlgorithm::DhkemX25519HkdfSha256 as i32, |
| 1208 |
kdf: KdfAlgorithm::HkdfSha256 as i32, |
| 1209 |
aead: AeadAlgorithm::Aes256Gcm as i32, |
| 1210 |
}; |
| 1211 |
let algo_bytes = algo.encode_to_vec(); |
| 1212 |
|
| 1213 |
// Generate a key to retrieve. |
| 1214 |
let res = unsafe { |
| 1215 |
key_manager_generate_kem_keypair( |
| 1216 |
algo_bytes.as_ptr(), |
| 1217 |
algo_bytes.len(), |
| 1218 |
binding_pubkey.as_ptr(), |
| 1219 |
binding_pubkey.len(), |
| 1220 |
3600, |
| 1221 |
uuid_bytes.as_mut_ptr(), |
| 1222 |
generated_kem_pubkey_bytes.as_mut_ptr(), |
| 1223 |
pubkey_len, |
| 1224 |
) |
| 1225 |
}; |
| 1226 |
assert_eq!(res, 0); |
| 1227 |
let _cleanup = KeyCleanup(Uuid::from_bytes(uuid_bytes)); |
| 1228 |
|
| 1229 |
// Now, retrieve it with invalid buffer lengths. |
| 1230 |
let mut retrieved_kem_pubkey_bytes = [0u8; 32]; |
| 1231 |
let mut retrieved_binding_pubkey_bytes = [0u8; 32]; |
| 1232 |
let mut retrieved_algo_bytes = [0u8; 128]; |
| 1233 |
let mut retrieved_algo_len: usize = retrieved_algo_bytes.len(); |
| 1234 |
let mut remaining_lifespan_secs: u64 = 0; |
| 1235 |
|
| 1236 |
// KEM pubkey buffer too small. |
| 1237 |
let result = unsafe { |
| 1238 |
key_manager_get_kem_key( |
| 1239 |
uuid_bytes.as_ptr(), |
| 1240 |
retrieved_kem_pubkey_bytes.as_mut_ptr(), |
| 1241 |
31, // Invalid length |
| 1242 |
retrieved_binding_pubkey_bytes.as_mut_ptr(), |
| 1243 |
32, |
| 1244 |
retrieved_algo_bytes.as_mut_ptr(), |
| 1245 |
&mut retrieved_algo_len, |
| 1246 |
&mut remaining_lifespan_secs, |
| 1247 |
) |
| 1248 |
}; |
| 1249 |
assert_eq!(result, -2); |
| 1250 |
|
| 1251 |
// Binding pubkey buffer too small. |
| 1252 |
let result = unsafe { |
| 1253 |
key_manager_get_kem_key( |
| 1254 |
uuid_bytes.as_ptr(), |
| 1255 |
retrieved_kem_pubkey_bytes.as_mut_ptr(), |
| 1256 |
32, |
| 1257 |
retrieved_binding_pubkey_bytes.as_mut_ptr(), |
| 1258 |
33, // Invalid length |
| 1259 |
retrieved_algo_bytes.as_mut_ptr(), |
| 1260 |
&mut retrieved_algo_len, |
| 1261 |
&mut remaining_lifespan_secs, |
| 1262 |
) |
| 1263 |
}; |
| 1264 |
assert_eq!(result, -2); |
| 1265 |
} |
| 1266 |
} |