Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 146 additions & 6 deletions crabport-ssh/src/known_hosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@
use std::collections::HashSet;
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard};

/// A single known_hosts entry.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -82,6 +83,23 @@ pub enum LookupResult {
},
}

/// Serializes read-modify-write cycles across every handle in the process.
///
/// Each SSH connection opens its own [`KnownHosts`] and the Settings window
/// opens another, so without this a concurrent TOFU `add` could read the file
/// before a `remove` rewrote it and then write the deleted entry back. The
/// lock is process-local — an external editor still races, which is why the
/// file keeps its "do not edit while the app is running" header.
static STORE_LOCK: Mutex<()> = Mutex::new(());

fn store_lock() -> MutexGuard<'static, ()> {
// A panic while holding the lock must not disable known_hosts for the
// rest of the process; the data is a plain file, so recovering is safe.
STORE_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// Persistent known_hosts store backed by a plain text file.
pub struct KnownHosts {
path: PathBuf,
Expand All @@ -97,11 +115,22 @@ impl KnownHosts {
})
}

/// Where [`Self::open`] stores the file, whether or not it exists yet.
/// Lets the UI show / reveal the path before the first host is trusted.
pub fn default_path() -> std::io::Result<PathBuf> {
Ok(default_data_dir()?.join("known_hosts"))
}

/// Open at an explicit path (mainly for tests).
pub fn open_at(path: PathBuf) -> Self {
Self { path }
}

/// The file backing this store.
pub fn path(&self) -> &Path {
&self.path
}

/// Read all entries currently in the file.
fn read_all(&self) -> std::io::Result<HashSet<KnownHost>> {
let mut set = HashSet::new();
Expand Down Expand Up @@ -158,11 +187,49 @@ impl KnownHosts {
}
}

/// Every stored entry, sorted by host, port and algorithm.
pub fn list(&self) -> std::io::Result<Vec<KnownHost>> {
let mut entries: Vec<KnownHost> = self.read_all()?.into_iter().collect();
entries.sort_by(|a, b| {
a.host
.cmp(&b.host)
.then(a.port.cmp(&b.port))
.then(a.algo.cmp(&b.algo))
.then(a.fingerprint.cmp(&b.fingerprint))
});
Ok(entries)
}

/// Persist a new trusted entry. Rewrites the file atomically.
pub fn add(&self, entry: &KnownHost) -> std::io::Result<()> {
let _guard = store_lock();
let mut all = self.read_all()?;
all.insert(entry.clone());
self.write_all(&all)
}

/// Remove one trusted key. Returns `false` when it was not stored (the
/// caller may be looking at a stale snapshot).
pub fn remove(&self, entry: &KnownHost) -> std::io::Result<bool> {
let _guard = store_lock();
let mut all = self.read_all()?;
if !all.remove(entry) {
return Ok(false);
}
self.write_all(&all)?;
Ok(true)
}

/// Forget every trusted key. Leaves the file in place (header only) so
/// the next connect starts from a clean TOFU state.
pub fn clear(&self) -> std::io::Result<()> {
let _guard = store_lock();
self.write_all(&HashSet::new())
}

