Skip to main content

teter_core/
account.rs

1//! The client side of accounts: the keys derived from the password, the
2//! account's key pairs, their wrapping, and the requests to the relay's
3//! account service (`teter_common::account`).
4//!
5//! From the password and the account's salt, Argon2id gives a master key;
6//! HKDF-SHA256 over it gives an auth key (presented to the relay, which keeps
7//! only its hash) and a wrapping key (which never leaves the client). The
8//! account has two key pairs: X25519, to receive session keys sealed to it
9//! (#87), and Ed25519, to sign commands to its machines (#88). Their private
10//! halves reach the relay only wrapped, with XChaCha20-Poly1305 under the
11//! wrapping key, bound to the account's name.
12//!
13//! No I/O here: the requests to the relay are `teter_client::account`'s.
14
15use 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
26/// The nonce of a wrapping, before its ciphertext.
27const NONCE_LEN: usize = 24;
28
29/// What can go wrong with an account's keys.
30#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum AccountError {
33    /// A salt this build cannot read (another version, or damaged).
34    #[error("the account's salt is not one this version of teter reads")]
35    BadSalt,
36    /// The key derivation failed (parameters out of range).
37    #[error("deriving the account's keys: {0}")]
38    Kdf(String),
39    /// The wrapped keys do not open: another password, or altered.
40    #[error("the account's keys do not open with this password")]
41    WrongKeys,
42    /// The relay's account service refused, or answered out of turn.
43    #[error("{0}")]
44    Refused(String),
45    /// The connection, or the system's random source, failed.
46    #[error(transparent)]
47    Io(#[from] io::Error),
48}
49
50/// A new salt for `params`, with fresh random bytes.
51///
52/// # Errors
53///
54/// When the system's random source fails.
55pub 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
61/// The two keys derived from the password.
62pub struct Derived {
63    /// Presented to the relay, which keeps its hash.
64    pub auth_key: Zeroizing<[u8; 32]>,
65    /// Wraps the account's private keys; never leaves the client.
66    wrap_key: Zeroizing<[u8; 32]>,
67}
68
69/// Derives the auth and wrapping keys from `password` and the account's
70/// `salt`.
71///
72/// # Errors
73///
74/// A salt this build cannot read, or parameters Argon2 refuses.
75pub fn derive(password: &str, salt: &[u8]) -> Result<Derived, AccountError> {
76    let (params, random) = parse_salt(salt).ok_or(AccountError::BadSalt)?;
77    // The relay chose these (it is not trusted): too cheap would make the
78    // auth key a cheap way to the password, too dear would exhaust the
79    // client.
80    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
112/// The account's key pairs: X25519 (to receive sealed session keys) and
113/// Ed25519 (to sign commands). Its `Debug` hides the private halves.
114pub 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    /// New key pairs.
127    ///
128    /// # Errors
129    ///
130    /// When the system's random source fails.
131    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    /// The key pairs from their private halves (X25519, then the Ed25519
138    /// seed, 32 bytes each).
139    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    /// The private halves, as [`AccountKeys::from_private`] takes them.
155    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    /// The key pairs from their private halves, if `bytes` holds 64.
164    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    /// The public halves: X25519, then Ed25519, 32 bytes each.
170    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    /// The private halves wrapped under `derived`'s wrapping key, bound to
178    /// account `name`: a nonce, then the ciphertext.
179    ///
180    /// # Errors
181    ///
182    /// When the system's random source fails.
183    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    /// The key pairs `wrapped` holds, for account `name`, under `derived`'s
203    /// wrapping key; they must match `public_keys`.
204    ///
205    /// # Errors
206    ///
207    /// [`AccountError::WrongKeys`] when they do not open or do not match.
208    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    /// The account's Ed25519 signature of `message` (#88).
239    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    /// What [`seal_to`] sealed to this account, for `info`.
245    ///
246    /// # Errors
247    ///
248    /// [`AccountError::WrongKeys`] when it does not open: sealed to another
249    /// account, for another `info`, or altered.
250    pub fn open_sealed(
251        &self,
252        info: &[u8],
253        sealed: &[u8],
254    ) -> Result<Zeroizing<Vec<u8>>, AccountError> {
255        open_with(&self.x25519, info, sealed)
256    }
257}
258
259/// Opens what [`seal_to`] sealed to `secret`'s public key with `info`.
260fn open_with(
261    secret: &x25519_dalek::StaticSecret,
262    info: &[u8],
263    sealed: &[u8],
264) -> Result<Zeroizing<Vec<u8>>, AccountError> {
265    let (ephemeral, rest) = sealed.split_at_checked(32).ok_or(AccountError::WrongKeys)?;
266    let (nonce, ciphertext) = rest
267        .split_at_checked(NONCE_LEN)
268        .ok_or(AccountError::WrongKeys)?;
269    let ephemeral: [u8; 32] = ephemeral
270        .try_into()
271        .map_err(|_opaque| AccountError::WrongKeys)?;
272    let shared = secret.diffie_hellman(&x25519_dalek::PublicKey::from(ephemeral));
273    let recipient = *x25519_dalek::PublicKey::from(secret).as_bytes();
274    let key = sealing_key(shared.as_bytes(), &ephemeral, &recipient, info)?;
275    XChaCha20Poly1305::new(key.as_ref().into())
276        .decrypt(XNonce::from_slice(nonce), ciphertext)
277        .map(Zeroizing::new)
278        .map_err(|_opaque| AccountError::WrongKeys)
279}
280
281/// What a wrapping is bound to.
282fn wrap_aad(name: &str) -> Vec<u8> {
283    let mut aad = b"teter-account-v1 keys ".to_vec();
284    aad.extend_from_slice(name.as_bytes());
285    aad
286}
287
288/// Seals `plaintext` to the account whose public keys are `public_keys`
289/// (its X25519 key, the first 32 bytes), for `info` (what it is, bound in
290/// the key): an ephemeral X25519 key agreed with the account's, HKDF-SHA256
291/// over the shared secret, XChaCha20-Poly1305. Only the account's private
292/// key opens it ([`AccountKeys::open_sealed`]). The result: the ephemeral
293/// public key, the nonce, the ciphertext.
294///
295/// # Errors
296///
297/// Public keys that hold no X25519 key, or a random source that fails.
298pub fn seal_to(public_keys: &[u8], info: &[u8], plaintext: &[u8]) -> io::Result<Vec<u8>> {
299    let recipient: [u8; 32] = public_keys
300        .get(..32)
301        .and_then(|key| key.try_into().ok())
302        .ok_or_else(|| io::Error::other("the account's public keys hold no X25519 key"))?;
303    let mut ephemeral = Zeroizing::new([0_u8; 32]);
304    getrandom::fill(ephemeral.as_mut()).map_err(io::Error::other)?;
305    let ephemeral = x25519_dalek::StaticSecret::from(*ephemeral);
306    let ephemeral_public = x25519_dalek::PublicKey::from(&ephemeral);
307    let shared = ephemeral.diffie_hellman(&x25519_dalek::PublicKey::from(recipient));
308    let key = sealing_key(
309        shared.as_bytes(),
310        ephemeral_public.as_bytes(),
311        &recipient,
312        info,
313    )?;
314    let mut nonce = [0_u8; NONCE_LEN];
315    getrandom::fill(&mut nonce).map_err(io::Error::other)?;
316    let sealed = XChaCha20Poly1305::new(key.as_ref().into())
317        .encrypt(XNonce::from_slice(&nonce), plaintext)
318        .map_err(|_opaque| io::Error::other("sealing failed"))?;
319    let mut out = ephemeral_public.as_bytes().to_vec();
320    out.extend_from_slice(&nonce);
321    out.extend_from_slice(&sealed);
322    Ok(out)
323}
324
325/// The key a sealing to `recipient` from `ephemeral` uses, for `info`.
326fn sealing_key(
327    shared: &[u8; 32],
328    ephemeral: &[u8; 32],
329    recipient: &[u8; 32],
330    info: &[u8],
331) -> io::Result<Zeroizing<[u8; 32]>> {
332    let mut salt = ephemeral.to_vec();
333    salt.extend_from_slice(recipient);
334    let hkdf = Hkdf::<Sha256>::new(Some(&salt), shared);
335    let mut full_info = b"teter-seal-v1 ".to_vec();
336    full_info.extend_from_slice(info);
337    let mut key = Zeroizing::new([0_u8; 32]);
338    hkdf.expand(&full_info, key.as_mut())
339        .map_err(|_opaque| io::Error::other("deriving the sealing key failed"))?;
340    Ok(key)
341}
342
343/// Whether `signature` is the Ed25519 signature of `message` by
344/// `public_key` (32 bytes).
345pub fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> bool {
346    let (Ok(key), Ok(signature)) = (
347        <&[u8; 32]>::try_from(public_key),
348        <&[u8; 64]>::try_from(signature),
349    ) else {
350        return false;
351    };
352    let Ok(key) = ed25519_dalek::VerifyingKey::from_bytes(key) else {
353        return false;
354    };
355    key.verify_strict(message, &ed25519_dalek::Signature::from_bytes(signature))
356        .is_ok()
357}
358
359/// A machine's key pair (Ed25519): it authenticates the machine to the
360/// relay. Its `Debug` hides the private half.
361pub struct MachineKey(ed25519_dalek::SigningKey);
362
363impl std::fmt::Debug for MachineKey {
364    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
365        f.debug_struct("MachineKey").finish_non_exhaustive()
366    }
367}
368
369impl MachineKey {
370    /// A new key pair.
371    ///
372    /// # Errors
373    ///
374    /// When the system's random source fails.
375    pub fn generate() -> io::Result<Self> {
376        let mut seed = Zeroizing::new([0_u8; 32]);
377        getrandom::fill(seed.as_mut()).map_err(io::Error::other)?;
378        Ok(Self(ed25519_dalek::SigningKey::from_bytes(&seed)))
379    }
380
381    /// The key pair from its 32-byte private seed, if `seed` holds 32 bytes.
382    pub fn from_seed(seed: &[u8]) -> Option<Self> {
383        let seed: &[u8; 32] = seed.try_into().ok()?;
384        Some(Self(ed25519_dalek::SigningKey::from_bytes(seed)))
385    }
386
387    /// The private seed.
388    pub fn seed(&self) -> Zeroizing<[u8; 32]> {
389        Zeroizing::new(*self.0.as_bytes())
390    }
391
392    /// The public key, 32 bytes.
393    pub fn public_key(&self) -> Vec<u8> {
394        self.0.verifying_key().as_bytes().to_vec()
395    }
396
397    /// The signature of `message`, 64 bytes.
398    pub fn sign(&self, message: &[u8]) -> Vec<u8> {
399        ed25519_dalek::Signer::sign(&self.0, message)
400            .to_bytes()
401            .to_vec()
402    }
403}
404
405/// A device's key pair (#158), the same kind as a machine's: each login is
406/// bound to the public half, and every request with its token is signed
407/// ([`prove`]).
408pub type DeviceKey = MachineKey;
409
410/// `request` (one with a login token), signed by `device` at `at` (Unix
411/// seconds) with a fresh nonce: what the relay takes for it (#158).
412///
413/// # Errors
414///
415/// When the request does not serialize or the random source fails.
416pub fn prove(
417    device: &DeviceKey,
418    request: &teter_common::account::AccountRequest,
419    at: i64,
420) -> io::Result<teter_common::account::AccountRequest> {
421    let request = serde_json::to_string(request).map_err(io::Error::other)?;
422    let mut nonce = vec![0_u8; teter_common::account::PROOF_NONCE_LEN];
423    getrandom::fill(&mut nonce).map_err(io::Error::other)?;
424    let signature = device.sign(&teter_common::account::proof_bytes(&request, at, &nonce));
425    Ok(teter_common::account::AccountRequest::Proven {
426        request,
427        at,
428        nonce,
429        signature,
430    })
431}
432
433/// The fingerprint of an account's public keys: the first 16 bytes of their
434/// SHA-256. A registration token carries it, and the machine checks the
435/// keys the relay gives it against it (#86).
436pub fn fingerprint(public_keys: &[u8]) -> [u8; 16] {
437    let digest = <Sha256 as sha2::Digest>::digest(public_keys);
438    let mut fingerprint = [0_u8; 16];
439    fingerprint.copy_from_slice(digest.get(..16).unwrap_or_default());
440    fingerprint
441}
442
443/// The hash of a registration token's enrollment secret, which is all the
444/// relay keeps of it.
445pub fn secret_hash(secret: &[u8]) -> Vec<u8> {
446    <Sha256 as sha2::Digest>::digest(secret).to_vec()
447}
448
449/// What of a registration token's secret goes to the relay (#133): a key
450/// derived from it, so the relay never learns the [`registration_binding`]
451/// key, which proves to the account's device that the machine held the
452/// token.
453pub fn registration_auth(secret: &[u8]) -> Zeroizing<[u8; 32]> {
454    registration_key(secret, b"teter-reg-v1 auth")
455}
456
457/// The key a machine proves with that it held the registration token
458/// (#133); never sent anywhere.
459pub fn registration_binding(secret: &[u8]) -> Zeroizing<[u8; 32]> {
460    registration_key(secret, b"teter-reg-v1 bind")
461}
462
463fn registration_key(secret: &[u8], info: &[u8]) -> Zeroizing<[u8; 32]> {
464    let mut key = Zeroizing::new([0_u8; 32]);
465    // 32 bytes is always a valid HKDF-SHA256 length: the error never comes.
466    if Hkdf::<Sha256>::new(None, secret)
467        .expand(info, key.as_mut())
468        .is_err()
469    {
470        key.fill(0);
471    }
472    key
473}
474
475/// The machine's proof it held the token whose secret is `secret`, for its
476/// key and sealed name: HMAC-SHA256 (HKDF-Extract) under the binding key.
477pub fn binding_proof(secret: &[u8], machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
478    let key = registration_binding(secret);
479    let (prk, _) = Hkdf::<Sha256>::extract(
480        Some(key.as_ref()),
481        &teter_common::account::binding_bytes(machine_key, sealed_name),
482    );
483    prk.to_vec()
484}
485
486/// The account keys `pinned` leads to through `rotations` (#89): each one
487/// from the keys reached so far, signed by their signing key, moves on to its
488/// new keys; any other is skipped (a relay cannot forge one).
489pub fn follow_rotations(
490    pinned: &[u8],
491    rotations: &[teter_common::account::KeyRotation],
492) -> Vec<u8> {
493    let mut keys = pinned.to_vec();
494    for rotation in rotations {
495        let signed = rotation.old_keys == keys
496            && rotation.new_keys.len() == 64
497            && keys.get(32..64).is_some_and(|signing| {
498                verify(
499                    signing,
500                    &teter_common::account::rotation_bytes(
501                        &rotation.old_keys,
502                        &rotation.new_keys,
503                        rotation.at,
504                    ),
505                    &rotation.signature,
506                )
507            });
508        if signed {
509            keys.clone_from(&rotation.new_keys);
510        }
511    }
512    keys
513}
514
515/// A rotation from `old` to `new`, signed by `old` (#89).
516pub fn rotation(
517    old: &AccountKeys,
518    new: &AccountKeys,
519    at: i64,
520) -> teter_common::account::KeyRotation {
521    let (old_keys, new_keys) = (old.public_keys(), new.public_keys());
522    teter_common::account::KeyRotation {
523        signature: old.sign(&teter_common::account::rotation_bytes(
524            &old_keys, &new_keys, at,
525        )),
526        old_keys,
527        new_keys,
528        at,
529    }
530}
531
532/// Whether `cert` is the account's approval of machine `id` with
533/// `machine_key` and `sealed_name`, checked against `account_public` (the
534/// account's public keys as the device knows them from its own private
535/// keys, never as a relay gives them).
536pub fn cert_holds(
537    account_public: &[u8],
538    id: &str,
539    machine_key: &[u8],
540    sealed_name: &[u8],
541    cert: &[u8],
542) -> bool {
543    // A key of its exact length: the signed bytes join it and the name.
544    machine_key.len() == 32
545        && account_public.get(32..64).is_some_and(|signing| {
546            verify(
547                signing,
548                &teter_common::account::cert_bytes(id, machine_key, sealed_name),
549                cert,
550            )
551        })
552}
553
554/// What the account's keys are sealed to for the device whose Ed25519
555/// public key is `device_key` (#154, #158): its X25519 form, then the key
556/// itself, as [`seal_to`] takes public keys. `None` for a key that is not
557/// one.
558pub fn device_sealing_keys(device_key: &[u8]) -> Option<Vec<u8>> {
559    let key = ed25519_dalek::VerifyingKey::from_bytes(device_key.try_into().ok()?).ok()?;
560    let mut keys = key.to_montgomery().to_bytes().to_vec();
561    keys.extend_from_slice(device_key);
562    Some(keys)
563}
564
565impl MachineKey {
566    /// Opens what was sealed (with [`seal_to`]) to this key's X25519 form
567    /// ([`device_sealing_keys`]) with `info`.
568    ///
569    /// # Errors
570    ///
571    /// [`AccountError::WrongKeys`] when it does not open.
572    pub fn open_sealed(
573        &self,
574        info: &[u8],
575        sealed: &[u8],
576    ) -> Result<Zeroizing<Vec<u8>>, AccountError> {
577        let scalar = Zeroizing::new(self.0.to_scalar_bytes());
578        open_with(&x25519_dalek::StaticSecret::from(*scalar), info, sealed)
579    }
580}
581
582/// A device's proof it holds `device` (#154), for its login to account
583/// `name` with `auth_key` at `at` (Unix seconds).
584pub fn device_proof(device: &MachineKey, name: &str, auth_key: &[u8], at: i64) -> Vec<u8> {
585    device.sign(&teter_common::account::device_login_bytes(
586        name,
587        at,
588        &secret_hash(auth_key),
589    ))
590}
591
592/// Crockford's base32 alphabet: no I, L, O or U, which read as other
593/// characters.
594const BASE32: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
595
596/// `bytes` in Crockford's base32, `chars` characters from the first bit
597/// (the last one padded with zero bits).
598fn base32(bytes: &[u8], chars: usize) -> String {
599    let mut out = String::with_capacity(chars);
600    for n in 0..chars {
601        let mut value = 0_usize;
602        for bit in n * 5..n * 5 + 5 {
603            let set = bytes
604                .get(bit / 8)
605                .is_some_and(|byte| byte & (0x80 >> (bit % 8)) != 0);
606            value = (value << 1) | usize::from(set);
607        }
608        out.push(char::from(*BASE32.get(value).unwrap_or(&b'0')));
609    }
610    out
611}
612
613/// `text`, grouped by `size` with dashes.
614fn grouped(text: &str, size: usize) -> String {
615    text.as_bytes()
616        .chunks(size)
617        .map(|chunk| String::from_utf8_lossy(chunk).into_owned())
618        .collect::<Vec<_>>()
619        .join("-")
620}
621
622/// The pairing code of a device's public keys (#154): what the new device
623/// shows, and what the approving device is given (typed) to find it. 10
624/// characters of Crockford's base32 (50 bits) of their SHA-256, so a relay
625/// cannot make keys of its own with a code it is shown in the minutes the
626/// request lasts.
627pub fn pairing_code(pairing_key: &[u8]) -> String {
628    let mut message = b"teter-pairing-v1 ".to_vec();
629    message.extend_from_slice(pairing_key);
630    let digest = <Sha256 as sha2::Digest>::digest(&message);
631    grouped(&base32(&digest, 10), 5)
632}
633
634/// A pairing code or recovery code as typed: upper case, without dashes or
635/// spaces, with the letters base32 reads as digits (O, I, L) made digits.
636pub fn normalize_code(code: &str) -> String {
637    code.chars()
638        .filter(|c| !matches!(c, '-' | ' '))
639        .map(|c| match c.to_ascii_uppercase() {
640            'O' => '0',
641            'I' | 'L' => '1',
642            other => other,
643        })
644        .collect()
645}
646
647/// The random bytes in a recovery code (#154): 128 bits, as the code wraps
648/// the account's keys and the relay keeps that wrapping, open to an offline
649/// guess.
650const RECOVERY_BYTES: usize = 16;
651
652/// A new recovery code: 26 characters of Crockford's base32, in groups.
653///
654/// # Errors
655///
656/// When the system's random source fails.
657pub fn recovery_code() -> io::Result<String> {
658    let mut random = Zeroizing::new([0_u8; RECOVERY_BYTES]);
659    getrandom::fill(random.as_mut()).map_err(io::Error::other)?;
660    Ok(grouped(&base32(random.as_ref(), 26), 5))
661}
662
663/// The random bytes `code` holds, if it is a recovery code.
664fn recovery_bytes(code: &str) -> Option<Zeroizing<[u8; RECOVERY_BYTES]>> {
665    let code = normalize_code(code);
666    if code.len() != 26 {
667        return None;
668    }
669    let mut bits = Zeroizing::new(Vec::with_capacity(130));
670    for c in code.bytes() {
671        let value = BASE32.iter().position(|&b| b == c)?;
672        for shift in (0..5).rev() {
673            bits.push((value >> shift) & 1 == 1);
674        }
675    }
676    // The two padding bits are zero in a code teter made.
677    if bits
678        .get(128..)
679        .is_some_and(|pad| pad.iter().any(|&bit| bit))
680    {
681        return None;
682    }
683    let mut bytes = Zeroizing::new([0_u8; RECOVERY_BYTES]);
684    for (n, bit) in bits.iter().take(128).enumerate() {
685        if *bit && let Some(byte) = bytes.get_mut(n / 8) {
686            *byte |= 0x80 >> (n % 8);
687        }
688    }
689    Some(bytes)
690}
691
692/// The keys a recovery code derives (#154), as a password's: an auth key the
693/// relay checks (keeping its SHA-256), and a wrapping key for the account's
694/// private keys, which never leaves the client. `None` when `code` is not a
695/// recovery code.
696pub fn recovery_derive(code: &str) -> Option<Derived> {
697    let random = recovery_bytes(code)?;
698    let hkdf = Hkdf::<Sha256>::new(Some(b"teter-recovery-v1"), random.as_ref());
699    let key = |info: &[u8]| {
700        let mut key = Zeroizing::new([0_u8; 32]);
701        hkdf.expand(info, key.as_mut()).ok()?;
702        Some(key)
703    };
704    Some(Derived {
705        auth_key: key(b"teter-recovery-v1 auth")?,
706        wrap_key: key(b"teter-recovery-v1 wrap")?,
707    })
708}
709
710/// What the relay keeps of recovery `code` for `keys` of account `name`.
711///
712/// # Errors
713///
714/// A code that is not one, or a random source that fails.
715pub fn recovery_entry(
716    keys: &AccountKeys,
717    name: &str,
718    code: &str,
719) -> io::Result<teter_common::account::RecoveryCode> {
720    let derived = recovery_derive(code).ok_or_else(|| io::Error::other("not a recovery code"))?;
721    Ok(teter_common::account::RecoveryCode {
722        auth_hash: secret_hash(derived.auth_key.as_ref()),
723        wrapped_keys: keys.wrap(&derived, name)?,
724    })
725}
726
727#[cfg(test)]
728mod tests {
729    use super::{
730        AccountError, AccountKeys, KdfParams, derive, follow_rotations, new_salt, rotation,
731        salt_blob,
732    };
733
734    #[test]
735    fn a_machine_follows_only_rotations_signed_from_the_keys_it_holds() {
736        let first = AccountKeys::generate().unwrap();
737        let second = AccountKeys::generate().unwrap();
738        let third = AccountKeys::generate().unwrap();
739        let stranger = AccountKeys::generate().unwrap();
740        let one = rotation(&first, &second, 10);
741        let two = rotation(&second, &third, 20);
742        // A chain, in order, leads to its end; from the middle, the rest.
743        assert_eq!(
744            follow_rotations(&first.public_keys(), &[one.clone(), two.clone()]),
745            third.public_keys()
746        );
747        assert_eq!(
748            follow_rotations(&second.public_keys(), &[one.clone(), two.clone()]),
749            third.public_keys()
750        );
751        // One signed by other keys, or altered, is skipped.
752        let forged = rotation(&stranger, &stranger, 30);
753        let mut moved = one.clone();
754        moved.old_keys = stranger.public_keys();
755        let mut altered = one.clone();
756        altered.new_keys = stranger.public_keys();
757        let mut later = one.clone();
758        later.at += 1;
759        for skipped in [forged, moved, altered, later] {
760            assert_eq!(
761                follow_rotations(&first.public_keys(), &[skipped]),
762                first.public_keys()
763            );
764        }
765        // Keys no rotation starts from stay.
766        assert_eq!(
767            follow_rotations(&stranger.public_keys(), &[one, two]),
768            stranger.public_keys()
769        );
770    }
771
772    use teter_common::account::{DEFAULT_KDF, MAX_KDF};
773
774    /// The parameters new accounts get (fast in tests: Argon2 is built
775    /// optimized in the dev profile).
776    const CHEAP: KdfParams = DEFAULT_KDF;
777
778    #[test]
779    fn the_same_password_and_salt_give_the_same_keys_and_another_password_others() {
780        let salt = new_salt(CHEAP).unwrap();
781        let one = derive("correct horse", &salt).unwrap();
782        let again = derive("correct horse", &salt).unwrap();
783        let other = derive("correct horsf", &salt).unwrap();
784        assert_eq!(*one.auth_key, *again.auth_key);
785        assert_ne!(*one.auth_key, *other.auth_key);
786        assert_ne!(*one.auth_key, *one.wrap_key);
787        // Another salt, other keys.
788        let elsewhere = derive("correct horse", &new_salt(CHEAP).unwrap()).unwrap();
789        assert_ne!(*one.auth_key, *elsewhere.auth_key);
790    }
791
792    #[test]
793    fn wrapped_keys_open_with_the_password_and_name_only() {
794        let salt = new_salt(CHEAP).unwrap();
795        let derived = derive("correct horse", &salt).unwrap();
796        let keys = AccountKeys::generate().unwrap();
797        let wrapped = keys.wrap(&derived, "ana").unwrap();
798        let public = keys.public_keys();
799        let opened = AccountKeys::unwrap(&derived, "ana", &wrapped, &public).unwrap();
800        assert_eq!(*opened.private_bytes(), *keys.private_bytes());
801        let wrong = derive("wrong", &salt).unwrap();
802        assert!(matches!(
803            AccountKeys::unwrap(&wrong, "ana", &wrapped, &public),
804            Err(AccountError::WrongKeys)
805        ));
806        assert!(matches!(
807            AccountKeys::unwrap(&derived, "bia", &wrapped, &public),
808            Err(AccountError::WrongKeys)
809        ));
810        // Keys that open but are not the account's public ones.
811        let other = AccountKeys::generate().unwrap().public_keys();
812        assert!(AccountKeys::unwrap(&derived, "ana", &wrapped, &other).is_err());
813        // Nothing private in Debug.
814        assert_eq!(format!("{keys:?}"), "AccountKeys { .. }");
815    }
816
817    #[test]
818    fn a_salt_of_another_version_is_refused() {
819        let mut salt = new_salt(CHEAP).unwrap();
820        salt[0] = 9;
821        assert!(matches!(derive("x", &salt), Err(AccountError::BadSalt)));
822        assert!(matches!(
823            derive("x", &salt[..10]),
824            Err(AccountError::BadSalt)
825        ));
826    }
827
828    #[test]
829    fn a_salt_whose_cost_is_too_low_or_too_high_is_refused() {
830        let random = [7_u8; 16];
831        for params in [
832            KdfParams {
833                memory_kib: 8,
834                passes: 1,
835                lanes: 1,
836            },
837            KdfParams {
838                passes: 1,
839                ..DEFAULT_KDF
840            },
841            KdfParams {
842                memory_kib: MAX_KDF.memory_kib + 1,
843                ..DEFAULT_KDF
844            },
845            KdfParams {
846                passes: u32::MAX,
847                ..DEFAULT_KDF
848            },
849            KdfParams {
850                lanes: 0,
851                ..DEFAULT_KDF
852            },
853        ] {
854            assert!(
855                matches!(
856                    derive("x", &salt_blob(params, &random)),
857                    Err(AccountError::Kdf(_))
858                ),
859                "{params:?}"
860            );
861        }
862    }
863
864    #[test]
865    fn what_is_sealed_to_an_account_opens_with_its_keys_and_info_only() {
866        use super::{MachineKey, seal_to};
867
868        let keys = AccountKeys::generate().unwrap();
869        let sealed = seal_to(&keys.public_keys(), b"machine name", b"jupiter").unwrap();
870        assert_eq!(
871            keys.open_sealed(b"machine name", &sealed)
872                .unwrap()
873                .as_slice(),
874            b"jupiter"
875        );
876        assert!(keys.open_sealed(b"session key", &sealed).is_err());
877        let other = AccountKeys::generate().unwrap();
878        assert!(other.open_sealed(b"machine name", &sealed).is_err());
879        // A machine key signs, and keeps its seed.
880        let machine = MachineKey::generate().unwrap();
881        let again = MachineKey::from_seed(machine.seed().as_ref()).unwrap();
882        assert_eq!(machine.public_key(), again.public_key());
883        assert_eq!(machine.sign(b"x").len(), 64);
884        assert_eq!(format!("{machine:?}"), "MachineKey { .. }");
885    }
886
887    #[test]
888    fn a_proven_request_carries_the_request_and_verifies_under_the_device_key() {
889        use super::{DeviceKey, prove, verify};
890        use teter_common::account::{AccountRequest, proof_bytes};
891
892        let device = DeviceKey::generate().unwrap();
893        let inner = AccountRequest::MachineList {
894            login: "tok".into(),
895        };
896        let AccountRequest::Proven {
897            request,
898            at,
899            nonce,
900            signature,
901        } = prove(&device, &inner, 42).unwrap()
902        else {
903            panic!("not proven");
904        };
905        assert_eq!(at, 42);
906        assert_eq!(
907            serde_json::from_str::<AccountRequest>(&request).unwrap(),
908            inner
909        );
910        let bytes = proof_bytes(&request, at, &nonce);
911        assert!(verify(&device.public_key(), &bytes, &signature));
912        let other = DeviceKey::generate().unwrap();
913        assert!(!verify(&other.public_key(), &bytes, &signature));
914        // Each proof has its own nonce.
915        let AccountRequest::Proven { nonce: again, .. } = prove(&device, &inner, 42).unwrap()
916        else {
917            panic!("not proven");
918        };
919        assert_ne!(nonce, again);
920    }
921
922    #[test]
923    fn a_recovery_code_holds_128_bits_and_reads_back_as_typed() {
924        let code = super::recovery_code().unwrap();
925        assert_eq!(code.len(), 26 + 5);
926        let keys = AccountKeys::generate().unwrap();
927        let entry = super::recovery_entry(&keys, "ana", &code).unwrap();
928        // Typed in lower case, without dashes: the same keys.
929        let typed = code.replace('-', "").to_lowercase();
930        let derived = super::recovery_derive(&typed).unwrap();
931        assert_eq!(
932            super::secret_hash(derived.auth_key.as_ref()),
933            entry.auth_hash
934        );
935        let opened =
936            AccountKeys::unwrap(&derived, "ana", &entry.wrapped_keys, &keys.public_keys()).unwrap();
937        assert_eq!(opened.public_keys(), keys.public_keys());
938        // Another code, another account's name, or a code cut short: nothing.
939        let other = super::recovery_derive(&super::recovery_code().unwrap()).unwrap();
940        assert!(
941            AccountKeys::unwrap(&other, "ana", &entry.wrapped_keys, &keys.public_keys()).is_err()
942        );
943        assert!(
944            AccountKeys::unwrap(&derived, "bob", &entry.wrapped_keys, &keys.public_keys()).is_err()
945        );
946        assert!(super::recovery_derive(code.get(..20).unwrap()).is_none());
947        assert!(super::recovery_derive("UUUUU-UUUUU-UUUUU-UUUUU-UUUUUU").is_none());
948    }
949
950    #[test]
951    fn a_pairing_code_follows_the_key_and_reads_as_typed() {
952        let one = AccountKeys::generate().unwrap().public_keys();
953        let two = AccountKeys::generate().unwrap().public_keys();
954        let code = super::pairing_code(&one);
955        assert_eq!(code.len(), 11);
956        assert_eq!(code, super::pairing_code(&one));
957        assert_ne!(code, super::pairing_code(&two));
958        assert_eq!(
959            super::normalize_code(&code.to_lowercase().replace('-', " ")),
960            code.replace('-', "")
961        );
962        assert_eq!(super::normalize_code("o1-il"), "0111");
963    }
964
965    #[test]
966    fn keys_sealed_to_a_device_key_open_with_it_alone() {
967        let device = super::DeviceKey::generate().unwrap();
968        let to = super::device_sealing_keys(&device.public_key()).unwrap();
969        let sealed = super::seal_to(&to, b"device keys d1", b"the keys").unwrap();
970        assert_eq!(
971            device
972                .open_sealed(b"device keys d1", &sealed)
973                .unwrap()
974                .as_slice(),
975            b"the keys"
976        );
977        assert!(device.open_sealed(b"device keys d2", &sealed).is_err());
978        let other = super::DeviceKey::generate().unwrap();
979        assert!(other.open_sealed(b"device keys d1", &sealed).is_err());
980        assert!(super::device_sealing_keys(&[0; 31]).is_none());
981    }
982}