feat(ssh): prompt to reset a changed host fingerprint
This commit is contained in:
1 parent
fd44331876
commit
c30fc33305
14 files changed
+418
-32
No files matched your search
@@ -434,6 +434,7 @@ async fn ensure_worker_consent(data_dir: &Path, identity: &str, dest: &str, dige
|
||||
port: port.parse().unwrap_or(22),
|
||||
key_type: Some("sha256".to_string()),
|
||||
fingerprint: Some(digest.to_string()),
|
||||
previous_fingerprint: None,
|
||||
prompt: Some(dest.to_string()),
|
||||
echo: false,
|
||||
};
|
||||
|
||||
@@ -21,28 +21,38 @@
|
||||
//! (the `check_server_key` handler) then performs an **explicit TOFU** flow:
|
||||
//! it asks the UI to confirm the key and, on acceptance, records it via
|
||||
//! [`HostKeyVerifier::learn`].
|
||||
//! 4. A *changed* key in the dbx store is [`HostKeyState::Changed`]. The caller
|
||||
//! prompts the user to compare fingerprints and, if they choose to update,
|
||||
//! replaces the old entry via [`HostKeyVerifier::replace`]. A changed key
|
||||
//! in `~/.ssh/known_hosts` stays a hard reject — dbx does not edit that file.
|
||||
//!
|
||||
//! Hardening rules:
|
||||
//! * A host whose key **changed** (vs. either store) is rejected. This closes
|
||||
//! the MITM credential-harvest hole so a password is never sent to an
|
||||
//! impostor, and we do not silently fall back to sending credentials.
|
||||
//! * A changed key is never trusted silently. Credentials are sent only after
|
||||
//! the user explicitly continues (session-only) or updates the saved key.
|
||||
//! * If an unknown host's key **cannot be persisted** (e.g. no write permission
|
||||
//! on `<data_dir>`), `learn` fails — but that failure is surfaced by the
|
||||
//! caller, which still refuses to trust the host silently.
|
||||
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use russh::keys::known_hosts::{check_known_hosts, check_known_hosts_path, learn_known_hosts_path};
|
||||
use russh::keys::ssh_key::PublicKey;
|
||||
use russh::keys::known_hosts::{
|
||||
check_known_hosts, check_known_hosts_path, known_host_keys_path, learn_known_hosts_path,
|
||||
};
|
||||
use russh::keys::parse_public_key_base64;
|
||||
use russh::keys::ssh_key::{HashAlg, PublicKey};
|
||||
|
||||
/// Outcome of checking a server key against the known-hosts stores.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HostKeyState {
|
||||
/// The key matches a previously trusted entry (system or dbx store).
|
||||
Trusted,
|
||||
/// The key is not present in either store (candidate for explicit TOFU).
|
||||
Unknown,
|
||||
/// The dbx store has a different key of the same algorithm. The caller
|
||||
/// should prompt before replacing it; `previous_fingerprint` is the saved
|
||||
/// SHA256 fingerprint (or a fallback locator if the line could not be parsed).
|
||||
Changed { previous_fingerprint: String },
|
||||
}
|
||||
|
||||
/// Host-key verifier backed by russh's OpenSSH-format known-hosts store.
|
||||
@@ -60,8 +70,9 @@ impl HostKeyVerifier {
|
||||
Self { known_hosts_path }
|
||||
}
|
||||
|
||||
/// Layered, fail-closed check. A *changed* key (mismatch vs either store)
|
||||
/// is reported as an `Err` so the caller aborts the handshake.
|
||||
/// Layered, fail-closed check. A *changed* key in `~/.ssh` is an `Err`. A
|
||||
/// changed key in the dbx store is [`HostKeyState::Changed`] so the UI can
|
||||
/// offer a one-click replace.
|
||||
pub fn check(&self, host: &str, port: u16, key: &PublicKey) -> Result<HostKeyState, io::Error> {
|
||||
// 1. System known_hosts (read-only). A changed key there is a hard reject.
|
||||
match check_known_hosts(host, port, key) {
|
||||
@@ -79,7 +90,9 @@ impl HostKeyVerifier {
|
||||
match check_known_hosts_path(host, port, key, &self.known_hosts_path) {
|
||||
Ok(true) => return Ok(HostKeyState::Trusted),
|
||||
Err(russh::keys::Error::KeyChanged { line }) => {
|
||||
return Err(host_key_changed_error(host, port, line, &self.known_hosts_path.display().to_string()));
|
||||
let previous_fingerprint = previous_fingerprint_for(&self.known_hosts_path, host, port, key)
|
||||
.unwrap_or_else(|| format!("(known_hosts line {line})"));
|
||||
return Ok(HostKeyState::Changed { previous_fingerprint });
|
||||
}
|
||||
// Unknown (or an unreadable dbx store): report as a candidate for TOFU.
|
||||
_ => {}
|
||||
@@ -105,6 +118,64 @@ impl HostKeyVerifier {
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Drops the previous same-algorithm key for this host in the dbx store,
|
||||
/// then records `key`. Used after the user confirms a fingerprint change.
|
||||
pub fn replace(&self, host: &str, port: u16, key: &PublicKey) -> Result<(), io::Error> {
|
||||
self.forget_matching_algorithm(host, port, key)?;
|
||||
self.learn(host, port, key)
|
||||
}
|
||||
|
||||
fn forget_matching_algorithm(&self, host: &str, port: u16, key: &PublicKey) -> Result<(), io::Error> {
|
||||
let recorded = match known_host_keys_path(host, port, &self.known_hosts_path) {
|
||||
Ok(keys) => keys,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
let drop_keys: Vec<PublicKey> = recorded
|
||||
.into_iter()
|
||||
.filter(|(_, recorded)| recorded.algorithm() == key.algorithm())
|
||||
.map(|(_, recorded)| recorded)
|
||||
.collect();
|
||||
if drop_keys.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let contents = match std::fs::read_to_string(&self.known_hosts_path) {
|
||||
Ok(contents) => contents,
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let mut kept = Vec::new();
|
||||
for line in contents.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() || trimmed.starts_with('#') {
|
||||
kept.push(line);
|
||||
continue;
|
||||
}
|
||||
let should_drop = trimmed
|
||||
.split_whitespace()
|
||||
.nth(2)
|
||||
.and_then(|encoded| parse_public_key_base64(encoded).ok())
|
||||
.map(|parsed| drop_keys.iter().any(|recorded| recorded == &parsed))
|
||||
.unwrap_or(false);
|
||||
if !should_drop {
|
||||
kept.push(line);
|
||||
}
|
||||
}
|
||||
let mut out = kept.join("\n");
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
std::fs::write(&self.known_hosts_path, out)
|
||||
}
|
||||
}
|
||||
|
||||
fn previous_fingerprint_for(path: &Path, host: &str, port: u16, key: &PublicKey) -> Option<String> {
|
||||
let recorded = known_host_keys_path(host, port, path).ok()?;
|
||||
recorded
|
||||
.into_iter()
|
||||
.find(|(_, recorded)| recorded.algorithm() == key.algorithm() && recorded != key)
|
||||
.map(|(_, recorded)| recorded.fingerprint(HashAlg::Sha256).to_string())
|
||||
}
|
||||
|
||||
fn host_key_changed_error(host: &str, port: u16, line: usize, store: &str) -> io::Error {
|
||||
|
||||
@@ -24,6 +24,8 @@ use uuid::Uuid;
|
||||
pub enum SshPromptKind {
|
||||
/// Confirm/deny a server host key (explicit TOFU).
|
||||
HostKeyVerify,
|
||||
/// Confirm replacing a previously saved host key that no longer matches.
|
||||
HostKeyChanged,
|
||||
/// Collect a secret typed by the user (e.g. a dynamic verification code).
|
||||
SecretInput,
|
||||
/// Confirm uploading the SQLite worker binary onto the file host.
|
||||
@@ -41,9 +43,12 @@ pub struct SshPromptRequest {
|
||||
/// HostKeyVerify: key algorithm, e.g. `ssh-ed25519`.
|
||||
#[serde(default)]
|
||||
pub key_type: Option<String>,
|
||||
/// HostKeyVerify: SHA256 fingerprint string, e.g. `SHA256:xxxx`.
|
||||
/// HostKeyVerify / HostKeyChanged: SHA256 fingerprint string, e.g. `SHA256:xxxx`.
|
||||
#[serde(default)]
|
||||
pub fingerprint: Option<String>,
|
||||
/// HostKeyChanged: previously saved SHA256 fingerprint for comparison.
|
||||
#[serde(default)]
|
||||
pub previous_fingerprint: Option<String>,
|
||||
/// SecretInput: the challenge text to show the user.
|
||||
#[serde(default)]
|
||||
pub prompt: Option<String>,
|
||||
@@ -109,6 +114,28 @@ pub fn host_key_verify_request(
|
||||
port,
|
||||
key_type,
|
||||
fingerprint,
|
||||
previous_fingerprint: None,
|
||||
prompt: None,
|
||||
echo: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a [`SshPromptRequest`] for a changed-host-key confirmation.
|
||||
pub fn host_key_changed_request(
|
||||
host: &str,
|
||||
port: u16,
|
||||
key_type: Option<String>,
|
||||
fingerprint: Option<String>,
|
||||
previous_fingerprint: Option<String>,
|
||||
) -> SshPromptRequest {
|
||||
SshPromptRequest {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
kind: SshPromptKind::HostKeyChanged,
|
||||
host: host.to_string(),
|
||||
port,
|
||||
key_type,
|
||||
fingerprint,
|
||||
previous_fingerprint,
|
||||
prompt: None,
|
||||
echo: false,
|
||||
}
|
||||
@@ -123,6 +150,7 @@ pub fn secret_input_request(host: &str, port: u16, prompt: String, echo: bool) -
|
||||
port,
|
||||
key_type: None,
|
||||
fingerprint: None,
|
||||
previous_fingerprint: None,
|
||||
prompt: Some(prompt),
|
||||
echo,
|
||||
}
|
||||
|
||||
@@ -67,15 +67,18 @@ impl client::Handler for SshClient {
|
||||
) -> Result<bool, Self::Error> {
|
||||
// Runs *before any credential authentication*. We first check the
|
||||
// known-hosts stores (system + dbx-managed). A trusted key is accepted
|
||||
// immediately; a *changed* key is rejected (MITM hardening); an unknown
|
||||
// key triggers an explicit TOFU prompt so the user can confirm the host
|
||||
// fingerprint before any password/key is sent.
|
||||
// immediately; an unknown key triggers explicit TOFU; a changed key in
|
||||
// the dbx store prompts for replace-or-session-only; a changed key in
|
||||
// ~/.ssh/known_hosts is still a hard reject (dbx never writes that file).
|
||||
match self.host_key_verifier.check(&self.host, self.port, server_public_key) {
|
||||
Ok(HostKeyState::Trusted) => Ok(true),
|
||||
Ok(HostKeyState::Unknown) => self.prompt_for_host_key(server_public_key).await,
|
||||
Ok(HostKeyState::Unknown) => self.prompt_for_host_key(server_public_key, None).await,
|
||||
Ok(HostKeyState::Changed { previous_fingerprint }) => {
|
||||
self.prompt_for_host_key(server_public_key, Some(previous_fingerprint)).await
|
||||
}
|
||||
Err(e) => {
|
||||
// Changed host key => possible MITM. Surface it to the user as a
|
||||
// clear notice (best-effort; never affects the fail-closed below).
|
||||
// Changed host key in ~/.ssh/known_hosts => possible MITM. dbx
|
||||
// never writes that file, so surface a notice and fail closed.
|
||||
let msg = e.to_string();
|
||||
let _ =
|
||||
ssh_prompt::notify_host_key(ssh_prompt::SshHostKeyNoticeKind::Changed, &self.host, self.port, &msg);
|
||||
@@ -93,10 +96,16 @@ impl SshClient {
|
||||
async fn prompt_for_host_key(
|
||||
&mut self,
|
||||
server_public_key: &russh::keys::ssh_key::PublicKey,
|
||||
previous_fingerprint: Option<String>,
|
||||
) -> Result<bool, russh::Error> {
|
||||
let key_type = Some(server_public_key.algorithm().to_string());
|
||||
let fingerprint = Some(server_public_key.fingerprint(HashAlg::Sha256).to_string());
|
||||
let request = ssh_prompt::host_key_verify_request(&self.host, self.port, key_type, fingerprint);
|
||||
let replace = previous_fingerprint.is_some();
|
||||
let request = if replace {
|
||||
ssh_prompt::host_key_changed_request(&self.host, self.port, key_type, fingerprint, previous_fingerprint)
|
||||
} else {
|
||||
ssh_prompt::host_key_verify_request(&self.host, self.port, key_type, fingerprint)
|
||||
};
|
||||
|
||||
let Some(responder_rx) = ssh_prompt::request_ssh_prompt(request) else {
|
||||
log::warn!(
|
||||
@@ -118,7 +127,12 @@ impl SshClient {
|
||||
match answer {
|
||||
Ok(Ok(ssh_prompt::SshPromptAnswer::Accept { remember })) => {
|
||||
if remember {
|
||||
if let Err(e) = self.host_key_verifier.learn(&self.host, self.port, server_public_key) {
|
||||
let persist = if replace {
|
||||
self.host_key_verifier.replace(&self.host, self.port, server_public_key)
|
||||
} else {
|
||||
self.host_key_verifier.learn(&self.host, self.port, server_public_key)
|
||||
};
|
||||
if let Err(e) = persist {
|
||||
// Persistence failure does not by itself abort the
|
||||
// session — the host is simply trusted for this session
|
||||
// only. Still log it AND surface a notice so the UI can
|
||||
@@ -2244,7 +2258,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changed_host_key_is_rejected() {
|
||||
fn changed_host_key_is_reported() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("known_hosts");
|
||||
// Pre-seed the store with a *different* (valid) ed25519 key for the host.
|
||||
@@ -2257,7 +2271,38 @@ mod tests {
|
||||
|
||||
// The server actually presents TEST_SERVER_KEY_PEM's key -> mismatch.
|
||||
let key = test_server_public_key();
|
||||
assert!(verifier.check("db.example.com", 22, &key).is_err(), "changed host key must be rejected (MITM)");
|
||||
match verifier.check("db.example.com", 22, &key).unwrap() {
|
||||
HostKeyState::Changed { previous_fingerprint } => {
|
||||
assert!(
|
||||
previous_fingerprint.starts_with("SHA256:"),
|
||||
"changed key must expose the saved fingerprint, got {previous_fingerprint}"
|
||||
);
|
||||
}
|
||||
other => panic!("changed host key must be reported as Changed, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replace_updates_changed_host_key() {
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("known_hosts");
|
||||
std::fs::write(
|
||||
&path,
|
||||
"db.example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G1sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X\n",
|
||||
)
|
||||
.unwrap();
|
||||
let verifier = HostKeyVerifier::new(path.clone());
|
||||
let key = test_server_public_key();
|
||||
|
||||
assert!(matches!(verifier.check("db.example.com", 22, &key).unwrap(), HostKeyState::Changed { .. }));
|
||||
verifier.replace("db.example.com", 22, &key).unwrap();
|
||||
assert_eq!(verifier.check("db.example.com", 22, &key).unwrap(), HostKeyState::Trusted);
|
||||
let contents = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(
|
||||
!contents.contains("AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G1sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X"),
|
||||
"old key must be removed: {contents}"
|
||||
);
|
||||
assert!(contents.contains("db.example.com"), "new key must be recorded: {contents}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2412,6 +2457,94 @@ mod tests {
|
||||
assert!(trusted, "a known-trusted host must be accepted without a prompt");
|
||||
}
|
||||
|
||||
fn seed_changed_host_key(path: &std::path::Path) {
|
||||
std::fs::write(
|
||||
path,
|
||||
"db.example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G1sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X\n",
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn changed_host_prompt_update_replaces_key() {
|
||||
let _guard = PROMPT_TEST_LOCK.lock().await;
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("known_hosts");
|
||||
seed_changed_host_key(&path);
|
||||
let verifier = HostKeyVerifier::new(path.clone());
|
||||
let key = test_server_public_key();
|
||||
|
||||
install_fake_prompt_gateway(ssh_prompt::SshPromptAnswer::Accept { remember: true });
|
||||
let mut client = SshClient {
|
||||
host_key_verifier: Arc::new(verifier),
|
||||
host: "db.example.com".to_string(),
|
||||
port: 22,
|
||||
prompt_started_tx: None,
|
||||
};
|
||||
|
||||
let trusted = client.check_server_key(&key).await.unwrap();
|
||||
assert!(trusted, "updating a changed host key should continue the handshake");
|
||||
let contents = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(
|
||||
!contents.contains("AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G1sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X"),
|
||||
"old key must be removed: {contents}"
|
||||
);
|
||||
assert!(contents.contains("db.example.com"), "new key should be learned: {contents}");
|
||||
ssh_prompt::clear_ssh_prompt_gateway();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn changed_host_prompt_continue_is_session_only() {
|
||||
let _guard = PROMPT_TEST_LOCK.lock().await;
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("known_hosts");
|
||||
seed_changed_host_key(&path);
|
||||
let original = std::fs::read_to_string(&path).unwrap();
|
||||
let verifier = HostKeyVerifier::new(path.clone());
|
||||
let key = test_server_public_key();
|
||||
|
||||
install_fake_prompt_gateway(ssh_prompt::SshPromptAnswer::Accept { remember: false });
|
||||
let mut client = SshClient {
|
||||
host_key_verifier: Arc::new(verifier),
|
||||
host: "db.example.com".to_string(),
|
||||
port: 22,
|
||||
prompt_started_tx: None,
|
||||
};
|
||||
|
||||
let trusted = client.check_server_key(&key).await.unwrap();
|
||||
assert!(trusted, "continuing without update should trust this session");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).unwrap(),
|
||||
original,
|
||||
"remember=false must leave known_hosts unchanged"
|
||||
);
|
||||
ssh_prompt::clear_ssh_prompt_gateway();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn changed_host_prompt_reject_aborts_handshake() {
|
||||
let _guard = PROMPT_TEST_LOCK.lock().await;
|
||||
let dir = tempdir().unwrap();
|
||||
let path = dir.path().join("known_hosts");
|
||||
seed_changed_host_key(&path);
|
||||
let original = std::fs::read_to_string(&path).unwrap();
|
||||
let verifier = HostKeyVerifier::new(path.clone());
|
||||
let key = test_server_public_key();
|
||||
|
||||
install_fake_prompt_gateway(ssh_prompt::SshPromptAnswer::Reject);
|
||||
let mut client = SshClient {
|
||||
host_key_verifier: Arc::new(verifier),
|
||||
host: "db.example.com".to_string(),
|
||||
port: 22,
|
||||
prompt_started_tx: None,
|
||||
};
|
||||
|
||||
let trusted = client.check_server_key(&key).await.unwrap();
|
||||
assert!(!trusted, "rejected changed host key must not be trusted");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), original, "rejected change must not rewrite known_hosts");
|
||||
ssh_prompt::clear_ssh_prompt_gateway();
|
||||
}
|
||||
|
||||
// --- key+password fallback policy ------------------------------------------
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user