/// Atomically rewrite the store with `all`. Callers must hold
/// [`STORE_LOCK`].
fn write_all(&self, all: &HashSet<KnownHost>) -> std::io::Result<()> {
if let Some(parent) = self.path.parent() {
fs::create_dir_all(parent)?;
}
Expand Down Expand Up @@ -235,20 +302,25 @@ mod tests {

// Unknown host:port → NotFound (ask the user).
assert_eq!(
kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:aaa").unwrap(),
kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:aaa")
.unwrap(),
LookupResult::NotFound
);

// Trust it, then the same key matches.
kh.add(&entry("example.com", 22, "ssh-ed25519", "SHA256:aaa"))
.unwrap();
assert_eq!(
kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:aaa").unwrap(),
kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:aaa")
.unwrap(),
LookupResult::Matched
);

// Same host, different key → Mismatched with the stored expectation.
match kh.lookup("example.com", 22, "ssh-ed25519", "SHA256:EVIL").unwrap() {
match kh
.lookup("example.com", 22, "ssh-ed25519", "SHA256:EVIL")
.unwrap()
{
LookupResult::Mismatched {
expected_algo,
expected_fingerprint,
Expand All @@ -261,7 +333,8 @@ mod tests {

// Same host on a different port is a separate TOFU decision.
assert_eq!(
kh.lookup("example.com", 2222, "ssh-ed25519", "SHA256:aaa").unwrap(),
kh.lookup("example.com", 2222, "ssh-ed25519", "SHA256:aaa")
.unwrap(),
LookupResult::NotFound
);

Expand Down Expand Up @@ -300,7 +373,8 @@ mod tests {
let path = tmp_path("multi-algo");
let kh = KnownHosts::open_at(path.clone());
kh.add(&entry("h", 22, "ssh-ed25519", "SHA256:ed")).unwrap();
kh.add(&entry("h", 22, "rsa-sha2-512", "SHA256:rsa")).unwrap();
kh.add(&entry("h", 22, "rsa-sha2-512", "SHA256:rsa"))
.unwrap();

assert_eq!(
kh.lookup("h", 22, "ssh-ed25519", "SHA256:ed").unwrap(),
Expand All @@ -313,4 +387,70 @@ mod tests {

let _ = fs::remove_file(&path);
}

#[test]
fn list_is_sorted_and_skips_malformed_lines() {
let path = tmp_path("list");
let kh = KnownHosts::open_at(path.clone());
kh.add(&entry("b.example", 22, "ssh-ed25519", "SHA256:b"))
.unwrap();
kh.add(&entry("a.example", 2222, "ssh-rsa", "SHA256:a2"))
.unwrap();
kh.add(&entry("a.example", 22, "ssh-rsa", "SHA256:a1"))
.unwrap();

// Junk lines (hand edits) don't reach the list.
let mut contents = fs::read_to_string(&path).unwrap();
contents.push_str("not a known_hosts line\n\n");
fs::write(&path, contents).unwrap();

let listed = kh.list().unwrap();
let targets: Vec<(&str, u16)> = listed.iter().map(|e| (e.host.as_str(), e.port)).collect();
assert_eq!(
targets,
vec![("a.example", 22), ("a.example", 2222), ("b.example", 22),]
);
assert_eq!(kh.path(), path.as_path());

let _ = fs::remove_file(&path);
}

#[test]
fn remove_deletes_one_entry_and_clear_empties_the_store() {
let path = tmp_path("remove-clear");
let kh = KnownHosts::open_at(path.clone());
let ed = entry("h", 22, "ssh-ed25519", "SHA256:ed");
let rsa = entry("h", 22, "ssh-rsa", "SHA256:rsa");
kh.add(&ed).unwrap();
kh.add(&rsa).unwrap();

// Removing one key leaves the host's other algorithm trusted.
assert!(kh.remove(&ed).unwrap());
assert_eq!(
kh.lookup("h", 22, "ssh-rsa", "SHA256:rsa").unwrap(),
LookupResult::Matched
);
assert_eq!(
kh.lookup("h", 22, "ssh-ed25519", "SHA256:ed").unwrap(),
LookupResult::Mismatched {
expected_algo: "ssh-rsa".into(),
expected_fingerprint: "SHA256:rsa".into(),
}
);
// Removing an entry that isn't stored is a no-op, not an error.
assert!(!kh.remove(&ed).unwrap());

kh.clear().unwrap();
assert!(kh.list().unwrap().is_empty());
assert_eq!(
kh.lookup("h", 22, "ssh-rsa", "SHA256:rsa").unwrap(),
LookupResult::NotFound
);
// The file survives with its header so the store stays discoverable.
let contents = fs::read_to_string(&path).unwrap();
assert_eq!(contents.lines().count(), 1);
assert!(contents.starts_with('#'));

let _ = fs::remove_file(&path);
}
}
22 changes: 22 additions & 0 deletions crabport-ui/i18n/en.toml
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,7 @@ general = "General"
appearance = "Appearance"
keybinds = "Keybinds"
connection = "Connection"
known_hosts = "Known Hosts"
panels = "Panels"
ai = "AI"

Expand Down Expand Up @@ -578,6 +579,27 @@ desc = "Keepalive probes keep idle sessions from being dropped by NAT and firewa
keepalive = "Keepalive interval (s)"
auto_reconnect = "Auto-reconnect on drop"

[window.settings.known_hosts]
section = "Known Hosts"
desc = "SSH host keys you trusted on first connect. Forgetting a key makes CrabPort ask you to verify that host again the next time you connect."
file = "File"
open_folder = "Open Folder"
search_placeholder = "Search host, key type or fingerprint"
count = "Trusted keys: %{count}"
empty = "No hosts trusted yet"
no_matches = "No hosts match your search"
forget_all = "Forget All"
delete_title = "Forget host key"
delete_desc = "CrabPort will ask you to verify %{host} again on the next connection."
detail_host = "Host"
detail_type = "Key type"
detail_fingerprint = "Fingerprint"
delete_confirm = "Forget"
clear_title = "Forget all known hosts"
clear_desc = "Every trusted host key will be deleted. You will be asked to verify each host again on the next connection."
clear_confirm = "Forget All"
error = "Could not update known hosts: %{error}"

[window.settings.appearance]
section_language = "Language"
language_en = "English"
Expand Down
22 changes: 22 additions & 0 deletions crabport-ui/i18n/zh-CN.toml
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,7 @@ general = "通用"
appearance = "外观"
keybinds = "快捷键"
connection = "连接"
known_hosts = "已知主机"
panels = "面板"
ai = "AI"

Expand Down Expand Up @@ -579,6 +580,27 @@ desc = "心跳探测避免空闲会话被 NAT / 防火墙超时断开;断线
keepalive = "心跳间隔 (秒)"
auto_reconnect = "断线自动重连"

[window.settings.known_hosts]
section = "已知主机"
desc = "首次连接时信任的 SSH 主机密钥。删除某个密钥后,下次连接该主机时会重新要求你确认。"
file = "文件"
open_folder = "打开文件夹"
search_placeholder = "搜索主机、密钥类型或指纹"
count = "已信任密钥:%{count} 个"
empty = "还没有信任任何主机"
no_matches = "没有匹配的主机"
forget_all = "全部删除"
delete_title = "删除主机密钥"
delete_desc = "下次连接 %{host} 时将重新要求你确认。"
detail_host = "主机"
detail_type = "密钥类型"
detail_fingerprint = "指纹"
delete_confirm = "删除"
clear_title = "删除所有已知主机"
clear_desc = "所有已信任的主机密钥都将被删除,下次连接每个主机时都需要重新确认。"
clear_confirm = "全部删除"
error = "更新已知主机失败:%{error}"

[window.settings.appearance]
section_language = "语言"
language_en = "English"
Expand Down
Loading
Loading