1use std::io;
16
17use chacha20poly1305::aead::{Aead, KeyInit, Payload};
18use chacha20poly1305::{XChaCha20Poly1305, XNonce};
19use hkdf::Hkdf;
20use sha2::Sha256;
21use zeroize::Zeroizing;
22
23pub use teter_common::account::{DEFAULT_KDF, KdfParams, salt_blob};
24use teter_common::account::{SALT_RANDOM_LEN, acceptable_kdf, parse_salt};
25
26const NONCE_LEN: usize = 24;
28
29#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum AccountError {
33 #[error("the account's salt is not one this version of teter reads")]
35 BadSalt,
36 #[error("deriving the account's keys: {0}")]
38 Kdf(String),
39 #[error("the account's keys do not open with this password")]
41 WrongKeys,
42 #[error("{0}")]
44 Refused(String),
45 #[error(transparent)]
47 Io(#[from] io::Error),
48}
49
50pub fn new_salt(params: KdfParams) -> io::Result<Vec<u8>> {
56 let mut random = [0_u8; SALT_RANDOM_LEN];
57 getrandom::fill(&mut random).map_err(io::Error::other)?;
58 Ok(salt_blob(params, &random))
59}
60
61pub struct Derived {
63 pub auth_key: Zeroizing<[u8; 32]>,
65 wrap_key: Zeroizing<[u8; 32]>,
67}
68
69pub fn derive(password: &str, salt: &[u8]) -> Result<Derived, AccountError> {
76 let (params, random) = parse_salt(salt).ok_or(AccountError::BadSalt)?;
77 if !acceptable_kdf(params) {
81 return Err(AccountError::Kdf(format!(
82 "the account's key derivation ({} KiB, {} passes, {} lanes) is outside what teter accepts",
83 params.memory_kib, params.passes, params.lanes
84 )));
85 }
86 let argon_params =
87 argon2::Params::new(params.memory_kib, params.passes, params.lanes, Some(32))
88 .map_err(|e| AccountError::Kdf(e.to_string()))?;
89 let argon = argon2::Argon2::new(
90 argon2::Algorithm::Argon2id,
91 argon2::Version::V0x13,
92 argon_params,
93 );
94 let mut master = Zeroizing::new([0_u8; 32]);
95 argon
96 .hash_password_into(password.as_bytes(), random, master.as_mut())
97 .map_err(|e| AccountError::Kdf(e.to_string()))?;
98 let hkdf =
99 Hkdf::<Sha256>::from_prk(master.as_ref()).map_err(|e| AccountError::Kdf(e.to_string()))?;
100 let key = |info: &[u8]| -> Result<Zeroizing<[u8; 32]>, AccountError> {
101 let mut key = Zeroizing::new([0_u8; 32]);
102 hkdf.expand(info, key.as_mut())
103 .map_err(|e| AccountError::Kdf(e.to_string()))?;
104 Ok(key)
105 };
106 Ok(Derived {
107 auth_key: key(b"teter-account-v1 auth")?,
108 wrap_key: key(b"teter-account-v1 wrap")?,
109 })
110}
111
112pub struct AccountKeys {
115 x25519: x25519_dalek::StaticSecret,
116 ed25519: ed25519_dalek::SigningKey,
117}
118
119impl std::fmt::Debug for AccountKeys {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 f.debug_struct("AccountKeys").finish_non_exhaustive()
122 }
123}
124
125impl AccountKeys {
126 pub fn generate() -> io::Result<Self> {
132 let mut bytes = Zeroizing::new([0_u8; 64]);
133 getrandom::fill(bytes.as_mut()).map_err(io::Error::other)?;
134 Ok(Self::from_private(&bytes))
135 }
136
137 fn from_private(bytes: &[u8; 64]) -> Self {
140 let (x, e) = bytes.split_at(32);
141 let mut x_bytes = [0_u8; 32];
142 x_bytes.copy_from_slice(x);
143 let mut e_bytes = [0_u8; 32];
144 e_bytes.copy_from_slice(e);
145 let keys = Self {
146 x25519: x25519_dalek::StaticSecret::from(x_bytes),
147 ed25519: ed25519_dalek::SigningKey::from_bytes(&e_bytes),
148 };
149 zeroize::Zeroize::zeroize(&mut x_bytes);
150 zeroize::Zeroize::zeroize(&mut e_bytes);
151 keys
152 }
153
154 pub fn private_bytes(&self) -> Zeroizing<[u8; 64]> {
156 let mut bytes = Zeroizing::new([0_u8; 64]);
157 let (x, e) = bytes.split_at_mut(32);
158 x.copy_from_slice(self.x25519.as_bytes());
159 e.copy_from_slice(self.ed25519.as_bytes());
160 bytes
161 }
162
163 pub fn from_private_bytes(bytes: &[u8]) -> Option<Self> {
165 let bytes: &[u8; 64] = bytes.try_into().ok()?;
166 Some(Self::from_private(bytes))
167 }
168
169 pub fn public_keys(&self) -> Vec<u8> {
171 let mut public = Vec::with_capacity(64);
172 public.extend_from_slice(x25519_dalek::PublicKey::from(&self.x25519).as_bytes());
173 public.extend_from_slice(self.ed25519.verifying_key().as_bytes());
174 public
175 }
176
177 pub fn wrap(&self, derived: &Derived, name: &str) -> io::Result<Vec<u8>> {
184 let mut nonce = [0_u8; NONCE_LEN];
185 getrandom::fill(&mut nonce).map_err(io::Error::other)?;
186 let cipher = XChaCha20Poly1305::new(derived.wrap_key.as_ref().into());
187 let private = self.private_bytes();
188 let sealed = cipher
189 .encrypt(
190 XNonce::from_slice(&nonce),
191 Payload {
192 msg: private.as_ref(),
193 aad: &wrap_aad(name),
194 },
195 )
196 .map_err(|_opaque| io::Error::other("wrapping the account's keys failed"))?;
197 let mut wrapped = nonce.to_vec();
198 wrapped.extend_from_slice(&sealed);
199 Ok(wrapped)
200 }
201
202 pub fn unwrap(
209 derived: &Derived,
210 name: &str,
211 wrapped: &[u8],
212 public_keys: &[u8],
213 ) -> Result<Self, AccountError> {
214 let (nonce, sealed) = wrapped
215 .split_at_checked(NONCE_LEN)
216 .ok_or(AccountError::WrongKeys)?;
217 let cipher = XChaCha20Poly1305::new(derived.wrap_key.as_ref().into());
218 let private = Zeroizing::new(
219 cipher
220 .decrypt(
221 XNonce::from_slice(nonce),
222 Payload {
223 msg: sealed,
224 aad: &wrap_aad(name),
225 },
226 )
227 .map_err(|_opaque| AccountError::WrongKeys)?,
228 );
229 let keys = Self::from_private_bytes(&private).ok_or(AccountError::WrongKeys)?;
230 if keys.public_keys() != public_keys {
231 return Err(AccountError::WrongKeys);
232 }
233 Ok(keys)
234 }
235}
236
237impl AccountKeys {
238 pub fn sign(&self, message: &[u8]) -> Vec<u8> {
240 use ed25519_dalek::Signer as _;
241 self.ed25519.sign(message).to_bytes().to_vec()
242 }
243
244 pub fn open_sealed(
251 &self,
252 info: &[u8],
253 sealed: &[u8],
254 ) -> Result<Zeroizing<Vec<u8>>, AccountError> {
255 let (ephemeral, rest) = sealed.split_at_checked(32).ok_or(AccountError::WrongKeys)?;
256 let (nonce, ciphertext) = rest
257 .split_at_checked(NONCE_LEN)
258 .ok_or(AccountError::WrongKeys)?;
259 let ephemeral: [u8; 32] = ephemeral
260 .try_into()
261 .map_err(|_opaque| AccountError::WrongKeys)?;
262 let shared = self
263 .x25519
264 .diffie_hellman(&x25519_dalek::PublicKey::from(ephemeral));
265 let recipient = *x25519_dalek::PublicKey::from(&self.x25519).as_bytes();
266 let key = sealing_key(shared.as_bytes(), &ephemeral, &recipient, info)?;
267 XChaCha20Poly1305::new(key.as_ref().into())
268 .decrypt(XNonce::from_slice(nonce), ciphertext)
269 .map(Zeroizing::new)
270 .map_err(|_opaque| AccountError::WrongKeys)
271 }
272}
273
274fn wrap_aad(name: &str) -> Vec<u8> {
276 let mut aad = b"teter-account-v1 keys ".to_vec();
277 aad.extend_from_slice(name.as_bytes());
278 aad
279}
280
281pub fn seal_to(public_keys: &[u8], info: &[u8], plaintext: &[u8]) -> io::Result<Vec<u8>> {
292 let recipient: [u8; 32] = public_keys
293 .get(..32)
294 .and_then(|key| key.try_into().ok())
295 .ok_or_else(|| io::Error::other("the account's public keys hold no X25519 key"))?;
296 let mut ephemeral = Zeroizing::new([0_u8; 32]);
297 getrandom::fill(ephemeral.as_mut()).map_err(io::Error::other)?;
298 let ephemeral = x25519_dalek::StaticSecret::from(*ephemeral);
299 let ephemeral_public = x25519_dalek::PublicKey::from(&ephemeral);
300 let shared = ephemeral.diffie_hellman(&x25519_dalek::PublicKey::from(recipient));
301 let key = sealing_key(
302 shared.as_bytes(),
303 ephemeral_public.as_bytes(),
304 &recipient,
305 info,
306 )?;
307 let mut nonce = [0_u8; NONCE_LEN];
308 getrandom::fill(&mut nonce).map_err(io::Error::other)?;
309 let sealed = XChaCha20Poly1305::new(key.as_ref().into())
310 .encrypt(XNonce::from_slice(&nonce), plaintext)
311 .map_err(|_opaque| io::Error::other("sealing failed"))?;
312 let mut out = ephemeral_public.as_bytes().to_vec();
313 out.extend_from_slice(&nonce);
314 out.extend_from_slice(&sealed);
315 Ok(out)
316}
317
318fn sealing_key(
320 shared: &[u8; 32],
321 ephemeral: &[u8; 32],
322 recipient: &[u8; 32],
323 info: &[u8],
324) -> io::Result<Zeroizing<[u8; 32]>> {
325 let mut salt = ephemeral.to_vec();
326 salt.extend_from_slice(recipient);
327 let hkdf = Hkdf::<Sha256>::new(Some(&salt), shared);
328 let mut full_info = b"teter-seal-v1 ".to_vec();
329 full_info.extend_from_slice(info);
330 let mut key = Zeroizing::new([0_u8; 32]);
331 hkdf.expand(&full_info, key.as_mut())
332 .map_err(|_opaque| io::Error::other("deriving the sealing key failed"))?;
333 Ok(key)
334}
335
336pub fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> bool {
339 let (Ok(key), Ok(signature)) = (
340 <&[u8; 32]>::try_from(public_key),
341 <&[u8; 64]>::try_from(signature),
342 ) else {
343 return false;
344 };
345 let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(key) else {
346 return false;
347 };
348 key.verify_strict(message, &ed25519_dalek::Signature::from_bytes(signature))
349 .is_ok()
350}
351
352pub struct MachineKey(ed25519_dalek::SigningKey);
355
356impl std::fmt::Debug for MachineKey {
357 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358 f.debug_struct("MachineKey").finish_non_exhaustive()
359 }
360}
361
362impl MachineKey {
363 pub fn generate() -> io::Result<Self> {
369 let mut seed = Zeroizing::new([0_u8; 32]);
370 getrandom::fill(seed.as_mut()).map_err(io::Error::other)?;
371 Ok(Self(ed25519_dalek::SigningKey::from_bytes(&seed)))
372 }
373
374 pub fn from_seed(seed: &[u8]) -> Option<Self> {
376 let seed: &[u8; 32] = seed.try_into().ok()?;
377 Some(Self(ed25519_dalek::SigningKey::from_bytes(seed)))
378 }
379
380 pub fn seed(&self) -> Zeroizing<[u8; 32]> {
382 Zeroizing::new(*self.0.as_bytes())
383 }
384
385 pub fn public_key(&self) -> Vec<u8> {
387 self.0.verifying_key().as_bytes().to_vec()
388 }
389
390 pub fn sign(&self, message: &[u8]) -> Vec<u8> {
392 ed25519_dalek::Signer::sign(&self.0, message)
393 .to_bytes()
394 .to_vec()
395 }
396}
397
398pub type DeviceKey = MachineKey;
402
403pub fn prove(
410 device: &DeviceKey,
411 request: &teter_common::account::AccountRequest,
412 at: i64,
413) -> io::Result<teter_common::account::AccountRequest> {
414 let request = serde_json::to_string(request).map_err(io::Error::other)?;
415 let mut nonce = vec![0_u8; teter_common::account::PROOF_NONCE_LEN];
416 getrandom::fill(&mut nonce).map_err(io::Error::other)?;
417 let signature = device.sign(&teter_common::account::proof_bytes(&request, at, &nonce));
418 Ok(teter_common::account::AccountRequest::Proven {
419 request,
420 at,
421 nonce,
422 signature,
423 })
424}
425
426pub fn fingerprint(public_keys: &[u8]) -> [u8; 16] {
430 let digest = <Sha256 as sha2::Digest>::digest(public_keys);
431 let mut fingerprint = [0_u8; 16];
432 fingerprint.copy_from_slice(digest.get(..16).unwrap_or_default());
433 fingerprint
434}
435
436pub fn secret_hash(secret: &[u8]) -> Vec<u8> {
439 <Sha256 as sha2::Digest>::digest(secret).to_vec()
440}
441
442pub fn registration_auth(secret: &[u8]) -> Zeroizing<[u8; 32]> {
447 registration_key(secret, b"teter-reg-v1 auth")
448}
449
450pub fn registration_binding(secret: &[u8]) -> Zeroizing<[u8; 32]> {
453 registration_key(secret, b"teter-reg-v1 bind")
454}
455
456fn registration_key(secret: &[u8], info: &[u8]) -> Zeroizing<[u8; 32]> {
457 let mut key = Zeroizing::new([0_u8; 32]);
458 if Hkdf::<Sha256>::new(None, secret)
460 .expand(info, key.as_mut())
461 .is_err()
462 {
463 key.fill(0);
464 }
465 key
466}
467
468pub fn binding_proof(secret: &[u8], machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
471 let key = registration_binding(secret);
472 let (prk, _) = Hkdf::<Sha256>::extract(
473 Some(key.as_ref()),
474 &teter_common::account::binding_bytes(machine_key, sealed_name),
475 );
476 prk.to_vec()
477}
478
479pub fn follow_rotations(
483 pinned: &[u8],
484 rotations: &[teter_common::account::KeyRotation],
485) -> Vec<u8> {
486 let mut keys = pinned.to_vec();
487 for rotation in rotations {
488 let signed = rotation.old_keys == keys
489 && rotation.new_keys.len() == 64
490 && keys.get(32..64).is_some_and(|signing| {
491 verify(
492 signing,
493 &teter_common::account::rotation_bytes(
494 &rotation.old_keys,
495 &rotation.new_keys,
496 rotation.at,
497 ),
498 &rotation.signature,
499 )
500 });
501 if signed {
502 keys.clone_from(&rotation.new_keys);
503 }
504 }
505 keys
506}
507
508pub fn rotation(
510 old: &AccountKeys,
511 new: &AccountKeys,
512 at: i64,
513) -> teter_common::account::KeyRotation {
514 let (old_keys, new_keys) = (old.public_keys(), new.public_keys());
515 teter_common::account::KeyRotation {
516 signature: old.sign(&teter_common::account::rotation_bytes(
517 &old_keys, &new_keys, at,
518 )),
519 old_keys,
520 new_keys,
521 at,
522 }
523}
524
525pub fn cert_holds(
530 account_public: &[u8],
531 id: &str,
532 machine_key: &[u8],
533 sealed_name: &[u8],
534 cert: &[u8],
535) -> bool {
536 machine_key.len() == 32
538 && account_public.get(32..64).is_some_and(|signing| {
539 verify(
540 signing,
541 &teter_common::account::cert_bytes(id, machine_key, sealed_name),
542 cert,
543 )
544 })
545}
546
547#[cfg(test)]
548mod tests {
549 use super::{
550 AccountError, AccountKeys, KdfParams, derive, follow_rotations, new_salt, rotation,
551 salt_blob,
552 };
553
554 #[test]
555 fn a_machine_follows_only_rotations_signed_from_the_keys_it_holds() {
556 let first = AccountKeys::generate().unwrap();
557 let second = AccountKeys::generate().unwrap();
558 let third = AccountKeys::generate().unwrap();
559 let stranger = AccountKeys::generate().unwrap();
560 let one = rotation(&first, &second, 10);
561 let two = rotation(&second, &third, 20);
562 assert_eq!(
564 follow_rotations(&first.public_keys(), &[one.clone(), two.clone()]),
565 third.public_keys()
566 );
567 assert_eq!(
568 follow_rotations(&second.public_keys(), &[one.clone(), two.clone()]),
569 third.public_keys()
570 );
571 let forged = rotation(&stranger, &stranger, 30);
573 let mut moved = one.clone();
574 moved.old_keys = stranger.public_keys();
575 let mut altered = one.clone();
576 altered.new_keys = stranger.public_keys();
577 let mut later = one.clone();
578 later.at += 1;
579 for skipped in [forged, moved, altered, later] {
580 assert_eq!(
581 follow_rotations(&first.public_keys(), &[skipped]),
582 first.public_keys()
583 );
584 }
585 assert_eq!(
587 follow_rotations(&stranger.public_keys(), &[one, two]),
588 stranger.public_keys()
589 );
590 }
591
592 use teter_common::account::{DEFAULT_KDF, MAX_KDF};
593
594 const CHEAP: KdfParams = DEFAULT_KDF;
597
598 #[test]
599 fn the_same_password_and_salt_give_the_same_keys_and_another_password_others() {
600 let salt = new_salt(CHEAP).unwrap();
601 let one = derive("correct horse", &salt).unwrap();
602 let again = derive("correct horse", &salt).unwrap();
603 let other = derive("correct horsf", &salt).unwrap();
604 assert_eq!(*one.auth_key, *again.auth_key);
605 assert_ne!(*one.auth_key, *other.auth_key);
606 assert_ne!(*one.auth_key, *one.wrap_key);
607 let elsewhere = derive("correct horse", &new_salt(CHEAP).unwrap()).unwrap();
609 assert_ne!(*one.auth_key, *elsewhere.auth_key);
610 }
611
612 #[test]
613 fn wrapped_keys_open_with_the_password_and_name_only() {
614 let salt = new_salt(CHEAP).unwrap();
615 let derived = derive("correct horse", &salt).unwrap();
616 let keys = AccountKeys::generate().unwrap();
617 let wrapped = keys.wrap(&derived, "ana").unwrap();
618 let public = keys.public_keys();
619 let opened = AccountKeys::unwrap(&derived, "ana", &wrapped, &public).unwrap();
620 assert_eq!(*opened.private_bytes(), *keys.private_bytes());
621 let wrong = derive("wrong", &salt).unwrap();
622 assert!(matches!(
623 AccountKeys::unwrap(&wrong, "ana", &wrapped, &public),
624 Err(AccountError::WrongKeys)
625 ));
626 assert!(matches!(
627 AccountKeys::unwrap(&derived, "bia", &wrapped, &public),
628 Err(AccountError::WrongKeys)
629 ));
630 let other = AccountKeys::generate().unwrap().public_keys();
632 assert!(AccountKeys::unwrap(&derived, "ana", &wrapped, &other).is_err());
633 assert_eq!(format!("{keys:?}"), "AccountKeys { .. }");
635 }
636
637 #[test]
638 fn a_salt_of_another_version_is_refused() {
639 let mut salt = new_salt(CHEAP).unwrap();
640 salt[0] = 9;
641 assert!(matches!(derive("x", &salt), Err(AccountError::BadSalt)));
642 assert!(matches!(
643 derive("x", &salt[..10]),
644 Err(AccountError::BadSalt)
645 ));
646 }
647
648 #[test]
649 fn a_salt_whose_cost_is_too_low_or_too_high_is_refused() {
650 let random = [7_u8; 16];
651 for params in [
652 KdfParams {
653 memory_kib: 8,
654 passes: 1,
655 lanes: 1,
656 },
657 KdfParams {
658 passes: 1,
659 ..DEFAULT_KDF
660 },
661 KdfParams {
662 memory_kib: MAX_KDF.memory_kib + 1,
663 ..DEFAULT_KDF
664 },
665 KdfParams {
666 passes: u32::MAX,
667 ..DEFAULT_KDF
668 },
669 KdfParams {
670 lanes: 0,
671 ..DEFAULT_KDF
672 },
673 ] {
674 assert!(
675 matches!(
676 derive("x", &salt_blob(params, &random)),
677 Err(AccountError::Kdf(_))
678 ),
679 "{params:?}"
680 );
681 }
682 }
683
684 #[test]
685 fn what_is_sealed_to_an_account_opens_with_its_keys_and_info_only() {
686 use super::{MachineKey, seal_to};
687
688 let keys = AccountKeys::generate().unwrap();
689 let sealed = seal_to(&keys.public_keys(), b"machine name", b"jupiter").unwrap();
690 assert_eq!(
691 keys.open_sealed(b"machine name", &sealed)
692 .unwrap()
693 .as_slice(),
694 b"jupiter"
695 );
696 assert!(keys.open_sealed(b"session key", &sealed).is_err());
697 let other = AccountKeys::generate().unwrap();
698 assert!(other.open_sealed(b"machine name", &sealed).is_err());
699 let machine = MachineKey::generate().unwrap();
701 let again = MachineKey::from_seed(machine.seed().as_ref()).unwrap();
702 assert_eq!(machine.public_key(), again.public_key());
703 assert_eq!(machine.sign(b"x").len(), 64);
704 assert_eq!(format!("{machine:?}"), "MachineKey { .. }");
705 }
706
707 #[test]
708 fn a_proven_request_carries_the_request_and_verifies_under_the_device_key() {
709 use super::{DeviceKey, prove, verify};
710 use teter_common::account::{AccountRequest, proof_bytes};
711
712 let device = DeviceKey::generate().unwrap();
713 let inner = AccountRequest::MachineList {
714 login: "tok".into(),
715 };
716 let AccountRequest::Proven {
717 request,
718 at,
719 nonce,
720 signature,
721 } = prove(&device, &inner, 42).unwrap()
722 else {
723 panic!("not proven");
724 };
725 assert_eq!(at, 42);
726 assert_eq!(
727 serde_json::from_str::<AccountRequest>(&request).unwrap(),
728 inner
729 );
730 let bytes = proof_bytes(&request, at, &nonce);
731 assert!(verify(&device.public_key(), &bytes, &signature));
732 let other = DeviceKey::generate().unwrap();
733 assert!(!verify(&other.public_key(), &bytes, &signature));
734 let AccountRequest::Proven { nonce: again, .. } = prove(&device, &inner, 42).unwrap()
736 else {
737 panic!("not proven");
738 };
739 assert_ne!(nonce, again);
740 }
741}