S027: ssh config parser and known_hosts checking
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
parent
71bd840ca0
commit
1c1817f7ed
10 changed files with 677 additions and 7 deletions
50
Cargo.lock
generated
50
Cargo.lock
generated
|
|
@ -762,6 +762,12 @@ dependencies = [
|
|||
"hashbrown 0.16.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "codespan-reporting"
|
||||
version = "0.13.1"
|
||||
|
|
@ -938,6 +944,15 @@ dependencies = [
|
|||
"windows-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.5"
|
||||
|
|
@ -1020,6 +1035,15 @@ dependencies = [
|
|||
"dtor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cursor-icon"
|
||||
version = "1.2.0"
|
||||
|
|
@ -1076,6 +1100,7 @@ dependencies = [
|
|||
"block-buffer",
|
||||
"const-oid",
|
||||
"crypto-common",
|
||||
"ctutils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
@ -1855,6 +1880,15 @@ version = "0.4.3"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "htmlparser"
|
||||
version = "0.2.1"
|
||||
|
|
@ -4580,6 +4614,17 @@ dependencies = [
|
|||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
|
|
@ -5531,6 +5576,11 @@ version = "0.1.0"
|
|||
[[package]]
|
||||
name = "tunal-net"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"hmac",
|
||||
"sha1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tunal-player"
|
||||
|
|
|
|||
|
|
@ -30,3 +30,6 @@ cpal = "0.18"
|
|||
rubato = "0.16"
|
||||
rtrb = "0.4"
|
||||
nusb = "0.2"
|
||||
base64 = "0.23"
|
||||
hmac = "0.13"
|
||||
sha1 = "0.11"
|
||||
|
|
|
|||
|
|
@ -10,12 +10,12 @@ Hosts from `~/.ssh/config` and host-key checking against `known_hosts` plus Tuna
|
|||
docs/DECISIONS.md D-020; CLAUDE.md §1 (never modify ~/.ssh).
|
||||
|
||||
## Steps
|
||||
- [ ] Config parser: Host (concrete aliases listed; wildcards/negations used only for matching), HostName, Port, User, IdentityFile (`~` expansion, several), IdentitiesOnly, Include (globs, relative to ~/.ssh); Match blocks skipped; ProxyJump/ProxyCommand flagged unsupported.
|
||||
- [ ] Resolve an alias with first-match-wins semantics.
|
||||
- [ ] known_hosts: plain and hashed (`|1|` HMAC-SHA1) entries, `[host]:port`, `@revoked`; `@cert-authority` ignored; result Match / Mismatch / Unknown / Revoked.
|
||||
- [ ] Accepted keys are appended to `$XDG_CONFIG_HOME/tunal/known_hosts` (never ~/.ssh), read together with `~/.ssh/known_hosts`.
|
||||
- [ ] Example parsing sample files in the scratchpad (HOME overridden).
|
||||
- [ ] PROGRESS entry, INDEX line, commit `S027: …`
|
||||
- [x] Config parser: Host (concrete aliases listed; wildcards/negations used only for matching), HostName, Port, User, IdentityFile (`~` expansion, several), IdentitiesOnly, Include (globs, relative to ~/.ssh); Match blocks skipped; ProxyJump/ProxyCommand flagged unsupported.
|
||||
- [x] Resolve an alias with first-match-wins semantics.
|
||||
- [x] known_hosts: plain and hashed (`|1|` HMAC-SHA1) entries, `[host]:port`, `@revoked`; `@cert-authority` ignored; result Match / Mismatch / Unknown / Revoked.
|
||||
- [x] Accepted keys are appended to `$XDG_CONFIG_HOME/tunal/known_hosts` (never ~/.ssh), read together with `~/.ssh/known_hosts`.
|
||||
- [x] Example parsing sample files in the scratchpad (HOME overridden).
|
||||
- [x] PROGRESS entry, INDEX line, commit `S027: …`
|
||||
|
||||
## End criteria
|
||||
- `cargo build --workspace`, `cargo clippy --workspace --all-targets -- -D warnings` and `cargo fmt --check` pass.
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ Tracker: https://claude.ai/artifact/4X8YCk3cQjUGyuyCqGuU7v
|
|||
|
||||
## 10 Network
|
||||
|
||||
- [ ] [S027 — ssh config and known_hosts](10%20Network/S027-ssh-config-known-hosts.md) · Sonnet high
|
||||
- [x] [S027 — ssh config and known_hosts](10%20Network/S027-ssh-config-known-hosts.md) · Sonnet high
|
||||
- [ ] [S028 — SFTP location](10%20Network/S028-sftp-location.md) · Opus high
|
||||
- [ ] [S029 — SFTP connections in the UI](10%20Network/S029-sftp-ui.md) · Opus high
|
||||
|
||||
|
|
|
|||
|
|
@ -4,3 +4,8 @@ version.workspace = true
|
|||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
base64.workspace = true
|
||||
hmac.workspace = true
|
||||
sha1.workspace = true
|
||||
|
|
|
|||
48
crates/tunal-net/examples/ssh_smoke.rs
Normal file
48
crates/tunal-net/examples/ssh_smoke.rs
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
//! Smoke run: `HOME=<dir> XDG_CONFIG_HOME=<dir>/xdg cargo run -p tunal-net --example ssh_smoke -- <key1> <key2>`
|
||||
//! Lists hosts of `$HOME/.ssh/config`, resolves some aliases and checks known_hosts entries.
|
||||
//! Appends one accepted key to the own file under XDG_CONFIG_HOME (refuses when that is not under HOME).
|
||||
use tunal_net::known_hosts::{self, KnownHosts};
|
||||
use tunal_net::ssh_config::SshConfig;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let (k1, k2) = (&args[0], &args[1]);
|
||||
let home = std::env::var("HOME").unwrap();
|
||||
let xdg = std::env::var("XDG_CONFIG_HOME").unwrap();
|
||||
assert!(
|
||||
xdg.starts_with(&home),
|
||||
"XDG_CONFIG_HOME must be inside HOME"
|
||||
);
|
||||
|
||||
let cfg = SshConfig::load_default();
|
||||
println!("hosts: {:?}", cfg.hosts());
|
||||
for a in ["nas", "work", "dev-1", "dev-old", "other"] {
|
||||
println!("{:#?}", cfg.resolve(a));
|
||||
}
|
||||
|
||||
let kh = KnownHosts::load_default();
|
||||
for (h, p, key) in [
|
||||
("plain.example.com", 22, k1),
|
||||
("plain.example.com", 22, k2),
|
||||
("hashed.example.com", 22, k1),
|
||||
("nas.lan", 2222, k1),
|
||||
("nas.lan", 22, k1),
|
||||
("bad.example.com", 22, k2),
|
||||
("x.ca.example", 22, k1),
|
||||
] {
|
||||
println!("{h}:{p} -> {:?}", kh.check(h, p, "ssh-ed25519", key));
|
||||
}
|
||||
let own = known_hosts::own_file().unwrap();
|
||||
known_hosts::accept_key(&own, "new.example.com", 22, "ssh-ed25519", k2).unwrap();
|
||||
let kh = KnownHosts::load_default();
|
||||
println!(
|
||||
"after accept: {:?}",
|
||||
kh.check("new.example.com", 22, "ssh-ed25519", k2)
|
||||
);
|
||||
println!("own file: {}", std::fs::read_to_string(own).unwrap().trim());
|
||||
let bad = std::path::Path::new(&home).join(".ssh/known_hosts");
|
||||
println!(
|
||||
"write under ~/.ssh: {:?}",
|
||||
known_hosts::accept_key(&bad, "x", 22, "t", "k").map_err(|e| e.kind())
|
||||
);
|
||||
}
|
||||
216
crates/tunal-net/src/known_hosts.rs
Normal file
216
crates/tunal-net/src/known_hosts.rs
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
//! 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,
|
||||
})
|
||||
}
|
||||
|
|
@ -1 +1,27 @@
|
|||
//! SFTP locations, ssh config hosts and known_hosts.
|
||||
|
||||
pub mod known_hosts;
|
||||
pub mod ssh_config;
|
||||
|
||||
/// Shell-style glob match (`*`, `?`) on bytes, as used by ssh patterns.
|
||||
pub(crate) fn glob_match(pattern: &str, text: &str) -> bool {
|
||||
let (p, t) = (pattern.as_bytes(), text.as_bytes());
|
||||
let (mut pi, mut ti) = (0, 0);
|
||||
let mut star: Option<(usize, usize)> = None;
|
||||
while ti < t.len() {
|
||||
if pi < p.len() && (p[pi] == b'?' || p[pi] == t[ti]) {
|
||||
pi += 1;
|
||||
ti += 1;
|
||||
} else if pi < p.len() && p[pi] == b'*' {
|
||||
star = Some((pi, ti));
|
||||
pi += 1;
|
||||
} else if let Some((sp, st)) = star {
|
||||
pi = sp + 1;
|
||||
ti = st + 1;
|
||||
star = Some((sp, st + 1));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
p[pi..].iter().all(|&c| c == b'*')
|
||||
}
|
||||
|
|
|
|||
315
crates/tunal-net/src/ssh_config.rs
Normal file
315
crates/tunal-net/src/ssh_config.rs
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
//! `~/.ssh/config` parser (read only): hosts, resolution, Include.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::glob_match;
|
||||
|
||||
const MAX_INCLUDE_DEPTH: usize = 8;
|
||||
|
||||
/// Options of one `Host` block (or the resolved result of several).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct HostOptions {
|
||||
pub host_name: Option<String>,
|
||||
pub port: Option<u16>,
|
||||
pub user: Option<String>,
|
||||
pub identity_files: Vec<PathBuf>,
|
||||
pub identities_only: Option<bool>,
|
||||
/// ProxyJump or ProxyCommand set: Tunal cannot connect through it.
|
||||
pub unsupported_proxy: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct Block {
|
||||
patterns: Vec<String>,
|
||||
options: HostOptions,
|
||||
}
|
||||
|
||||
/// A parsed config: `Host` blocks in file order (after Include expansion).
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct SshConfig {
|
||||
blocks: Vec<Block>,
|
||||
}
|
||||
|
||||
/// An alias ready to connect to.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Resolved {
|
||||
pub alias: String,
|
||||
pub host_name: String,
|
||||
pub port: u16,
|
||||
pub user: Option<String>,
|
||||
pub identity_files: Vec<PathBuf>,
|
||||
pub identities_only: bool,
|
||||
pub unsupported_proxy: bool,
|
||||
}
|
||||
|
||||
impl SshConfig {
|
||||
/// Reads `~/.ssh/config`; missing or unreadable = empty config.
|
||||
pub fn load_default() -> Self {
|
||||
match ssh_dir() {
|
||||
Some(dir) => Self::load(&dir.join("config"), &dir),
|
||||
None => Self::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads `file`; relative `Include` paths resolve against `ssh_dir`.
|
||||
pub fn load(file: &Path, ssh_dir: &Path) -> Self {
|
||||
let mut config = Self::default();
|
||||
let mut state = Parser::default();
|
||||
state.read_file(file, ssh_dir, 0, &mut config);
|
||||
state.finish(&mut config);
|
||||
config
|
||||
}
|
||||
|
||||
/// Parses config text (Include resolves against `ssh_dir`).
|
||||
pub fn parse(text: &str, ssh_dir: &Path) -> Self {
|
||||
let mut config = Self::default();
|
||||
let mut state = Parser::default();
|
||||
state.read_text(text, ssh_dir, 0, &mut config);
|
||||
state.finish(&mut config);
|
||||
config
|
||||
}
|
||||
|
||||
/// Concrete aliases (no wildcard, no negation), in file order, unique.
|
||||
pub fn hosts(&self) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for block in &self.blocks {
|
||||
for p in &block.patterns {
|
||||
if !p.starts_with('!') && !p.contains(['*', '?']) && !out.contains(p) {
|
||||
out.push(p.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// First value wins per option; lists (identity files) collect from all matches.
|
||||
pub fn resolve(&self, alias: &str) -> Resolved {
|
||||
let mut o = HostOptions::default();
|
||||
for block in self.blocks.iter().filter(|b| matches(&b.patterns, alias)) {
|
||||
let b = &block.options;
|
||||
o.host_name = o.host_name.or_else(|| b.host_name.clone());
|
||||
o.port = o.port.or(b.port);
|
||||
o.user = o.user.or_else(|| b.user.clone());
|
||||
o.identities_only = o.identities_only.or(b.identities_only);
|
||||
o.unsupported_proxy |= b.unsupported_proxy;
|
||||
for f in &b.identity_files {
|
||||
if !o.identity_files.contains(f) {
|
||||
o.identity_files.push(f.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Resolved {
|
||||
alias: alias.to_string(),
|
||||
host_name: o
|
||||
.host_name
|
||||
.map(|h| h.replace("%h", alias))
|
||||
.unwrap_or_else(|| alias.to_string()),
|
||||
port: o.port.unwrap_or(22),
|
||||
user: o.user,
|
||||
identity_files: o.identity_files,
|
||||
identities_only: o.identities_only.unwrap_or(false),
|
||||
unsupported_proxy: o.unsupported_proxy,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `~/.ssh` (HOME), if known.
|
||||
pub fn ssh_dir() -> Option<PathBuf> {
|
||||
std::env::var_os("HOME")
|
||||
.filter(|h| !h.is_empty())
|
||||
.map(|h| PathBuf::from(h).join(".ssh"))
|
||||
}
|
||||
|
||||
/// A negated match wins over any positive one.
|
||||
fn matches(patterns: &[String], alias: &str) -> bool {
|
||||
let mut hit = false;
|
||||
for p in patterns {
|
||||
match p.strip_prefix('!') {
|
||||
Some(neg) if glob_match(neg, alias) => return false,
|
||||
Some(_) => {}
|
||||
None => hit |= glob_match(p, alias),
|
||||
}
|
||||
}
|
||||
hit
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Parser {
|
||||
/// Block being filled; `None` before the first Host line (global options).
|
||||
current: Option<Block>,
|
||||
/// Inside a `Match` block: options are skipped.
|
||||
skipping: bool,
|
||||
/// Global options before any Host line apply to every host.
|
||||
global: HostOptions,
|
||||
}
|
||||
|
||||
impl Parser {
|
||||
fn finish(&mut self, config: &mut SshConfig) {
|
||||
self.flush(config);
|
||||
let global = std::mem::take(&mut self.global);
|
||||
if global != HostOptions::default() {
|
||||
config.blocks.insert(
|
||||
0,
|
||||
Block {
|
||||
patterns: vec!["*".into()],
|
||||
options: global,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn flush(&mut self, config: &mut SshConfig) {
|
||||
if let Some(b) = self.current.take() {
|
||||
config.blocks.push(b);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_file(&mut self, file: &Path, ssh_dir: &Path, depth: usize, config: &mut SshConfig) {
|
||||
if let Ok(bytes) = std::fs::read(file) {
|
||||
self.read_text(&String::from_utf8_lossy(&bytes), ssh_dir, depth, config);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_text(&mut self, text: &str, ssh_dir: &Path, depth: usize, config: &mut SshConfig) {
|
||||
for line in text.lines() {
|
||||
let Some((key, args)) = split_line(line) else {
|
||||
continue;
|
||||
};
|
||||
let key = key.to_ascii_lowercase();
|
||||
match key.as_str() {
|
||||
"host" => {
|
||||
self.flush(config);
|
||||
self.skipping = false;
|
||||
self.current = Some(Block {
|
||||
patterns: args,
|
||||
options: HostOptions::default(),
|
||||
});
|
||||
}
|
||||
"match" => {
|
||||
self.flush(config);
|
||||
self.skipping = true;
|
||||
}
|
||||
"include" => {
|
||||
// Include inside a Match block is skipped with the block.
|
||||
if depth >= MAX_INCLUDE_DEPTH || self.skipping {
|
||||
continue;
|
||||
}
|
||||
for pat in args {
|
||||
for file in expand_include(&pat, ssh_dir) {
|
||||
self.read_file(&file, ssh_dir, depth + 1, config);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ if self.skipping => {}
|
||||
_ => {
|
||||
let opts = match self.current.as_mut() {
|
||||
Some(b) => &mut b.options,
|
||||
None => &mut self.global,
|
||||
};
|
||||
apply(opts, &key, &args);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(o: &mut HostOptions, key: &str, args: &[String]) {
|
||||
let Some(first) = args.first() else { return };
|
||||
match key {
|
||||
"hostname" => o.host_name = o.host_name.take().or_else(|| Some(first.clone())),
|
||||
"port" => o.port = o.port.or(first.parse().ok()),
|
||||
"user" => o.user = o.user.take().or_else(|| Some(first.clone())),
|
||||
"identityfile" => {
|
||||
let p = expand_tilde(first);
|
||||
if !o.identity_files.contains(&p) {
|
||||
o.identity_files.push(p);
|
||||
}
|
||||
}
|
||||
"identitiesonly" => o.identities_only = o.identities_only.or(parse_bool(first)),
|
||||
"proxyjump" | "proxycommand" if !first.eq_ignore_ascii_case("none") => {
|
||||
o.unsupported_proxy = true
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_bool(s: &str) -> Option<bool> {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"yes" | "true" => Some(true),
|
||||
"no" | "false" => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn expand_tilde(s: &str) -> PathBuf {
|
||||
if (s == "~" || s.starts_with("~/"))
|
||||
&& let Some(home) = std::env::var_os("HOME")
|
||||
{
|
||||
return PathBuf::from(home).join(s.trim_start_matches('~').trim_start_matches('/'));
|
||||
}
|
||||
PathBuf::from(s)
|
||||
}
|
||||
|
||||
/// Splits `Key value`, `Key=value` and quoted values; comments and blanks give `None`.
|
||||
fn split_line(line: &str) -> Option<(String, Vec<String>)> {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
return None;
|
||||
}
|
||||
let key_end = line.find(|c: char| c.is_whitespace() || c == '=')?;
|
||||
let key = line[..key_end].to_string();
|
||||
let rest = line[key_end..]
|
||||
.trim_start()
|
||||
.trim_start_matches('=')
|
||||
.trim_start();
|
||||
let mut args = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut quoted = false;
|
||||
let mut has = false;
|
||||
for c in rest.chars() {
|
||||
match c {
|
||||
'"' => {
|
||||
quoted = !quoted;
|
||||
has = true;
|
||||
}
|
||||
'#' if !quoted && !has && cur.is_empty() => break,
|
||||
c if c.is_whitespace() && !quoted => {
|
||||
if has || !cur.is_empty() {
|
||||
args.push(std::mem::take(&mut cur));
|
||||
has = false;
|
||||
}
|
||||
}
|
||||
c => cur.push(c),
|
||||
}
|
||||
}
|
||||
if has || !cur.is_empty() {
|
||||
args.push(cur);
|
||||
}
|
||||
Some((key, args))
|
||||
}
|
||||
|
||||
/// Include path with `~` and globs; relative paths resolve against `ssh_dir`. Sorted.
|
||||
fn expand_include(pattern: &str, ssh_dir: &Path) -> Vec<PathBuf> {
|
||||
let path = expand_tilde(pattern);
|
||||
let path = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
ssh_dir.join(path)
|
||||
};
|
||||
let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if !name.contains(['*', '?']) {
|
||||
return vec![path];
|
||||
}
|
||||
let mut found: Vec<PathBuf> = std::fs::read_dir(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.filter(|e| e.file_name().to_str().is_some_and(|n| glob_match(name, n)))
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.is_file())
|
||||
.collect();
|
||||
found.sort();
|
||||
found
|
||||
}
|
||||
|
|
@ -137,5 +137,12 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done,
|
|||
- Not done: ripple/morph motion not watched (single frames); the software renderer draws stroked paths unevenly, so the wave is a filled band. Settings page list still plain rows.
|
||||
- Later: tune clover depth (reads like a plus); shaped rows in the settings nav.
|
||||
|
||||
## S027 — ssh config and known_hosts
|
||||
- Done: `tunal-net` `ssh_config::SshConfig` (`load_default()`, `load(file, ssh_dir)`, `parse(text, ssh_dir)`, `hosts()` = concrete aliases in file order, `resolve(alias) -> Resolved {alias, host_name, port (22), user, identity_files, identities_only, unsupported_proxy}`): first value wins per option, identity files collect from all matching blocks, negated patterns win, `Match` blocks skipped, `Include` (globs, `~`, relative to ~/.ssh, depth 8), ProxyJump/ProxyCommand set `unsupported_proxy`. `known_hosts::KnownHosts` (`load_default()` reads ~/.ssh/known_hosts + own file, `add_file`, `add_text`, `check(host, port, key_type, key_b64) -> HostCheck::{Match, Mismatch, Unknown, Revoked}`): plain (comma lists, wildcards, `!`), hashed `|1|` HMAC-SHA1, `[host]:port`, `@revoked`, `@cert-authority` ignored. `own_file()` = `$XDG_CONFIG_HOME/tunal/known_hosts`; `accept_key(file, host, port, key_type, key_b64)` appends one line (creates dirs) and refuses paths under ~/.ssh.
|
||||
- SFTP/UI use: connect → `resolve(alias)`; after the SSH handshake `check(...)`: Unknown → ask user, then `accept_key(own_file()?, ...)`; Mismatch/Revoked → refuse. Key blob = base64 as in a known_hosts line.
|
||||
- Deps (workspace): base64 0.23, hmac 0.13, sha1 0.11.
|
||||
- Verified: workspace build, clippy -D warnings, fmt --check; `cargo run -p tunal-net --example ssh_smoke` with HOME overridden: Include file listed, first-match/negation resolution, plain + hashed + port + revoked + ca entries, accept then Match, write under ~/.ssh refused, sample ~/.ssh unchanged.
|
||||
- Not done: no real ~/.ssh read; `Match` conditions not evaluated (block skipped); `%h`-style tokens only for HostName; no host-key algorithm negotiation preference.
|
||||
|
||||
## Later
|
||||
-
|
||||
|
|
|
|||
Loading…
Reference in a new issue