216 lines
6.5 KiB
Rust
216 lines
6.5 KiB
Rust
//! known_hosts reading (`~/.ssh/known_hosts`, read only) plus Tunal's own file.
|
|
//!
|
|
//! Accepted keys are appended to `$XDG_CONFIG_HOME/tunal/known_hosts` only (D-020).
|
|
|
|
use std::fs::{self, OpenOptions};
|
|
use std::io::{self, Write};
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use base64::Engine;
|
|
use base64::engine::general_purpose::STANDARD;
|
|
use hmac::{Hmac, KeyInit, Mac};
|
|
use sha1::Sha1;
|
|
|
|
use crate::glob_match;
|
|
|
|
/// Result of checking a server key.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum HostCheck {
|
|
/// Host listed with this key.
|
|
Match,
|
|
/// Host listed, but only with other key(s) of this type: possible attack.
|
|
Mismatch,
|
|
/// Host not listed (or listed only with other key types).
|
|
Unknown,
|
|
/// Key is marked `@revoked`.
|
|
Revoked,
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
enum HostSpec {
|
|
Patterns(Vec<String>),
|
|
Hashed { salt: Vec<u8>, hash: Vec<u8> },
|
|
}
|
|
|
|
#[derive(Debug, Clone)]
|
|
struct Entry {
|
|
revoked: bool,
|
|
host: HostSpec,
|
|
key_type: String,
|
|
/// Base64 key blob as written in the file.
|
|
key: String,
|
|
}
|
|
|
|
/// Entries from every known_hosts file read.
|
|
#[derive(Debug, Clone, Default)]
|
|
pub struct KnownHosts {
|
|
entries: Vec<Entry>,
|
|
}
|
|
|
|
impl KnownHosts {
|
|
/// `~/.ssh/known_hosts` and `$XDG_CONFIG_HOME/tunal/known_hosts`; missing files are empty.
|
|
pub fn load_default() -> Self {
|
|
let mut kh = Self::default();
|
|
if let Some(dir) = crate::ssh_config::ssh_dir() {
|
|
kh.add_file(&dir.join("known_hosts"));
|
|
}
|
|
if let Some(own) = own_file() {
|
|
kh.add_file(&own);
|
|
}
|
|
kh
|
|
}
|
|
|
|
pub fn add_file(&mut self, file: &Path) {
|
|
if let Ok(bytes) = fs::read(file) {
|
|
self.add_text(&String::from_utf8_lossy(&bytes));
|
|
}
|
|
}
|
|
|
|
pub fn add_text(&mut self, text: &str) {
|
|
self.entries.extend(text.lines().filter_map(parse_line));
|
|
}
|
|
|
|
/// Checks `key` (base64 blob, as in the file) of type `key_type` (e.g. `ssh-ed25519`)
|
|
/// for `host` on `port`.
|
|
pub fn check(&self, host: &str, port: u16, key_type: &str, key: &str) -> HostCheck {
|
|
let names = host_names(host, port);
|
|
let mut mismatch = false;
|
|
for e in self.entries.iter().filter(|e| e.host_matches(&names)) {
|
|
if e.key_type != key_type {
|
|
continue;
|
|
}
|
|
if e.key == key {
|
|
return if e.revoked {
|
|
HostCheck::Revoked
|
|
} else {
|
|
HostCheck::Match
|
|
};
|
|
}
|
|
mismatch |= !e.revoked;
|
|
}
|
|
if mismatch {
|
|
HostCheck::Mismatch
|
|
} else {
|
|
HostCheck::Unknown
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `$XDG_CONFIG_HOME/tunal/known_hosts` (falls back to `~/.config`).
|
|
pub fn own_file() -> Option<PathBuf> {
|
|
let base = std::env::var_os("XDG_CONFIG_HOME")
|
|
.filter(|v| !v.is_empty())
|
|
.map(PathBuf::from)
|
|
.or_else(|| {
|
|
std::env::var_os("HOME")
|
|
.filter(|h| !h.is_empty())
|
|
.map(|h| PathBuf::from(h).join(".config"))
|
|
})?;
|
|
Some(base.join("tunal").join("known_hosts"))
|
|
}
|
|
|
|
/// Appends an accepted key to `file` (Tunal's own file; refuses anything under `~/.ssh`).
|
|
pub fn accept_key(file: &Path, host: &str, port: u16, key_type: &str, key: &str) -> io::Result<()> {
|
|
if let Some(ssh) = crate::ssh_config::ssh_dir()
|
|
&& file.starts_with(&ssh)
|
|
{
|
|
return Err(io::Error::new(
|
|
io::ErrorKind::PermissionDenied,
|
|
"refusing to write under ~/.ssh",
|
|
));
|
|
}
|
|
if let Some(dir) = file.parent() {
|
|
fs::create_dir_all(dir)?;
|
|
}
|
|
let name = host_names(host, port).swap_remove(0);
|
|
let mut f = OpenOptions::new().create(true).append(true).open(file)?;
|
|
// Keep the entry on its own line even if the file lacks a final newline.
|
|
let needs_nl = fs::read(file)
|
|
.ok()
|
|
.and_then(|b| b.last().copied())
|
|
.is_some_and(|c| c != b'\n');
|
|
writeln!(
|
|
f,
|
|
"{}{name} {key_type} {key}",
|
|
if needs_nl { "\n" } else { "" }
|
|
)
|
|
}
|
|
|
|
/// Names a host is listed under: `host` for port 22, else `[host]:port`.
|
|
/// The first is the one to write; a port-22 host also matches `[host]:22`.
|
|
fn host_names(host: &str, port: u16) -> Vec<String> {
|
|
let host = host.to_ascii_lowercase();
|
|
if port == 22 {
|
|
vec![host.clone(), format!("[{host}]:22")]
|
|
} else {
|
|
vec![format!("[{host}]:{port}")]
|
|
}
|
|
}
|
|
|
|
impl Entry {
|
|
fn host_matches(&self, names: &[String]) -> bool {
|
|
match &self.host {
|
|
HostSpec::Hashed { salt, hash } => names.iter().any(|n| {
|
|
let Ok(mut mac) = Hmac::<Sha1>::new_from_slice(salt) else {
|
|
return false;
|
|
};
|
|
mac.update(n.as_bytes());
|
|
mac.finalize().into_bytes().as_slice() == hash.as_slice()
|
|
}),
|
|
HostSpec::Patterns(pats) => {
|
|
let mut hit = false;
|
|
for p in pats {
|
|
match p.strip_prefix('!') {
|
|
Some(neg)
|
|
if names
|
|
.iter()
|
|
.any(|n| glob_match(&neg.to_ascii_lowercase(), n)) =>
|
|
{
|
|
return false;
|
|
}
|
|
Some(_) => {}
|
|
None => hit |= names.iter().any(|n| glob_match(&p.to_ascii_lowercase(), n)),
|
|
}
|
|
}
|
|
hit
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn parse_line(line: &str) -> Option<Entry> {
|
|
let line = line.trim();
|
|
if line.is_empty() || line.starts_with('#') {
|
|
return None;
|
|
}
|
|
let mut parts = line.split_whitespace();
|
|
let mut first = parts.next()?;
|
|
let mut revoked = false;
|
|
match first {
|
|
"@revoked" => {
|
|
revoked = true;
|
|
first = parts.next()?;
|
|
}
|
|
"@cert-authority" => return None,
|
|
_ if first.starts_with('@') => return None,
|
|
_ => {}
|
|
}
|
|
let key_type = parts.next()?.to_string();
|
|
let key = parts.next()?.to_string();
|
|
let host = match first.strip_prefix("|1|") {
|
|
Some(rest) => {
|
|
let (salt, hash) = rest.split_once('|')?;
|
|
HostSpec::Hashed {
|
|
salt: STANDARD.decode(salt).ok()?,
|
|
hash: STANDARD.decode(hash).ok()?,
|
|
}
|
|
}
|
|
None => HostSpec::Patterns(first.split(',').map(str::to_string).collect()),
|
|
};
|
|
Some(Entry {
|
|
revoked,
|
|
host,
|
|
key_type,
|
|
key,
|
|
})
|
|
}
|