1use aes::Aes128;
22use aes::cipher::{BlockCipherEncrypt, KeyInit};
23use ccm::aead::AeadInOut;
24use ccm::{Ccm, KeyInit as CcmKeyInit};
25use hmac::{Mac, SimpleHmac};
26use p256::ecdsa::signature::hazmat::PrehashSigner;
27use p256::ecdsa::signature::hazmat::PrehashVerifier;
28use p256::ecdsa::{Signature as EcdsaSignature, SigningKey, VerifyingKey};
29use sha2::{Digest, Sha256};
30
31use super::{
32 AEAD_MIC_LENGTH_BYTES, AEAD_NONCE_LENGTH_BYTES, GROUP_SIZE_BYTES, HASH_LEN_BYTES, KeyHandle,
33 KeyPurpose, KeyStore, PRIVACY_KEY_INFO, PUBLIC_KEY_SIZE_BYTES, PublicKey,
34 SYMMETRIC_KEY_LENGTH_BYTES, Secret, Signature, SymmetricKey,
35};
36use crate::error::{Error, ErrorCode, Result};
37
38type Aes128Ccm = Ccm<Aes128, ccm::consts::U16, ccm::consts::U13>;
40
41type HmacSha256 = SimpleHmac<Sha256>;
43
44fn crypto_error(_: impl core::fmt::Debug) -> Error {
45 Error::new(ErrorCode::IntegrityCheckFailed)
46}
47
48#[must_use]
52pub fn hash(message: &[u8]) -> [u8; HASH_LEN_BYTES] {
53 Sha256::digest(message).into()
54}
55
56#[derive(Clone, Default)]
58pub struct Hasher(Sha256);
59
60impl Hasher {
61 #[must_use]
63 pub fn new() -> Self {
64 Self(Sha256::new())
65 }
66
67 pub fn update(&mut self, data: &[u8]) {
69 self.0.update(data);
70 }
71
72 #[must_use]
74 pub fn finish(self) -> [u8; HASH_LEN_BYTES] {
75 self.0.finalize().into()
76 }
77}
78
79impl core::fmt::Debug for Hasher {
80 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
81 f.write_str("Hasher(..)")
82 }
83}
84
85pub fn hmac(key: &[u8], message: &[u8]) -> Result<[u8; HASH_LEN_BYTES]> {
87 let mut mac = HmacSha256::new_from_slice(key).map_err(crypto_error)?;
88 mac.update(message);
89 Ok(mac.finalize().into_bytes().into())
90}
91
92pub fn kdf(input_key: &[u8], salt: &[u8], info: &[u8], out: &mut [u8]) -> Result<()> {
98 let hk = hkdf::Hkdf::<Sha256>::new(Some(salt), input_key);
99 hk.expand(info, out).map_err(crypto_error)
100}
101
102pub fn kdf_key(input_key: &[u8], salt: &[u8], info: &[u8]) -> Result<SymmetricKey> {
104 let mut out = [0u8; SYMMETRIC_KEY_LENGTH_BYTES];
105 kdf(input_key, salt, info, &mut out)?;
106 Ok(SymmetricKey::new(out))
107}
108
109pub fn pbkdf(password: &[u8], salt: &[u8], iterations: u32, out: &mut [u8]) -> Result<()> {
116 if !(super::PBKDF_ITERATIONS_MIN..=super::PBKDF_ITERATIONS_MAX).contains(&iterations) {
117 return Err(Error::new(ErrorCode::InvalidArgument));
118 }
119 if !(super::PBKDF_SALT_MIN_BYTES..=super::PBKDF_SALT_MAX_BYTES).contains(&salt.len()) {
120 return Err(Error::new(ErrorCode::InvalidArgument));
121 }
122 pbkdf2::pbkdf2::<HmacSha256>(password, salt, iterations, out).map_err(crypto_error)
123}
124
125pub fn aead_encrypt_in_place(
131 key: &SymmetricKey,
132 nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
133 aad: &[u8],
134 buffer: &mut [u8],
135 tag: &mut [u8; AEAD_MIC_LENGTH_BYTES],
136) -> Result<()> {
137 let cipher = <Aes128Ccm as CcmKeyInit>::new_from_slice(key.as_bytes()).map_err(crypto_error)?;
138 let computed = cipher
139 .encrypt_inout_detached(nonce.into(), aad, buffer.into())
140 .map_err(crypto_error)?;
141 tag.copy_from_slice(&computed);
142 Ok(())
143}
144
145pub fn aead_decrypt_in_place(
151 key: &SymmetricKey,
152 nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
153 aad: &[u8],
154 buffer: &mut [u8],
155 tag: &[u8; AEAD_MIC_LENGTH_BYTES],
156) -> Result<()> {
157 let cipher = <Aes128Ccm as CcmKeyInit>::new_from_slice(key.as_bytes()).map_err(crypto_error)?;
158 cipher
159 .decrypt_inout_detached(nonce.into(), aad, buffer.into(), tag.into())
160 .map_err(crypto_error)
161}
162
163pub fn privacy_xor(
175 key: &SymmetricKey,
176 nonce: &[u8; AEAD_NONCE_LENGTH_BYTES],
177 buffer: &mut [u8],
178) -> Result<()> {
179 const BLOCK: usize = 16;
180 let cipher = <Aes128 as KeyInit>::new_from_slice(key.as_bytes()).map_err(crypto_error)?;
181
182 let blocks = buffer.len().div_ceil(BLOCK);
184 if blocks > usize::from(u16::MAX) + 1 {
185 return Err(Error::new(ErrorCode::InvalidArgument));
186 }
187
188 for (index, chunk) in buffer.chunks_mut(BLOCK).enumerate() {
189 let mut counter_block = [0u8; BLOCK];
190 counter_block[0] = 0x01;
192 let Some(slot) = counter_block.get_mut(1..1 + AEAD_NONCE_LENGTH_BYTES) else {
193 return Err(Error::new(ErrorCode::InvalidArgument));
194 };
195 slot.copy_from_slice(nonce);
196 let Ok(index) = u16::try_from(index) else {
197 return Err(Error::new(ErrorCode::InvalidArgument));
198 };
199 let Some(slot) = counter_block.get_mut(14..16) else {
200 return Err(Error::new(ErrorCode::InvalidArgument));
201 };
202 slot.copy_from_slice(&index.to_be_bytes());
203
204 cipher.encrypt_block((&mut counter_block).into());
205 for (b, k) in chunk.iter_mut().zip(counter_block.iter()) {
206 *b ^= *k;
207 }
208 }
209 Ok(())
210}
211
212pub fn privacy_key(encryption_key: &SymmetricKey) -> Result<SymmetricKey> {
217 kdf_key(encryption_key.as_bytes(), &[], PRIVACY_KEY_INFO)
218}
219
220pub(super) fn verify_impl(
224 public: &PublicKey,
225 message: &[u8],
226 signature: &Signature,
227) -> Result<bool> {
228 let Ok(verifying) = VerifyingKey::from_sec1_bytes(public.as_bytes()) else {
229 return Err(Error::new(ErrorCode::InvalidArgument));
230 };
231 let Ok(sig) = EcdsaSignature::from_slice(signature.as_bytes()) else {
232 return Ok(false);
235 };
236 let digest = hash(message);
237 Ok(verifying.verify_prehash(&digest, &sig).is_ok())
238}
239
240pub struct SoftKeyStore<const N: usize> {
246 slots: [Option<Slot>; N],
247 next_handle: u32,
248}
249
250struct Slot {
251 handle: KeyHandle,
252 purpose: KeyPurpose,
253 key: SigningKey,
254}
255
256impl<const N: usize> Default for SoftKeyStore<N> {
257 fn default() -> Self {
258 Self::new()
259 }
260}
261
262impl<const N: usize> SoftKeyStore<N> {
263 #[must_use]
265 pub fn new() -> Self {
266 Self {
267 slots: [const { None }; N],
268 next_handle: 1,
269 }
270 }
271
272 #[must_use]
274 pub fn len(&self) -> usize {
275 self.slots.iter().flatten().count()
276 }
277
278 #[must_use]
280 pub fn is_empty(&self) -> bool {
281 self.len() == 0
282 }
283
284 fn insert(&mut self, purpose: KeyPurpose, key: SigningKey) -> Result<KeyHandle> {
285 let Some(slot) = self.slots.iter_mut().find(|s| s.is_none()) else {
286 return Err(Error::new(ErrorCode::NoSpace));
287 };
288 let handle = KeyHandle(self.next_handle);
289 self.next_handle = self.next_handle.saturating_add(1);
290 *slot = Some(Slot {
291 handle,
292 purpose,
293 key,
294 });
295 Ok(handle)
296 }
297
298 fn find(&self, handle: KeyHandle) -> Result<&Slot> {
299 self.slots
300 .iter()
301 .flatten()
302 .find(|s| s.handle == handle)
303 .ok_or(Error::new(ErrorCode::InvalidArgument))
304 }
305
306 pub fn purpose(&self, handle: KeyHandle) -> Result<KeyPurpose> {
308 Ok(self.find(handle)?.purpose)
309 }
310}
311
312impl<const N: usize> core::fmt::Debug for SoftKeyStore<N> {
313 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
314 write!(f, "SoftKeyStore({} keys)", self.len())
315 }
316}
317
318impl Drop for Slot {
319 fn drop(&mut self) {
320 }
323}
324
325impl<const N: usize> KeyStore for SoftKeyStore<N> {
326 fn generate(
327 &mut self,
328 purpose: KeyPurpose,
329 random: &[u8; GROUP_SIZE_BYTES],
330 ) -> Result<(KeyHandle, PublicKey)> {
331 let Ok(key) = SigningKey::from_slice(random) else {
336 return Err(Error::new(ErrorCode::InvalidArgument));
337 };
338 let public = public_of(&key)?;
339 let handle = self.insert(purpose, key)?;
340 Ok((handle, public))
341 }
342
343 fn import(
344 &mut self,
345 purpose: KeyPurpose,
346 secret: &[u8; GROUP_SIZE_BYTES],
347 ) -> Result<KeyHandle> {
348 let Ok(key) = SigningKey::from_slice(secret) else {
349 return Err(Error::new(ErrorCode::InvalidArgument));
350 };
351 self.insert(purpose, key)
352 }
353
354 fn public_key(&self, handle: KeyHandle) -> Result<PublicKey> {
355 public_of(&self.find(handle)?.key)
356 }
357
358 fn sign(&self, handle: KeyHandle, message: &[u8]) -> Result<Signature> {
359 let slot = self.find(handle)?;
360 let digest = hash(message);
361 let Ok(sig): core::result::Result<EcdsaSignature, _> = slot.key.sign_prehash(&digest)
362 else {
363 return Err(Error::new(ErrorCode::Platform));
364 };
365 Signature::from_slice(&sig.to_bytes())
366 }
367
368 fn ecdh(&self, handle: KeyHandle, peer: &PublicKey) -> Result<Secret<GROUP_SIZE_BYTES>> {
369 let slot = self.find(handle)?;
370 let Ok(peer_point) = p256::PublicKey::from_sec1_bytes(peer.as_bytes()) else {
371 return Err(Error::new(ErrorCode::InvalidArgument));
372 };
373 let secret = p256::ecdh::diffie_hellman(
374 p256::SecretKey::from(slot.key.clone()).to_nonzero_scalar(),
375 peer_point.as_affine(),
376 );
377 let mut out = Secret::<GROUP_SIZE_BYTES>::zeroed();
378 out.as_mut().copy_from_slice(secret.raw_secret_bytes());
379 Ok(out)
380 }
381
382 fn remove(&mut self, handle: KeyHandle) -> Result<()> {
383 let Some(slot) = self
384 .slots
385 .iter_mut()
386 .find(|s| s.as_ref().is_some_and(|s| s.handle == handle))
387 else {
388 return Err(Error::new(ErrorCode::InvalidArgument));
389 };
390 *slot = None;
391 Ok(())
392 }
393}
394
395fn public_of(key: &SigningKey) -> Result<PublicKey> {
396 let encoded = key.verifying_key().to_sec1_point(false);
397 let Some(bytes) = encoded.as_bytes().get(..PUBLIC_KEY_SIZE_BYTES) else {
398 return Err(Error::new(ErrorCode::Platform));
399 };
400 PublicKey::from_slice(bytes)
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 fn random() -> [u8; GROUP_SIZE_BYTES] {
410 use core::sync::atomic::{AtomicU32, Ordering};
411 static COUNTER: AtomicU32 = AtomicU32::new(1);
412 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
413 let mut out = [0x11u8; GROUP_SIZE_BYTES];
414 out[28..32].copy_from_slice(&n.to_be_bytes());
415 out
416 }
417
418 #[test]
419 fn sha256_matches_fips_180_4() {
420 assert_eq!(
422 hex::encode(hash(b"abc")),
423 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
424 );
425 assert_eq!(
426 hex::encode(hash(b"")),
427 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
428 );
429 }
430
431 #[test]
432 fn the_incremental_hasher_agrees_with_the_one_shot() {
433 let mut h = Hasher::new();
434 h.update(b"a");
435 h.update(b"b");
436 h.update(b"c");
437 assert_eq!(h.finish(), hash(b"abc"));
438 }
439
440 #[test]
441 fn hmac_matches_rfc_4231() {
442 let key = [0x0b; 20];
444 let mac = hmac(&key, b"Hi There").expect("hmac");
445 assert_eq!(
446 hex::encode(mac),
447 "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
448 );
449 }
450
451 #[test]
452 fn hkdf_matches_rfc_5869() {
453 let ikm = [0x0b; 22];
455 let salt: [u8; 13] = [
456 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c,
457 ];
458 let info: [u8; 10] = [0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9];
459 let mut out = [0u8; 42];
460 kdf(&ikm, &salt, &info, &mut out).expect("kdf");
461 assert_eq!(
462 hex::encode(out),
463 "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"
464 );
465 }
466
467 #[test]
468 fn pbkdf2_matches_rfc_7914() {
469 let mut out = [0u8; 32];
473 assert!(
474 pbkdf(b"passwd", b"0123456789abcdef", 1, &mut out).is_err(),
475 "below CRYPTO_PBKDF_ITERATIONS_MIN"
476 );
477 assert!(
478 pbkdf(b"passwd", b"0123456789abcdef", 1_000_000, &mut out).is_err(),
479 "above CRYPTO_PBKDF_ITERATIONS_MAX"
480 );
481 assert!(pbkdf(b"passwd", b"short", 1_000, &mut out).is_err());
483 assert!(pbkdf(b"passwd", &[0u8; 33], 1_000, &mut out).is_err());
484 assert!(pbkdf(b"passwd", &[0u8; 16], 1_000, &mut out).is_ok());
485 }
486
487 #[test]
488 fn aes_ccm_round_trips() {
489 let key = SymmetricKey::new([0x42; 16]);
490 let nonce = [0x11u8; AEAD_NONCE_LENGTH_BYTES];
491 let aad = b"header";
492 let mut buf = *b"the payload";
493 let original = buf;
494 let mut tag = [0u8; AEAD_MIC_LENGTH_BYTES];
495
496 aead_encrypt_in_place(&key, &nonce, aad, &mut buf, &mut tag).expect("encrypt");
497 assert_ne!(buf, original, "the payload was encrypted");
498
499 aead_decrypt_in_place(&key, &nonce, aad, &mut buf, &tag).expect("decrypt");
500 assert_eq!(buf, original);
501 }
502
503 #[test]
504 fn a_tampered_ciphertext_does_not_verify() {
505 let key = SymmetricKey::new([0x42; 16]);
506 let nonce = [0x11u8; AEAD_NONCE_LENGTH_BYTES];
507 let mut buf = *b"the payload";
508 let mut tag = [0u8; AEAD_MIC_LENGTH_BYTES];
509 aead_encrypt_in_place(&key, &nonce, b"h", &mut buf, &mut tag).expect("encrypt");
510
511 for byte in 0..buf.len() {
514 let mut broken = buf;
515 broken[byte] ^= 1;
516 assert!(
517 aead_decrypt_in_place(&key, &nonce, b"h", &mut broken, &tag).is_err(),
518 "flipped ciphertext byte {byte}"
519 );
520 }
521 for byte in 0..tag.len() {
522 let mut broken_tag = tag;
523 broken_tag[byte] ^= 1;
524 let mut copy = buf;
525 assert!(
526 aead_decrypt_in_place(&key, &nonce, b"h", &mut copy, &broken_tag).is_err(),
527 "flipped tag byte {byte}"
528 );
529 }
530 let mut copy = buf;
531 assert!(
532 aead_decrypt_in_place(&key, &nonce, b"H", &mut copy, &tag).is_err(),
533 "the associated data is authenticated too"
534 );
535 let mut copy = buf;
536 let mut other_nonce = nonce;
537 other_nonce[0] ^= 1;
538 assert!(
539 aead_decrypt_in_place(&key, &other_nonce, b"h", &mut copy, &tag).is_err(),
540 "so is the nonce"
541 );
542 }
543
544 #[test]
545 fn privacy_is_its_own_inverse() {
546 let key = SymmetricKey::new([0x7; 16]);
547 let nonce = [0x9u8; AEAD_NONCE_LENGTH_BYTES];
548 let original = *b"counter and node ids, obfuscated";
549 let mut buf = original;
550
551 privacy_xor(&key, &nonce, &mut buf).expect("obfuscate");
552 assert_ne!(buf, original);
553 privacy_xor(&key, &nonce, &mut buf).expect("deobfuscate");
554 assert_eq!(buf, original, "CTR mode xors the same keystream both ways");
555 }
556
557 #[test]
558 fn privacy_uses_the_counter_blocks_of_800_38c() {
559 let key = SymmetricKey::new([0x3; 16]);
562 let nonce = [0x5u8; AEAD_NONCE_LENGTH_BYTES];
563 let mut buf = [0u8; 32];
564 privacy_xor(&key, &nonce, &mut buf).expect("xor");
565
566 let cipher = <Aes128 as KeyInit>::new_from_slice(key.as_bytes()).expect("key");
567 for (index, chunk) in buf.chunks(16).enumerate() {
568 let mut block = [0u8; 16];
569 block[0] = 0x01;
570 block[1..14].copy_from_slice(&nonce);
571 block[14..16].copy_from_slice(&(index as u16).to_be_bytes());
572 cipher.encrypt_block((&mut block).into());
573 assert_eq!(chunk, &block[..chunk.len()], "keystream block {index}");
574 }
575 }
576
577 #[test]
578 fn the_privacy_key_is_derived_from_the_encryption_key() {
579 let encryption = SymmetricKey::new([0xAA; 16]);
581 let privacy = privacy_key(&encryption).expect("derive");
582 assert_ne!(privacy, encryption);
583 assert_eq!(privacy, privacy_key(&encryption).expect("derive"));
585 }
586
587 #[test]
588 fn signing_round_trips_through_verification() {
589 let mut store = SoftKeyStore::<4>::new();
590 let (handle, public) = store
591 .generate(KeyPurpose::Operational, &random())
592 .expect("generate");
593 let sig = store.sign(handle, b"attestation").expect("sign");
594
595 assert!(super::super::verify(&public, b"attestation", &sig).expect("verify"));
596 assert!(!super::super::verify(&public, b"attestatioN", &sig).expect("verify"));
597
598 let (_, other) = store
599 .generate(KeyPurpose::Operational, &random())
600 .expect("generate");
601 assert!(
602 !super::super::verify(&other, b"attestation", &sig).expect("verify"),
603 "another key's signature does not verify"
604 );
605 }
606
607 #[test]
608 fn ecdh_agrees_from_both_sides() {
609 let mut store = SoftKeyStore::<4>::new();
610 let (a, a_pub) = store
611 .generate(KeyPurpose::Ephemeral, &random())
612 .expect("generate");
613 let (b, b_pub) = store
614 .generate(KeyPurpose::Ephemeral, &random())
615 .expect("generate");
616
617 let ab = store.ecdh(a, &b_pub).expect("ecdh");
618 let ba = store.ecdh(b, &a_pub).expect("ecdh");
619 assert_eq!(ab, ba, "Diffie-Hellman is symmetric");
620 }
621
622 #[test]
623 fn a_public_key_is_an_uncompressed_sec1_point() {
624 let mut store = SoftKeyStore::<2>::new();
625 let (_, public) = store
626 .generate(KeyPurpose::Ephemeral, &random())
627 .expect("generate");
628 assert_eq!(public.as_bytes().len(), 65);
629 assert_eq!(public.as_bytes()[0], 0x04, "0x04 is 'uncompressed'");
630 }
631
632 #[test]
633 fn a_removed_key_is_gone() {
634 let mut store = SoftKeyStore::<2>::new();
635 let (handle, _) = store
636 .generate(KeyPurpose::Operational, &random())
637 .expect("generate");
638 assert_eq!(store.len(), 1);
639 store.remove(handle).expect("remove");
640 assert!(store.is_empty());
641 assert!(store.sign(handle, b"x").is_err(), "and cannot be used");
642 assert!(store.remove(handle).is_err(), "or removed twice");
643 }
644
645 #[test]
646 fn a_full_store_is_a_value_not_an_abort() {
647 let mut store = SoftKeyStore::<2>::new();
648 store
649 .generate(KeyPurpose::Operational, &random())
650 .expect("one");
651 store
652 .generate(KeyPurpose::Operational, &random())
653 .expect("two");
654 assert_eq!(
655 store
656 .generate(KeyPurpose::Operational, &random())
657 .unwrap_err()
658 .code(),
659 ErrorCode::NoSpace
660 );
661 }
662
663 #[test]
664 fn an_imported_key_signs_the_same_way() {
665 let secret = [
667 0xc9, 0xaf, 0xa9, 0xd8, 0x45, 0xba, 0x75, 0x16, 0x6b, 0x5c, 0x21, 0x57, 0x67, 0xb1,
668 0xd6, 0x93, 0x4e, 0x50, 0xc3, 0xdb, 0x36, 0xe8, 0x9b, 0x12, 0x7b, 0x8a, 0x62, 0x2b,
669 0x12, 0x0f, 0x67, 0x21,
670 ];
671 let mut store = SoftKeyStore::<2>::new();
672 let handle = store
673 .import(KeyPurpose::DeviceAttestation, &secret)
674 .expect("import");
675 let public = store.public_key(handle).expect("public");
676 let sig = store.sign(handle, b"msg").expect("sign");
677 assert!(super::super::verify(&public, b"msg", &sig).expect("verify"));
678 assert_eq!(
679 store.purpose(handle).expect("purpose"),
680 KeyPurpose::DeviceAttestation
681 );
682 }
683
684 #[test]
685 fn an_all_zero_private_key_is_refused() {
686 let mut store = SoftKeyStore::<2>::new();
688 assert!(store.import(KeyPurpose::Operational, &[0u8; 32]).is_err());
689 }
690}