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 fn fingerprint(public_keys: &[u8]) -> [u8; 16] {
402 let digest = <Sha256 as sha2::Digest>::digest(public_keys);
403 let mut fingerprint = [0_u8; 16];
404 fingerprint.copy_from_slice(digest.get(..16).unwrap_or_default());
405 fingerprint
406}
407
408pub fn secret_hash(secret: &[u8]) -> Vec<u8> {
411 <Sha256 as sha2::Digest>::digest(secret).to_vec()
412}
413
414pub fn registration_auth(secret: &[u8]) -> Zeroizing<[u8; 32]> {
419 registration_key(secret, b"teter-reg-v1 auth")
420}
421
422pub fn registration_binding(secret: &[u8]) -> Zeroizing<[u8; 32]> {
425 registration_key(secret, b"teter-reg-v1 bind")
426}
427
428fn registration_key(secret: &[u8], info: &[u8]) -> Zeroizing<[u8; 32]> {
429 let mut key = Zeroizing::new([0_u8; 32]);
430 if Hkdf::<Sha256>::new(None, secret)
432 .expand(info, key.as_mut())
433 .is_err()
434 {
435 key.fill(0);
436 }
437 key
438}
439
440pub fn binding_proof(secret: &[u8], machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
443 let key = registration_binding(secret);
444 let (prk, _) = Hkdf::<Sha256>::extract(
445 Some(key.as_ref()),
446 &teter_common::account::binding_bytes(machine_key, sealed_name),
447 );
448 prk.to_vec()
449}
450
451pub fn follow_rotations(
455 pinned: &[u8],
456 rotations: &[teter_common::account::KeyRotation],
457) -> Vec<u8> {
458 let mut keys = pinned.to_vec();
459 for rotation in rotations {
460 let signed = rotation.old_keys == keys
461 && rotation.new_keys.len() == 64
462 && keys.get(32..64).is_some_and(|signing| {
463 verify(
464 signing,
465 &teter_common::account::rotation_bytes(
466 &rotation.old_keys,
467 &rotation.new_keys,
468 rotation.at,
469 ),
470 &rotation.signature,
471 )
472 });
473 if signed {
474 keys.clone_from(&rotation.new_keys);
475 }
476 }
477 keys
478}
479
480pub fn rotation(
482 old: &AccountKeys,
483 new: &AccountKeys,
484 at: i64,
485) -> teter_common::account::KeyRotation {
486 let (old_keys, new_keys) = (old.public_keys(), new.public_keys());
487 teter_common::account::KeyRotation {
488 signature: old.sign(&teter_common::account::rotation_bytes(
489 &old_keys, &new_keys, at,
490 )),
491 old_keys,
492 new_keys,
493 at,
494 }
495}
496
497pub fn cert_holds(
502 account_public: &[u8],
503 id: &str,
504 machine_key: &[u8],
505 sealed_name: &[u8],
506 cert: &[u8],
507) -> bool {
508 machine_key.len() == 32
510 && account_public.get(32..64).is_some_and(|signing| {
511 verify(
512 signing,
513 &teter_common::account::cert_bytes(id, machine_key, sealed_name),
514 cert,
515 )
516 })
517}
518
519#[cfg(test)]
520mod tests {
521 use super::{
522 AccountError, AccountKeys, KdfParams, derive, follow_rotations, new_salt, rotation,
523 salt_blob,
524 };
525
526 #[test]
527 fn a_machine_follows_only_rotations_signed_from_the_keys_it_holds() {
528 let first = AccountKeys::generate().unwrap();
529 let second = AccountKeys::generate().unwrap();
530 let third = AccountKeys::generate().unwrap();
531 let stranger = AccountKeys::generate().unwrap();
532 let one = rotation(&first, &second, 10);
533 let two = rotation(&second, &third, 20);
534 assert_eq!(
536 follow_rotations(&first.public_keys(), &[one.clone(), two.clone()]),
537 third.public_keys()
538 );
539 assert_eq!(
540 follow_rotations(&second.public_keys(), &[one.clone(), two.clone()]),
541 third.public_keys()
542 );
543 let forged = rotation(&stranger, &stranger, 30);
545 let mut moved = one.clone();
546 moved.old_keys = stranger.public_keys();
547 let mut altered = one.clone();
548 altered.new_keys = stranger.public_keys();
549 let mut later = one.clone();
550 later.at += 1;
551 for skipped in [forged, moved, altered, later] {
552 assert_eq!(
553 follow_rotations(&first.public_keys(), &[skipped]),
554 first.public_keys()
555 );
556 }
557 assert_eq!(
559 follow_rotations(&stranger.public_keys(), &[one, two]),
560 stranger.public_keys()
561 );
562 }
563
564 use teter_common::account::{DEFAULT_KDF, MAX_KDF};
565
566 const CHEAP: KdfParams = DEFAULT_KDF;
569
570 #[test]
571 fn the_same_password_and_salt_give_the_same_keys_and_another_password_others() {
572 let salt = new_salt(CHEAP).unwrap();
573 let one = derive("correct horse", &salt).unwrap();
574 let again = derive("correct horse", &salt).unwrap();
575 let other = derive("correct horsf", &salt).unwrap();
576 assert_eq!(*one.auth_key, *again.auth_key);
577 assert_ne!(*one.auth_key, *other.auth_key);
578 assert_ne!(*one.auth_key, *one.wrap_key);
579 let elsewhere = derive("correct horse", &new_salt(CHEAP).unwrap()).unwrap();
581 assert_ne!(*one.auth_key, *elsewhere.auth_key);
582 }
583
584 #[test]
585 fn wrapped_keys_open_with_the_password_and_name_only() {
586 let salt = new_salt(CHEAP).unwrap();
587 let derived = derive("correct horse", &salt).unwrap();
588 let keys = AccountKeys::generate().unwrap();
589 let wrapped = keys.wrap(&derived, "ana").unwrap();
590 let public = keys.public_keys();
591 let opened = AccountKeys::unwrap(&derived, "ana", &wrapped, &public).unwrap();
592 assert_eq!(*opened.private_bytes(), *keys.private_bytes());
593 let wrong = derive("wrong", &salt).unwrap();
594 assert!(matches!(
595 AccountKeys::unwrap(&wrong, "ana", &wrapped, &public),
596 Err(AccountError::WrongKeys)
597 ));
598 assert!(matches!(
599 AccountKeys::unwrap(&derived, "bia", &wrapped, &public),
600 Err(AccountError::WrongKeys)
601 ));
602 let other = AccountKeys::generate().unwrap().public_keys();
604 assert!(AccountKeys::unwrap(&derived, "ana", &wrapped, &other).is_err());
605 assert_eq!(format!("{keys:?}"), "AccountKeys { .. }");
607 }
608
609 #[test]
610 fn a_salt_of_another_version_is_refused() {
611 let mut salt = new_salt(CHEAP).unwrap();
612 salt[0] = 9;
613 assert!(matches!(derive("x", &salt), Err(AccountError::BadSalt)));
614 assert!(matches!(
615 derive("x", &salt[..10]),
616 Err(AccountError::BadSalt)
617 ));
618 }
619
620 #[test]
621 fn a_salt_whose_cost_is_too_low_or_too_high_is_refused() {
622 let random = [7_u8; 16];
623 for params in [
624 KdfParams {
625 memory_kib: 8,
626 passes: 1,
627 lanes: 1,
628 },
629 KdfParams {
630 passes: 1,
631 ..DEFAULT_KDF
632 },
633 KdfParams {
634 memory_kib: MAX_KDF.memory_kib + 1,
635 ..DEFAULT_KDF
636 },
637 KdfParams {
638 passes: u32::MAX,
639 ..DEFAULT_KDF
640 },
641 KdfParams {
642 lanes: 0,
643 ..DEFAULT_KDF
644 },
645 ] {
646 assert!(
647 matches!(
648 derive("x", &salt_blob(params, &random)),
649 Err(AccountError::Kdf(_))
650 ),
651 "{params:?}"
652 );
653 }
654 }
655
656 #[test]
657 fn what_is_sealed_to_an_account_opens_with_its_keys_and_info_only() {
658 use super::{MachineKey, seal_to};
659
660 let keys = AccountKeys::generate().unwrap();
661 let sealed = seal_to(&keys.public_keys(), b"machine name", b"jupiter").unwrap();
662 assert_eq!(
663 keys.open_sealed(b"machine name", &sealed)
664 .unwrap()
665 .as_slice(),
666 b"jupiter"
667 );
668 assert!(keys.open_sealed(b"session key", &sealed).is_err());
669 let other = AccountKeys::generate().unwrap();
670 assert!(other.open_sealed(b"machine name", &sealed).is_err());
671 let machine = MachineKey::generate().unwrap();
673 let again = MachineKey::from_seed(machine.seed().as_ref()).unwrap();
674 assert_eq!(machine.public_key(), again.public_key());
675 assert_eq!(machine.sign(b"x").len(), 64);
676 assert_eq!(format!("{machine:?}"), "MachineKey { .. }");
677 }
678}