teter 26.11.5

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Machines (#86): `teter register` and `teter unregister` on the machine,
//! like a GitLab runner; `teter machine ls` and `teter machine rm` from a
//! logged-in device. A registered machine keeps its identity in
//! `$XDG_CONFIG_HOME/teter/host.json`, mode 0600: the relay, its ID, its
//! private key, and the account's public keys, pinned at registration.

use std::io::Write as _;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};
use teter_client::account::{self, AccountKeys, MachineKey};
use teter_common::account::{
    AccountReply, AccountRequest, MachineInfo, Registration, hex, unhex, unregister_message,
};
use zeroize::Zeroizing;

/// What a sealed machine name is bound to.
pub(crate) const NAME_INFO: &[u8] = teter_common::account::MACHINE_NAME_INFO;

/// Register this machine with an account, with a registration token.
#[derive(clap::Args)]
pub struct RegisterArgs {
    /// The registration token (`teter token create` on a logged-in device).
    #[arg(long, env = "TETER_REGISTRATION", hide_env_values = true)]
    token: String,

    /// The machine's name, as the account sees it (default: its host name).
    #[arg(long)]
    name: Option<String>,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// Unregister this machine: the relay forgets it, and its identity here is
/// removed.
#[derive(clap::Args)]
pub struct UnregisterArgs {
    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// The account's machines.
#[derive(clap::Args)]
pub struct MachineArgs {
    #[command(subcommand)]
    command: MachineCommand,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long, global = true)]
    ca_cert: Option<PathBuf>,
}

#[derive(clap::Subcommand)]
enum MachineCommand {
    /// List the account's machines.
    Ls,
    /// This machine's key fingerprint, to approve it by hand on a device
    /// of the account (#133).
    Fingerprint,
    /// Approve a machine of the account, after checking its key against the
    /// fingerprint it shows (`teter machine fingerprint` on it). Machines
    /// registered with a token this device made are approved on their own.
    Approve {
        /// The machine's name.
        name: String,
        /// Its key's fingerprint, as it shows it.
        #[arg(long)]
        fingerprint: String,
    },
    /// Remove a machine from the account: it can no longer connect.
    Rm {
        /// The machine's ID, as `teter machine ls` shows it (or the start of
        /// it).
        id: String,
    },
}

/// A registered machine's identity, kept on the machine.
#[derive(Serialize, Deserialize)]
pub(crate) struct Host {
    /// The relay it is registered with.
    pub(crate) relay: String,
    /// Its ID.
    pub(crate) machine: String,
    /// Its private key's seed, hex.
    pub(crate) machine_key: String,
    /// The account's public keys, hex, pinned at registration.
    pub(crate) account_keys: String,
}

impl Drop for Host {
    fn drop(&mut self) {
        zeroize::Zeroize::zeroize(&mut self.machine_key);
    }
}

impl Host {
    /// Its key pair.
    pub(crate) fn key(&self) -> std::io::Result<MachineKey> {
        unhex(&self.machine_key)
            .map(Zeroizing::new)
            .and_then(|seed| MachineKey::from_seed(&seed))
            .ok_or_else(|| std::io::Error::other("host.json is damaged: register again"))
    }
}

/// The file a registered machine keeps its identity in.
pub(crate) fn host_file() -> std::io::Result<PathBuf> {
    let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
    if let Some(config) = var("XDG_CONFIG_HOME") {
        return Ok(PathBuf::from(config).join("teter/host.json"));
    }
    let home = var("HOME").ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "neither XDG_CONFIG_HOME nor HOME is set: no place for the machine's identity",
        )
    })?;
    Ok(PathBuf::from(home).join(".config/teter/host.json"))
}

