isothrum_machine/place/ssh/
known_hosts.rs1use 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
17const SCAN_LIMIT: Duration = Duration::from_secs(20);
19
20const KEY_TYPES: &str = "ed25519,ecdsa,rsa";
22
23#[derive(Debug, Clone, PartialEq, Eq)]
25struct HostKey {
26 algorithm: String,
28 blob: String,
30}
31
32impl HostKey {
33 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#[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 pub algorithm: String,
48 pub fingerprint: String,
50}
51
52#[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 New,
60 Confirmed,
62 Changed,
64}
65
66#[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 pub pattern: String,
74 pub keys: Vec<Shown>,
76 pub state: State,
78}
79
80#[must_use]
82pub fn pattern(host: &str, port: u16) -> String {
83 if port == 22 { host.to_owned() } else { format!("[{host}]:{port}") }
84}
85
86fn 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 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
103async 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
108async 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
124async 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 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
141fn 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
150pub 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
176pub 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
215fn 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
226async 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
236const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
238
239fn 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
261fn 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;