teter_common/account.rs
1//! The account protocol, on the relay's `/account` path: one request, one
2//! reply, per connection (JSON text frames, like the rest of the protocol).
3//!
4//! The password never leaves the client (model C, decided in #57): the client
5//! derives a master key from it (Argon2id, with the parameters and salt the
6//! account carries), and from the master key an auth key, which it presents,
7//! and a wrapping key, which wraps the account's private keys before they
8//! reach the relay. The relay keeps a hash of the auth key, the public keys
9//! and the wrapped private keys, and can read none of what they protect.
10
11use serde::{Deserialize, Serialize};
12
13/// The relay path the account protocol is served on.
14pub const PATH: &str = "/account";
15
16/// The longest account name, in bytes.
17pub const MAX_NAME: usize = 64;
18
19/// Whether `name` can be an account's name: 1 to [`MAX_NAME`] ASCII letters,
20/// digits, `.`, `_` or `-`, starting with a letter or a digit.
21pub fn valid_name(name: &str) -> bool {
22 !name.is_empty()
23 && name.len() <= MAX_NAME
24 && name
25 .bytes()
26 .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
27 && name
28 .bytes()
29 .next()
30 .is_some_and(|b| b.is_ascii_alphanumeric())
31}
32
33/// The version of a salt's layout.
34pub const SALT_VERSION: u8 = 1;
35
36/// The random part of a salt, in bytes.
37pub const SALT_RANDOM_LEN: usize = 16;
38
39/// A salt's length: the version, the Argon2id parameters (memory in KiB,
40/// passes, lanes, each 4 bytes big-endian) and the random bytes.
41pub const SALT_LEN: usize = 1 + 12 + SALT_RANDOM_LEN;
42
43/// Argon2id's cost parameters, carried in an account's salt.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct KdfParams {
46 /// Memory, in KiB.
47 pub memory_kib: u32,
48 /// Passes over the memory.
49 pub passes: u32,
50 /// Lanes.
51 pub lanes: u32,
52}
53
54/// Argon2id's parameters for new accounts: 64 MiB, 3 passes, 1 lane (the
55/// second recommended set of RFC 9106, for memory-constrained devices).
56pub const DEFAULT_KDF: KdfParams = KdfParams {
57 memory_kib: 64 * 1024,
58 passes: 3,
59 lanes: 1,
60};
61
62/// The least Argon2id cost a client accepts, or a relay takes at signup:
63/// [`DEFAULT_KDF`]. A relay is not trusted (#57): one that answered a salt
64/// with a lower cost would make the auth key cheap to guess the password
65/// from.
66pub const MIN_KDF: KdfParams = DEFAULT_KDF;
67
68/// The most Argon2id cost a client accepts: 1 GiB, 10 passes, 8 lanes. A
69/// relay that answered more would have the client run out of memory or
70/// spin.
71pub const MAX_KDF: KdfParams = KdfParams {
72 memory_kib: 1024 * 1024,
73 passes: 10,
74 lanes: 8,
75};
76
77/// Whether `params` is within [`MIN_KDF`] and [`MAX_KDF`].
78pub fn acceptable_kdf(params: KdfParams) -> bool {
79 (MIN_KDF.memory_kib..=MAX_KDF.memory_kib).contains(¶ms.memory_kib)
80 && (MIN_KDF.passes..=MAX_KDF.passes).contains(¶ms.passes)
81 && (MIN_KDF.lanes..=MAX_KDF.lanes).contains(¶ms.lanes)
82}
83
84/// A salt for `params` with `random` as its random bytes.
85pub fn salt_blob(params: KdfParams, random: &[u8; SALT_RANDOM_LEN]) -> Vec<u8> {
86 let mut blob = Vec::with_capacity(SALT_LEN);
87 blob.push(SALT_VERSION);
88 blob.extend_from_slice(¶ms.memory_kib.to_be_bytes());
89 blob.extend_from_slice(¶ms.passes.to_be_bytes());
90 blob.extend_from_slice(¶ms.lanes.to_be_bytes());
91 blob.extend_from_slice(random);
92 blob
93}
94
95/// The parameters and random bytes of `salt`, if it has this build's layout.
96pub fn parse_salt(salt: &[u8]) -> Option<(KdfParams, &[u8])> {
97 let (header, random) = salt.split_at_checked(13)?;
98 let [version, m0, m1, m2, m3, t0, t1, t2, t3, p0, p1, p2, p3] = *header else {
99 return None;
100 };
101 (version == SALT_VERSION && random.len() == SALT_RANDOM_LEN).then_some((
102 KdfParams {
103 memory_kib: u32::from_be_bytes([m0, m1, m2, m3]),
104 passes: u32::from_be_bytes([t0, t1, t2, t3]),
105 lanes: u32::from_be_bytes([p0, p1, p2, p3]),
106 },
107 random,
108 ))
109}
110
111/// A request to the relay's account service.
112#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
113#[non_exhaustive]
114pub enum AccountRequest {
115 /// The salt (with its key derivation parameters) of account `name`, to
116 /// derive its keys before logging in. A name with no account gets a salt
117 /// all the same, always the same for that name, so the answer does not
118 /// tell which names have accounts.
119 Salt {
120 /// The account's name.
121 name: String,
122 },
123 /// Makes account `name`.
124 Signup {
125 /// The account's name.
126 name: String,
127 /// The salt and key derivation parameters the client used.
128 salt: Vec<u8>,
129 /// The auth key the client derived; the relay keeps only its hash.
130 auth_key: Vec<u8>,
131 /// The account's public keys.
132 public_keys: Vec<u8>,
133 /// The account's private keys, wrapped by the client.
134 wrapped_keys: Vec<u8>,
135 /// The invite the relay's admin gave (#103): signup is closed
136 /// without one.
137 #[serde(default)]
138 invite: String,
139 },
140 /// Logs in to account `name` with the auth key derived from its password.
141 Login {
142 /// The account's name.
143 name: String,
144 /// The auth key.
145 auth_key: Vec<u8>,
146 },
147 /// Ends the login session of `token`.
148 Logout {
149 /// The login token.
150 token: String,
151 },
152 /// Makes a registration token for the logged-in account: the relay keeps
153 /// the hash of its enrollment secret (the client keeps the secret), with
154 /// its expiry and uses.
155 TokenCreate {
156 /// The login token.
157 login: String,
158 /// The SHA-256 of the enrollment secret.
159 secret_hash: Vec<u8>,
160 /// Seconds until it stops working (at most [`MAX_TOKEN_LIFETIME`]).
161 expires_in: u64,
162 /// How many machines it registers (1 to [`MAX_TOKEN_USES`]).
163 uses: u32,
164 },
165 /// The registration tokens of the logged-in account.
166 TokenList {
167 /// The login token.
168 login: String,
169 },
170 /// Revokes a registration token of the logged-in account.
171 TokenRevoke {
172 /// The login token.
173 login: String,
174 /// The token's ID ([`TokenInfo::id`]).
175 id: String,
176 },
177 /// The public keys of the account a registration token belongs to, for
178 /// the machine to check against the token's fingerprint before it
179 /// registers. Uses nothing of the token.
180 TokenKeys {
181 /// The token's enrollment secret.
182 secret: Vec<u8>,
183 },
184 /// Registers a machine with a registration token, taking one of its
185 /// uses.
186 Register {
187 /// The token's enrollment secret.
188 secret: Vec<u8>,
189 /// The machine's Ed25519 public key, which it authenticates with.
190 machine_key: Vec<u8>,
191 /// The machine's display name, sealed to the account's X25519 key.
192 sealed_name: Vec<u8>,
193 /// Its proof it holds the token (#133): HMAC-SHA256 of
194 /// [`binding_bytes`] under the token's binding key, which never
195 /// reaches the relay. The device that made the token checks it
196 /// before it approves the machine.
197 #[serde(default)]
198 binding: Vec<u8>,
199 },
200 /// Approves a machine of the logged-in account (#133): the account's
201 /// signature of [`cert_bytes`], which devices check before they trust
202 /// the machine's key, name and records.
203 MachineApprove {
204 /// The login token.
205 login: String,
206 /// The machine's ID.
207 id: String,
208 /// The account's signature.
209 cert: Vec<u8>,
210 },
211 /// The logged-in account's machines.
212 MachineList {
213 /// The login token.
214 login: String,
215 },
216 /// Removes a machine of the logged-in account: it can no longer connect.
217 MachineRemove {
218 /// The login token.
219 login: String,
220 /// The machine's ID.
221 id: String,
222 },
223 /// The logged-in account's machines, each with the relay session it is
224 /// served on now (if it is connected) and its sessions' records (#87):
225 /// all a device needs to attach, nothing carried by hand.
226 Sessions {
227 /// The login token.
228 login: String,
229 },
230 /// A machine removes itself, proving it holds its key.
231 Unregister {
232 /// The machine's ID.
233 machine: String,
234 /// When it signed (Unix seconds); the relay takes it within
235 /// [`UNREGISTER_WINDOW`] of its own clock.
236 at: i64,
237 /// Its signature of [`unregister_message`].
238 signature: Vec<u8>,
239 },
240}
241
242/// How far a machine's `Unregister` time may be from the relay's, in seconds.
243pub const UNREGISTER_WINDOW: i64 = 300;
244
245/// What a machine signs to unregister: this prefix, its ID, and the time.
246pub fn unregister_message(machine: &str, at: i64) -> Vec<u8> {
247 let mut message = b"teter-unregister-v1 ".to_vec();
248 message.extend_from_slice(machine.as_bytes());
249 message.extend_from_slice(&at.to_be_bytes());
250 message
251}
252
253/// A machine as the relay lists it to its account.
254#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
255pub struct MachineInfo {
256 /// Its ID.
257 pub id: String,
258 /// Its display name, sealed to the account.
259 pub sealed_name: Vec<u8>,
260 /// When it last connected (Unix seconds), if it has.
261 pub last_seen: Option<i64>,
262 /// Its public key (#133).
263 #[serde(default)]
264 pub public_key: Vec<u8>,
265 /// Its proof it held the token (see [`AccountRequest::Register`]).
266 #[serde(default)]
267 pub binding: Vec<u8>,
268 /// The account's approval, empty before one.
269 #[serde(default)]
270 pub cert: Vec<u8>,
271}
272
273/// The longest a registration token works: 30 days.
274pub const MAX_TOKEN_LIFETIME: u64 = 30 * 24 * 3600;
275
276/// The most machines one registration token registers.
277pub const MAX_TOKEN_USES: u32 = 100;
278
279/// A registration token as the relay lists it: never its secret.
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281pub struct TokenInfo {
282 /// Its ID: the SHA-256 of its secret, hex.
283 pub id: String,
284 /// When it was made (Unix seconds).
285 pub created: i64,
286 /// When it stops working (Unix seconds).
287 pub expires: i64,
288 /// How many more machines it registers.
289 pub uses_left: i64,
290}
291
292/// The relay's reply to an [`AccountRequest`].
293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
294#[non_exhaustive]
295pub enum AccountReply {
296 /// The salt asked for.
297 Salt {
298 /// The salt and key derivation parameters.
299 salt: Vec<u8>,
300 },
301 /// The account was made.
302 SignedUp,
303 /// Logged in: a token for the relay, and the account's keys, the private
304 /// ones still wrapped.
305 LoggedIn {
306 /// The login token.
307 token: String,
308 /// The account's public keys.
309 public_keys: Vec<u8>,
310 /// The account's private keys, wrapped.
311 wrapped_keys: Vec<u8>,
312 },
313 /// The login session ended (or there was none).
314 LoggedOut,
315 /// The registration token was made.
316 TokenCreated,
317 /// The account's registration tokens, oldest first.
318 Tokens {
319 /// The tokens.
320 tokens: Vec<TokenInfo>,
321 /// The relay's clock (Unix seconds), which the expiries are on; 0
322 /// from a relay that does not send it.
323 #[serde(default)]
324 now: i64,
325 },
326 /// Whether a registration token was revoked (`false`: no such token).
327 TokenRevoked {
328 /// Whether it was.
329 revoked: bool,
330 },
331 /// The public keys of a registration token's account.
332 AccountKeys {
333 /// The account's public keys.
334 public_keys: Vec<u8>,
335 },
336 /// The machine is registered.
337 Registered {
338 /// Its ID, which it says hello with.
339 machine: String,
340 },
341 /// The account's machines.
342 Machines {
343 /// The machines.
344 machines: Vec<MachineInfo>,
345 },
346 /// Whether a machine was removed (`false`: no such machine).
347 MachineRemoved {
348 /// Whether it was.
349 removed: bool,
350 },
351 /// Whether a machine was approved (`false`: no such machine).
352 MachineApproved {
353 /// Whether it was.
354 approved: bool,
355 },
356 /// The account's machines and their sessions.
357 Sessions {
358 /// The machines.
359 machines: Vec<MachineSessions>,
360 },
361 /// Refused, and why. A failed login says only that the name or the
362 /// password is wrong, never which.
363 Refused {
364 /// Why.
365 reason: String,
366 },
367}
368
369/// The reason a login is refused, whatever was wrong.
370pub const WRONG_LOGIN: &str = "wrong account name or password";
371
372/// The reason an account request is refused when its login token is not
373/// (or no longer) a login.
374pub const NOT_LOGGED_IN: &str = "not logged in (or the login expired): run teter login";
375
376/// The prefix of a registration token's text.
377pub const REGISTRATION_PREFIX: &str = "teter-reg1";
378
379/// A registration token, as the logged-in user hands it to the machine to
380/// register: the relay's URL, the enrollment secret, and the fingerprint of
381/// the account's public keys, which the machine checks the keys the relay
382/// gives it against (#86), so a relay cannot swap the account's keys.
383#[derive(Clone, PartialEq, Eq)]
384pub struct Registration {
385 /// The relay's URL.
386 pub relay: String,
387 /// The enrollment secret.
388 pub secret: [u8; 32],
389 /// The fingerprint of the account's public keys.
390 pub fingerprint: [u8; 16],
391}
392
393impl std::fmt::Debug for Registration {
394 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
395 f.debug_struct("Registration")
396 .field("relay", &self.relay)
397 .finish_non_exhaustive()
398 }
399}
400
401impl Registration {
402 /// Its text: `teter-reg1.<relay, hex>.<secret, hex>.<fingerprint, hex>`.
403 pub fn to_text(&self) -> String {
404 format!(
405 "{REGISTRATION_PREFIX}.{}.{}.{}",
406 hex(self.relay.as_bytes()),
407 hex(&self.secret),
408 hex(&self.fingerprint)
409 )
410 }
411
412 /// The token `text` holds, if it is one.
413 pub fn parse(text: &str) -> Option<Self> {
414 let mut parts = text.trim().split('.');
415 let (Some(prefix), Some(relay), Some(secret), Some(fingerprint), None) = (
416 parts.next(),
417 parts.next(),
418 parts.next(),
419 parts.next(),
420 parts.next(),
421 ) else {
422 return None;
423 };
424 if prefix != REGISTRATION_PREFIX {
425 return None;
426 }
427 Some(Self {
428 relay: String::from_utf8(unhex(relay)?).ok()?,
429 secret: unhex(secret)?.try_into().ok()?,
430 fingerprint: unhex(fingerprint)?.try_into().ok()?,
431 })
432 }
433}
434
435/// `bytes`, hex.
436pub fn hex(bytes: &[u8]) -> String {
437 bytes.iter().map(|b| format!("{b:02x}")).collect()
438}
439
440/// The bytes `text` holds in hex, if it is hex.
441pub fn unhex(text: &str) -> Option<Vec<u8>> {
442 if !text.len().is_multiple_of(2) || !text.bytes().all(|b| b.is_ascii_hexdigit()) {
443 return None;
444 }
445 text.as_bytes()
446 .chunks(2)
447 .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok())
448 .collect()
449}
450
451/// The reason a relay refuses a machine it does not know (removed from its
452/// account, or never registered there): the one refusal after which a link
453/// stops for good (#138), not after a passing failure.
454pub const MACHINE_UNKNOWN: &str = "this relay does not know this machine (removed from its account, or registered with another relay?)";
455
456/// The reason a registration token is refused, whatever was wrong with it
457/// (unknown, expired, used up, revoked).
458pub const BAD_TOKEN: &str = "this registration token does not work (unknown, expired, used up or \
459 revoked; or made by a teter older than 26.11.3: make a new one)";
460
461/// A machine of the account and its sessions, as [`AccountReply::Sessions`]
462/// gives them.
463#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
464pub struct MachineSessions {
465 /// The machine's ID.
466 pub id: String,
467 /// Its display name, sealed to the account.
468 pub sealed_name: Vec<u8>,
469 /// Its public key (Ed25519), which signs its command challenges (#88);
470 /// empty from a relay older than that.
471 #[serde(default)]
472 pub public_key: Vec<u8>,
473 /// The account's approval of the machine (#133), empty before one.
474 #[serde(default)]
475 pub cert: Vec<u8>,
476 /// The relay session it is served on now, and the token a frontend joins
477 /// it with; `None` while it is not connected.
478 pub relay: Option<(crate::SessionId, String)>,
479 /// Its sessions.
480 pub sessions: Vec<SessionRecordInfo>,
481}
482
483/// One of a machine's sessions: its channel, its name and key sealed to the
484/// account.
485#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
486pub struct SessionRecordInfo {
487 /// The channel it travels on inside the machine's relay session.
488 pub channel: String,
489 /// The relay session that serves it now, and the token to join it;
490 /// `None` while no link of its machine serves it.
491 pub relay: Option<(crate::SessionId, String)>,
492 /// Its name, sealed to the account.
493 pub sealed_name: Vec<u8>,
494 /// Its end-to-end secret, sealed to the account for its channel.
495 pub sealed_key: Vec<u8>,
496 /// The machine's signature of [`record_bytes`] (#133).
497 #[serde(default)]
498 pub signature: Vec<u8>,
499 /// How many frontends are attached to it now (#135); `None` from a
500 /// relay older than the field.
501 #[serde(default)]
502 pub clients: Option<u32>,
503}
504
505/// What a machine signs to show it held its registration token: its key and
506/// its sealed name (#133).
507pub fn binding_bytes(machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
508 let mut bytes = b"teter-machine-bind-v1 ".to_vec();
509 bytes.extend_from_slice(machine_key);
510 bytes.extend_from_slice(sealed_name);
511 bytes
512}
513
514/// What the account signs to approve machine `id` (#133): its key and its
515/// sealed name, so a relay can neither swap a machine's key nor move its
516/// name.
517pub fn cert_bytes(id: &str, machine_key: &[u8], sealed_name: &[u8]) -> Vec<u8> {
518 let mut bytes = b"teter-machine-cert-v1 ".to_vec();
519 bytes.extend_from_slice(id.as_bytes());
520 bytes.push(0);
521 bytes.extend_from_slice(machine_key);
522 bytes.extend_from_slice(sealed_name);
523 bytes
524}
525
526/// What a machine's display name is sealed to the account with (#86).
527pub const MACHINE_NAME_INFO: &[u8] = b"machine name";
528
529/// What the name of machine `machine`'s session on `channel` is sealed to
530/// the account with (#87): bound to both, so a relay cannot move a name onto
531/// another record.
532pub fn session_name_info(machine: &str, channel: &str) -> Vec<u8> {
533 format!("session name {machine} {channel}").into_bytes()
534}
535
536/// What a session's end-to-end secret is sealed to the account with (#87),
537/// bound to its channel.
538pub fn session_key_info(channel: &str) -> Vec<u8> {
539 let mut info = b"session key ".to_vec();
540 info.extend_from_slice(channel.as_bytes());
541 info
542}
543
544/// What machine `machine` signs for its session on `channel` (#133).
545pub fn record_bytes(
546 machine: &str,
547 channel: &str,
548 sealed_name: &[u8],
549 sealed_key: &[u8],
550) -> Vec<u8> {
551 let mut bytes = b"teter-record-v1 ".to_vec();
552 bytes.extend_from_slice(machine.as_bytes());
553 bytes.push(0);
554 bytes.extend_from_slice(channel.as_bytes());
555 bytes.push(0);
556 bytes.extend_from_slice(
557 &u32::try_from(sealed_name.len())
558 .unwrap_or(u32::MAX)
559 .to_be_bytes(),
560 );
561 bytes.extend_from_slice(sealed_name);
562 bytes.extend_from_slice(sealed_key);
563 bytes
564}