Skip to main content

isothrum_machine/place/ssh/
known_hosts.rs

1//! A server's SSH host keys, trusted on first use: the keys it offers are read (`ssh-keyscan`)
2//! and given to the caller with their SHA-256 fingerprints, as `ssh-keygen -lf` and the server's
3//! own console show them; once the caller confirms them (a user who compared them, say), they are
4//! written to a `known_hosts` file the caller names, and every [`Target`](super::Target) checks
5//! them strictly. A server offering other keys is refused until the new ones are confirmed.
6
7use std::path::{Path, PathBuf};
8use std::time::Duration;
9
10use isothrum_runner::ProcessSpec;
11use serde::Serialize;
12use sha2::{Digest as _, Sha256};
13
14use super::{SshError, safe_token};
15use crate::Context;
16
17/// How long reading a server's keys may take.
18const SCAN_LIMIT: Duration = Duration::from_secs(20);
19
20/// The key types read, strongest first.
21const KEY_TYPES: &str = "ed25519,ecdsa,rsa";
22
23/// One host key of a server, as `known_hosts` writes it.
24#[derive(Debug, Clone, PartialEq, Eq)]
25struct HostKey {
26    /// Its type (`ssh-ed25519`).
27    algorithm: String,
28    /// Its public key, base64.
29    blob: String,
30}
31
32impl HostKey {
33    /// Its SHA-256 fingerprint, as OpenSSH writes it (`SHA256:` and unpadded base64).
34    fn fingerprint(&self) -> Option<String> {
35        let raw = base64_decode(&self.blob)?;
36        Some(format!("SHA256:{}", base64_encode_unpadded(&Sha256::digest(raw))))
37    }
38}
39
40/// One key a server offers.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
42#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS))]
43#[cfg_attr(feature = "ts-rs", ts(rename = "SshHostKey"))]
44#[serde(rename_all = "camelCase")]
45pub struct Shown {
46    /// Its type (`ssh-ed25519`).
47    pub algorithm: String,
48    /// Its SHA-256 fingerprint (`SHA256:…`).
49    pub fingerprint: String,
50}
51
52/// Whether the keys a server offers are the ones confirmed for it.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
54#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS))]
55#[cfg_attr(feature = "ts-rs", ts(rename = "SshHostKeyState"))]
56#[serde(rename_all = "camelCase")]
57pub enum State {
58    /// None was confirmed for it yet.
59    New,
60    /// They are.
61    Confirmed,
62    /// Others were: the server was reinstalled, or the connection is intercepted.
63    Changed,
64}
65
66/// The keys a server offers and whether they are the confirmed ones.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
68#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS))]
69#[cfg_attr(feature = "ts-rs", ts(rename = "SshHostKeys"))]
70#[serde(rename_all = "camelCase")]
71pub struct Offered {
72    /// The server's address and SSH port, as `known_hosts` names it (`pve.lan`, `[pve.lan]:2222`).
73    pub pattern: String,
74    /// The keys, strongest first.
75    pub keys: Vec<Shown>,
76    /// Whether they are the confirmed ones.
77    pub state: State,
78}
79
80/// How `known_hosts` names `host` reached on `port`.
81#[must_use]
82pub fn pattern(host: &str, port: u16) -> String {
83    if port == 22 { host.to_owned() } else { format!("[{host}]:{port}") }
84}
85
86/// The keys of the lines of `text` (a scan, or `ssh-keygen -F`'s answer) that name `pattern`.
87fn keys_in(text: &str, pattern: &str) -> Vec<HostKey> {
88    text.lines()
89        .filter(|l| !l.starts_with('#') && !l.starts_with('@'))
90        .filter_map(|l| {
91            let mut fields = l.split_whitespace();
92            let (hosts, algorithm, blob) = (fields.next()?, fields.next()?, fields.next()?);
93            // A scan names the host; `ssh-keygen -F` may answer a hashed name (`|1|…`).
94            let ours = hosts.starts_with("|1|") || hosts.split(',').any(|n| n == pattern);
95            ours.then(|| HostKey {
96                algorithm: algorithm.to_owned(),
97                blob: blob.to_owned(),
98            })
99        })
100        .collect()
101}
102
103/// Runs `program args` within [`SCAN_LIMIT`].
104async fn run(ctx: &Context, program: &str, args: &[&str]) -> Result<isothrum_runner::Captured, SshError> {
105    Ok(ctx.probe_within(SCAN_LIMIT, &ProcessSpec::new(program, args.iter().copied())).await?)
106}
107
108/// The keys `host` offers on `port`.
109async fn scan(ctx: &Context, host: &str, port: u16) -> Result<Vec<HostKey>, SshError> {
110    if !safe_token(host) {
111        return Err(SshError::Invalid("host"));
112    }
113    let port_arg = port.to_string();
114    let scanned = run(ctx, "ssh-keyscan", &["-T", "10", "-p", &port_arg, "-t", KEY_TYPES, host]).await?;
115    let out = scanned.output().map_err(|f| SshError::Failed(f.to_string()))?;
116    let mut keys = keys_in(&out, &pattern(host, port));
117    keys.dedup();
118    if keys.is_empty() {
119        return Err(SshError::Failed(format!("{host} offered no SSH host key on port {port}")));
120    }
121    Ok(keys)
122}
123
124/// The keys confirmed for `pattern` in `file`; none for a file not written yet.
125async fn confirmed(ctx: &Context, file: &Path, pattern: &str) -> Result<Vec<HostKey>, SshError> {
126    if !file.is_file() {
127        return Ok(Vec::new());
128    }
129    let path = file.to_string_lossy();
130    let found = run(ctx, "ssh-keygen", &["-F", pattern, "-f", &path]).await?;
131    if found.success() {
132        return Ok(keys_in(&found.stdout.join("\n"), pattern));
133    }
134    // Not found: `ssh-keygen -F` exits 1 without a word.
135    if found.stderr_tail.iter().all(|l| l.trim().is_empty()) {
136        return Ok(Vec::new());
137    }
138    Err(SshError::Failed(found.reason()))
139}
140
141/// Whether the keys `offered` are the ones confirmed (`known`).
142fn state(offered: &[HostKey], known: &[HostKey]) -> State {
143    match known {
144        [] => State::New,
145        known if known.iter().all(|k| offered.contains(k)) => State::Confirmed,
146        _ => State::Changed,
147    }
148}
149
150/// The keys `host` offers on `port`, to be confirmed, and whether they are the ones confirmed in
151/// `file` already.
152///
153/// # Errors
154///
155/// The host isn't a plain word, its keys couldn't be read, or it offered none.
156pub async fn offered(ctx: &Context, host: &str, port: u16, file: &Path) -> Result<Offered, SshError> {
157    let pattern = pattern(host, port);
158    let keys = scan(ctx, host, port).await?;
159    let known = confirmed(ctx, file, &pattern).await?;
160    let shown = keys
161        .iter()
162        .filter_map(|k| {
163            Some(Shown {
164                algorithm: k.algorithm.clone(),
165                fingerprint: k.fingerprint()?,
166            })
167        })
168        .collect();
169    Ok(Offered {
170        state: state(&keys, &known),
171        keys: shown,
172        pattern,
173    })
174}
175
176/// Confirms the keys `host` offers on `port`, which were shown as `fingerprints`: read again,
177/// they must be exactly those (a server that changed its keys meanwhile is refused), then they
178/// replace any keys each of `files` had for it, the other hosts' kept.
179///
180/// # Errors
181///
182/// The keys couldn't be read, aren't the ones shown, or a file couldn't be written.
183pub async fn confirm(ctx: &Context, host: &str, port: u16, fingerprints: &[String], files: &[PathBuf]) -> Result<(), SshError> {
184    let pattern = pattern(host, port);
185    let keys = scan(ctx, host, port).await?;
186    let mut now: Vec<String> = keys.iter().filter_map(HostKey::fingerprint).collect();
187    let mut shown = fingerprints.to_vec();
188    now.sort();
189    shown.sort();
190    if now != shown {
191        return Err(SshError::Failed(format!("the SSH host keys of {host} changed while they were being confirmed")));
192    }
193    let mut lines = String::new();
194    for k in &keys {
195        for field in [pattern.as_str(), " ", &k.algorithm, " ", &k.blob, "\n"] {
196            lines.push_str(field);
197        }
198    }
199    for file in files {
200        forget(ctx, file, &pattern).await?;
201        if let Some(dir) = file.parent() {
202            std::fs::create_dir_all(dir)?;
203        }
204        let kept = match std::fs::read_to_string(file) {
205            Ok(text) if text.is_empty() || text.ends_with('\n') => text,
206            Ok(text) => text + "\n",
207            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
208            Err(e) => return Err(e.into()),
209        };
210        write_private(file, &(kept + &lines))?;
211    }
212    Ok(())
213}
214
215/// Writes `text` to `file`, readable by its owner only (on unix).
216fn write_private(file: &Path, text: &str) -> std::io::Result<()> {
217    std::fs::write(file, text)?;
218    #[cfg(unix)]
219    {
220        use std::os::unix::fs::PermissionsExt as _;
221        std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600))?;
222    }
223    Ok(())
224}
225
226/// Removes the keys `file` has for `pattern`, hashed or not (`ssh-keygen -R`, which keeps the
227/// previous file as `.old`).
228async fn forget(ctx: &Context, file: &Path, pattern: &str) -> Result<(), SshError> {
229    if !file.is_file() {
230        return Ok(());
231    }
232    let removed = run(ctx, "ssh-keygen", &["-R", pattern, "-f", &file.to_string_lossy()]).await?;
233    removed.output().map(drop).map_err(|f| SshError::Failed(f.to_string()))
234}
235
236/// The standard base64 alphabet.
237const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
238
239/// `text`, standard base64 (padded or not), decoded; none when it isn't base64.
240fn base64_decode(text: &str) -> Option<Vec<u8>> {
241    let digits: Vec<u8> = text
242        .trim_end_matches('=')
243        .bytes()
244        .map(|b| ALPHABET.iter().position(|a| *a == b).and_then(|p| u8::try_from(p).ok()))
245        .collect::<Option<_>>()?;
246    if digits.len() % 4 == 1 {
247        return None;
248    }
249    let mut out = Vec::with_capacity(digits.len() * 3 / 4);
250    for chunk in digits.chunks(4) {
251        let mut n: u32 = 0;
252        for (i, d) in chunk.iter().enumerate() {
253            n |= u32::from(*d) << (18 - 6 * i);
254        }
255        let bytes = n.to_be_bytes();
256        out.extend(bytes.iter().skip(1).take(chunk.len().saturating_sub(1)));
257    }
258    Some(out)
259}
260
261/// `bytes` as standard base64 without padding.
262fn base64_encode_unpadded(bytes: &[u8]) -> String {
263    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
264    for chunk in bytes.chunks(3) {
265        let mut n: u32 = 0;
266        for (i, b) in chunk.iter().enumerate() {
267            n |= u32::from(*b) << (16 - 8 * i);
268        }
269        for i in 0..=chunk.len() {
270            let index = (n >> (18 - 6 * i)) & 0x3f;
271            let digit = usize::try_from(index).ok().and_then(|at| ALPHABET.get(at)).copied().unwrap_or(b'A');
272            out.push(char::from(digit));
273        }
274    }
275    out
276}
277
278#[cfg(test)]
279mod tests;