use std::path::{Path, PathBuf};
use std::time::Duration;
use isothrum_runner::ProcessSpec;
use serde::Serialize;
use sha2::{Digest as _, Sha256};
use super::{SshError, safe_token};
use crate::Context;
const SCAN_LIMIT: Duration = Duration::from_secs(20);
const KEY_TYPES: &str = "ed25519,ecdsa,rsa";
#[derive(Debug, Clone, PartialEq, Eq)]
struct HostKey {
algorithm: String,
blob: String,
}
impl HostKey {
fn fingerprint(&self) -> Option<String> {
let raw = base64_decode(&self.blob)?;
Some(format!("SHA256:{}", base64_encode_unpadded(&Sha256::digest(raw))))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts-rs", ts(rename = "SshHostKey"))]
#[serde(rename_all = "camelCase")]
pub struct Shown {
pub algorithm: String,
pub fingerprint: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts-rs", ts(rename = "SshHostKeyState"))]
#[serde(rename_all = "camelCase")]
pub enum State {
New,
Confirmed,
Changed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts-rs", derive(ts_rs::TS))]
#[cfg_attr(feature = "ts-rs", ts(rename = "SshHostKeys"))]
#[serde(rename_all = "camelCase")]
pub struct Offered {
pub pattern: String,
pub keys: Vec<Shown>,
pub state: State,
}
#[must_use]
pub fn pattern(host: &str, port: u16) -> String {
if port == 22 { host.to_owned() } else { format!("[{host}]:{port}") }
}
fn keys_in(text: &str, pattern: &str) -> Vec<HostKey> {
text.lines()
.filter(|l| !l.starts_with('#') && !l.starts_with('@'))
.filter_map(|l| {
let mut fields = l.split_whitespace();
let (hosts, algorithm, blob) = (fields.next()?, fields.next()?, fields.next()?);
let ours = hosts.starts_with("|1|") || hosts.split(',').any(|n| n == pattern);
ours.then(|| HostKey {
algorithm: algorithm.to_owned(),
blob: blob.to_owned(),
})
})
.collect()
}
async fn run(ctx: &Context, program: &str, args: &[&str]) -> Result<isothrum_runner::Captured, SshError> {
Ok(ctx.probe_within(SCAN_LIMIT, &ProcessSpec::new(program, args.iter().copied())).await?)
}
async fn scan(ctx: &Context, host: &str, port: u16) -> Result<Vec<HostKey>, SshError> {
if !safe_token(host) {
return Err(SshError::Invalid("host"));
}
let port_arg = port.to_string();
let scanned = run(ctx, "ssh-keyscan", &["-T", "10", "-p", &port_arg, "-t", KEY_TYPES, host]).await?;
let out = scanned.output().map_err(|f| SshError::Failed(f.to_string()))?;
let mut keys = keys_in(&out, &pattern(host, port));
keys.dedup();
if keys.is_empty() {
return Err(SshError::Failed(format!("{host} offered no SSH host key on port {port}")));
}
Ok(keys)
}
async fn confirmed(ctx: &Context, file: &Path, pattern: &str) -> Result<Vec<HostKey>, SshError> {
if !file.is_file() {
return Ok(Vec::new());
}
let path = file.to_string_lossy();
let found = run(ctx, "ssh-keygen", &["-F", pattern, "-f", &path]).await?;
if found.success() {
return Ok(keys_in(&found.stdout.join("\n"), pattern));
}
if found.stderr_tail.iter().all(|l| l.trim().is_empty()) {
return Ok(Vec::new());
}
Err(SshError::Failed(found.reason()))
}
fn state(offered: &[HostKey], known: &[HostKey]) -> State {
match known {
[] => State::New,
known if known.iter().all(|k| offered.contains(k)) => State::Confirmed,
_ => State::Changed,
}
}
pub async fn offered(ctx: &Context, host: &str, port: u16, file: &Path) -> Result<Offered, SshError> {
let pattern = pattern(host, port);
let keys = scan(ctx, host, port).await?;
let known = confirmed(ctx, file, &pattern).await?;
let shown = keys
.iter()
.filter_map(|k| {
Some(Shown {
algorithm: k.algorithm.clone(),
fingerprint: k.fingerprint()?,
})
})
.collect();
Ok(Offered {
state: state(&keys, &known),
keys: shown,
pattern,
})
}
pub async fn confirm(ctx: &Context, host: &str, port: u16, fingerprints: &[String], files: &[PathBuf]) -> Result<(), SshError> {
let pattern = pattern(host, port);
let keys = scan(ctx, host, port).await?;
let mut now: Vec<String> = keys.iter().filter_map(HostKey::fingerprint).collect();
let mut shown = fingerprints.to_vec();
now.sort();
shown.sort();
if now != shown {
return Err(SshError::Failed(format!("the SSH host keys of {host} changed while they were being confirmed")));
}
let mut lines = String::new();
for k in &keys {
for field in [pattern.as_str(), " ", &k.algorithm, " ", &k.blob, "\n"] {
lines.push_str(field);
}
}
for file in files {
forget(ctx, file, &pattern).await?;
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir)?;
}
let kept = match std::fs::read_to_string(file) {
Ok(text) if text.is_empty() || text.ends_with('\n') => text,
Ok(text) => text + "\n",
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e.into()),
};
write_private(file, &(kept + &lines))?;
}
Ok(())
}
fn write_private(file: &Path, text: &str) -> std::io::Result<()> {
std::fs::write(file, text)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
async fn forget(ctx: &Context, file: &Path, pattern: &str) -> Result<(), SshError> {
if !file.is_file() {
return Ok(());
}
let removed = run(ctx, "ssh-keygen", &["-R", pattern, "-f", &file.to_string_lossy()]).await?;
removed.output().map(drop).map_err(|f| SshError::Failed(f.to_string()))
}
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
fn base64_decode(text: &str) -> Option<Vec<u8>> {
let digits: Vec<u8> = text
.trim_end_matches('=')
.bytes()
.map(|b| ALPHABET.iter().position(|a| *a == b).and_then(|p| u8::try_from(p).ok()))
.collect::<Option<_>>()?;
if digits.len() % 4 == 1 {
return None;
}
let mut out = Vec::with_capacity(digits.len() * 3 / 4);
for chunk in digits.chunks(4) {
let mut n: u32 = 0;
for (i, d) in chunk.iter().enumerate() {
n |= u32::from(*d) << (18 - 6 * i);
}
let bytes = n.to_be_bytes();
out.extend(bytes.iter().skip(1).take(chunk.len().saturating_sub(1)));
}
Some(out)
}
fn base64_encode_unpadded(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let mut n: u32 = 0;
for (i, b) in chunk.iter().enumerate() {
n |= u32::from(*b) << (16 - 8 * i);
}
for i in 0..=chunk.len() {
let index = (n >> (18 - 6 * i)) & 0x3f;
let digit = usize::try_from(index).ok().and_then(|at| ALPHABET.get(at)).copied().unwrap_or(b'A');
out.push(char::from(digit));
}
}
out
}
#[cfg(test)]
mod tests;