/// This machine's identity, if it is registered.
pub(crate) fn load_host() -> std::io::Result<Option<Host>> {
    match std::fs::read(host_file()?) {
        Ok(bytes) => {
            let bytes = Zeroizing::new(bytes);
            serde_json::from_slice(&bytes)
                .map(Some)
                .map_err(std::io::Error::other)
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
        Err(e) => Err(e),
    }
}

/// Registers this machine.
pub async fn register(args: RegisterArgs) -> std::io::Result<()> {
    let path = host_file()?;
    if path.exists() {
        return Err(std::io::Error::other(
            "this machine is registered already: teter unregister first",
        ));
    }
    let registration = Registration::parse(&args.token)
        .ok_or_else(|| std::io::Error::other("this is not a registration token"))?;
    let ca_cert = args.ca_cert.as_deref();
    let relay = registration.relay.clone();
    let public_keys = checked_account_keys(&relay, ca_cert, &registration).await?;
    let name = match args.name {
        Some(name) => name,
        None => host_name(),
    };
    let key = MachineKey::generate()?;
    let mut host = Host {
        relay: relay.clone(),
        machine: String::new(),
        machine_key: hex(key.seed().as_ref()),
        account_keys: hex(&public_keys),
    };
    // The key is on disk before the relay knows it: a machine registered
    // whose key could not be kept would take a use of the token for nothing.
    save_host(&path, &host, true)?;
    let sealed_name = account::seal_to(&public_keys, NAME_INFO, name.as_bytes())?;
    let request = AccountRequest::Register {
        // A key derived from the secret: the relay never learns the one
        // the binding proves the token with (#133).
        secret: account::registration_auth(&registration.secret).to_vec(),
        machine_key: key.public_key(),
        binding: account::binding_proof(&registration.secret, &key.public_key(), &sealed_name),
        sealed_name,
    };
    let registered = match crate::account::ask(&relay, ca_cert, &request).await {
        Ok(AccountReply::Registered { machine }) => Ok(machine),
        Ok(reply) => Err(crate::account::unexpected(&reply)),
        Err(e) => Err(e),
    };
    let machine = match registered {
        Ok(machine) => machine,
        Err(e) => {
            drop(std::fs::remove_file(&path));
            return Err(e);
        }
    };
    host.machine.clone_from(&machine);
    save_host(&path, &host, false).map_err(|e| {
        std::io::Error::other(format!(
            "registered as {machine}, but could not keep it ({e}): remove it with teter machine \
             rm {machine} on a logged-in device, and register again"
        ))
    })?;
    println!("registered this machine as {name} ({machine}); run teter link to serve it");
    println!(
        "its key's fingerprint: {} (the device that made the token approves it on its own; \
         another approves it with teter machine approve {name} --fingerprint <it>)",
        hex(&account::fingerprint(&key.public_key()))
    );
    Ok(())
}

/// The public keys of `registration`'s account, as the relay gives them,
/// checked against the token's fingerprint: a relay that gave other keys
/// would have the machine seal to, and obey, someone else.
async fn checked_account_keys(
    relay: &str,
    ca_cert: Option<&Path>,
    registration: &Registration,
) -> std::io::Result<Vec<u8>> {
    let request = AccountRequest::TokenKeys {
        secret: account::registration_auth(&registration.secret).to_vec(),
    };
    let reply = crate::account::ask(relay, ca_cert, &request).await?;
    let AccountReply::AccountKeys { public_keys } = reply else {
        return Err(crate::account::unexpected(&reply));
    };
    if account::fingerprint(&public_keys) != registration.fingerprint {
        return Err(std::io::Error::other(
            "the relay gave account keys that do not match the token's fingerprint: refusing to \
             register (the relay, or something between, may be swapping the account's keys)",
        ));
    }
    Ok(public_keys)
}

/// Unregisters this machine.
pub async fn unregister(args: UnregisterArgs) -> std::io::Result<()> {
    let host =
        load_host()?.ok_or_else(|| std::io::Error::other("this machine is not registered"))?;
    let at = now();
    let request = AccountRequest::Unregister {
        machine: host.machine.clone(),
        at,
        signature: host.key()?.sign(&unregister_message(&host.machine, at)),
    };
    let reply = crate::account::ask(&host.relay, args.ca_cert.as_deref(), &request).await?;
    let AccountReply::MachineRemoved { removed } = reply else {
        return Err(crate::account::unexpected(&reply));
    };
    // Removed, or already unknown to the relay (its account removed it):
    // either way its identity here goes.
    std::fs::remove_file(host_file()?)?;
    if removed {
        println!("unregistered this machine");
    } else {
        println!("the relay had forgotten this machine already; its identity here is removed");
    }
    Ok(())
}

/// Runs `teter machine`.
pub async fn machine(args: MachineArgs) -> std::io::Result<()> {
    if matches!(args.command, MachineCommand::Fingerprint) {
        let host = load_host()?
            .filter(|host| !host.machine.is_empty())
            .ok_or_else(|| std::io::Error::other("this machine is not registered"))?;
        println!("{}", hex(&account::fingerprint(&host.key()?.public_key())));
        return Ok(());
    }
    let saved = crate::account::load()?;
    let ca_cert = args.ca_cert.as_deref();
    let keys = unhex(&saved.private_keys)
        .map(Zeroizing::new)
        .and_then(|private| AccountKeys::from_private_bytes(&private))
        .ok_or_else(|| std::io::Error::other("the saved account is damaged: log in again"))?;
    let mut machines = list(&saved, ca_cert).await?;
    if crate::approve::pending_machines(&saved, &keys, ca_cert, &machines).await? > 0 {
        machines = list(&saved, ca_cert).await?;
    }
    let name_of = |machine: &MachineInfo| {
        keys.open_sealed(NAME_INFO, &machine.sealed_name)
            .ok()
            .and_then(|name| String::from_utf8(name.to_vec()).ok())
    };
    match args.command {
        MachineCommand::Fingerprint => Ok(()),
        MachineCommand::Approve { name, fingerprint } => {
            let matching: Vec<&MachineInfo> = machines
                .iter()
                .filter(|machine| name_of(machine).as_deref() == Some(name.as_str()))
                .collect();
            approve_named(&saved, &keys, ca_cert, &name, &matching, &fingerprint).await
        }
        MachineCommand::Ls => {
            ls(&keys, &machines);
            Ok(())
        }
        MachineCommand::Rm { id } => rm(&saved, ca_cert, &machines, &id).await,
    }
}

/// `teter machine rm`: the one machine whose ID starts with `id`.
async fn rm(
    saved: &crate::account::Saved,
    ca_cert: Option<&Path>,
    machines: &[MachineInfo],
    id: &str,
) -> std::io::Result<()> {
    let id = id.to_ascii_lowercase();
    let matching: Vec<&MachineInfo> = machines
        .iter()
        .filter(|machine| !id.is_empty() && machine.id.starts_with(&id))
        .collect();
    let [machine] = matching[..] else {
        return Err(std::io::Error::other(if matching.is_empty() {
            format!("no machine's ID starts with {id:?}")
        } else {
            format!("more than one machine's ID starts with {id}: give more of it")
        }));
    };
    let request = AccountRequest::MachineRemove {
        login: saved.token.clone(),
        id: machine.id.clone(),
    };
    let reply = crate::account::ask(&saved.relay, ca_cert, &request).await?;
    let AccountReply::MachineRemoved { removed } = reply else {
        return Err(crate::account::unexpected(&reply));
    };
    println!(
        "{} {}",
        if removed { "removed" } else { "already gone:" },
        short(&machine.id)
    );
    Ok(())
}

/// `teter machine approve`: the one machine named `name` (in `matching`),
/// by its fingerprint.
async fn approve_named(
    saved: &crate::account::Saved,
    keys: &AccountKeys,
    ca_cert: Option<&Path>,
    name: &str,
    matching: &[&MachineInfo],
    fingerprint: &str,
) -> std::io::Result<()> {
    let Some(first) = matching.first() else {
        return Err(std::io::Error::other(format!(
            "no machine named {name:?} in this account"
        )));
    };
    // Of several of that name (one registered again, say), the one whose
    // key has that fingerprint.
    let machine = matching
        .iter()
        .find(|machine| {
            teter_common::account::hex(&account::fingerprint(&machine.public_key))
                .eq_ignore_ascii_case(fingerprint.trim())
        })
        .unwrap_or(first);
    crate::approve::by_fingerprint(saved, keys, ca_cert, machine, fingerprint).await?;
    println!("approved {name}");
    Ok(())
}

/// `teter machine ls`.
fn ls(keys: &AccountKeys, machines: &[MachineInfo]) {
    if machines.is_empty() {
        println!("no machines");
    }
    for machine in machines {
        let name = keys
            .open_sealed(NAME_INFO, &machine.sealed_name)
            .ok()
            .and_then(|name| String::from_utf8(name.to_vec()).ok())
            .unwrap_or_else(|| "(a name that does not open)".to_owned());
        let seen = match machine.last_seen {
            // When its link last connected: one connected for a week reads
            // a week ago, so not "seen".
            Some(at) => format!("last connected {}s ago", now().saturating_sub(at).max(0)),
            None => "never connected".to_owned(),
        };
        let approval = if crate::approve::approved(keys, machine) {
            ""
        } else {
            "  (not approved: teter machine approve)"
        };
        println!("{}  {name}  {seen}{approval}", short(&machine.id));
    }
}

async fn list(
    saved: &crate::account::Saved,
    ca_cert: Option<&Path>,
) -> std::io::Result<Vec<MachineInfo>> {
    let request = AccountRequest::MachineList {
        login: saved.token.clone(),
    };
    let reply = crate::account::ask(&saved.relay, ca_cert, &request).await?;
    let AccountReply::Machines { machines } = reply else {
        return Err(crate::account::unexpected(&reply));
    };
    Ok(machines)
}

/// Writes `host` to `path`, closed to others: `new`, a file that must not
/// exist yet; else a new file renamed over it.
fn save_host(path: &Path, host: &Host, new: bool) -> std::io::Result<()> {
    if let Some(dir) = path.parent() {
        std::fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(dir)?;
    }
    let target = if new {
        path.to_owned()
    } else {
        let temporary = path.with_extension("new");
        drop(std::fs::remove_file(&temporary));
        temporary
    };
    let mut file = std::fs::OpenOptions::new()
        .create_new(true)
        .write(true)
        .mode(0o600)
        .open(&target)?;
    let text = Zeroizing::new(serde_json::to_vec(host).map_err(std::io::Error::other)?);
    file.write_all(&text)?;
    file.sync_all()?;
    if new {
        Ok(())
    } else {
        std::fs::rename(&target, path)
    }
}

/// This machine's host name, or `machine` when it has none.
fn host_name() -> String {
    std::fs::read_to_string("/etc/hostname")
        .ok()
        .map(|name| name.trim().to_owned())
        .filter(|name| !name.is_empty())
        .or_else(|| std::env::var("HOSTNAME").ok())
        .unwrap_or_else(|| "machine".to_owned())
}

fn short(id: &str) -> &str {
    id.get(..12).unwrap_or(id)
}

fn now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |since| {
            i64::try_from(since.as_secs()).unwrap_or(i64::MAX)
        })
}