Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

feat(ssh): prompt to reset a changed host fingerprint

64673ac30fc33305b1
diff --git a/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue b/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
index 3ee2d07457..5e93330ab3 100644
--- a/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
+++ b/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
@@ -2,6 +2,7 @@
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useI18n } from "vue-i18n";
import { invoke } from "@tauri-apps/api/core";
+import { TriangleAlert } from "@lucide/vue";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { useToast } from "@/composables/useToast";
@@ -11,11 +12,12 @@ import { apiUrl } from "@/lib/common/webPath";
interface SshPromptRequest {
id: string;
- kind: "HostKeyVerify" | "SecretInput" | "WorkerUploadConsent";
+ kind: "HostKeyVerify" | "HostKeyChanged" | "SecretInput" | "WorkerUploadConsent";
host: string;
port: number;
key_type?: string | null;
fingerprint?: string | null;
+ previous_fingerprint?: string | null;
prompt?: string | null;
echo?: boolean;
}
@@ -38,6 +40,19 @@ const queue = ref<SshPromptRequest[]>([]);
const current = computed<SshPromptRequest | null>(() => queue.value[0] ?? null);
const isSecretPrompt = computed(() => current.value?.kind === "SecretInput");
const isWorkerUploadPrompt = computed(() => current.value?.kind === "WorkerUploadConsent");
+const isHostKeyChanged = computed(() => current.value?.kind === "HostKeyChanged");
+const titleKey = computed(() => {
+ if (isSecretPrompt.value) return "connection.sshInteractiveTitle";
+ if (isWorkerUploadPrompt.value) return "connection.sshWorkerUploadConsentTitle";
+ if (isHostKeyChanged.value) return "connection.sshHostKeyChangedTitle";
+ return "connection.sshHostKeyVerifyTitle";
+});
+const messageKey = computed(() => {
+ if (isSecretPrompt.value) return "connection.sshInteractiveMessage";
+ if (isWorkerUploadPrompt.value) return "connection.sshWorkerUploadConsentMessage";
+ if (isHostKeyChanged.value) return "connection.sshHostKeyChangedMessage";
+ return "connection.sshHostKeyVerifyMessage";
+});
const visible = ref(false);
const remember = ref(true);
@@ -224,10 +239,24 @@ function resetPromptState() {
secretCode.value = "";
}
+function fingerprintBody(value: string | null | undefined): string {
+ return (value ?? "").replace(/^SHA256:/i, "");
+}
+
function accept() {
void resolve("accept");
}
+function acceptSessionOnly() {
+ remember.value = false;
+ void resolve("accept");
+}
+
+function acceptAndUpdate() {
+ remember.value = true;
+ void resolve("accept");
+}
+
function reject() {
void resolve("reject");
}
@@ -250,16 +279,35 @@ function submitSecret() {
100). -->
<DialogContent class="flex max-h-[min(36rem,calc(var(--dbx-viewport-height)-2rem))] w-full max-w-[32rem] flex-col gap-4 overflow-hidden" overlay-class="z-[200]" portal-class="z-[200]" :show-close-button="false" @interact-outside.prevent @escape-key-down.prevent>
<DialogHeader class="shrink-0">
- <DialogTitle>
- {{ t(isSecretPrompt ? "connection.sshInteractiveTitle" : isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentTitle" : "connection.sshHostKeyVerifyTitle") }}
- </DialogTitle>
+ <DialogTitle>{{ t(titleKey) }}</DialogTitle>
<DialogDescription class="text-muted-foreground">
- {{ t(isSecretPrompt ? "connection.sshInteractiveMessage" : isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentMessage" : "connection.sshHostKeyVerifyMessage", { host: current?.host ?? "", port: current?.port ?? "" }) }}
+ {{ t(messageKey, { host: current?.host ?? "", port: current?.port ?? "" }) }}
</DialogDescription>
</DialogHeader>
<div v-if="current" class="min-h-0 flex-1 space-y-3 overflow-y-auto py-1">
- <div v-if="current.kind === 'HostKeyVerify' || current.kind === 'WorkerUploadConsent'" class="space-y-3 rounded-md border border-border bg-muted/40 p-3 text-sm">
+ <div v-if="isHostKeyChanged" class="space-y-3">
+ <div class="flex items-start gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ <TriangleAlert class="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
+ <div class="space-y-0.5">
+ <div class="font-medium">{{ t("connection.sshHostKeyChangedTitle") }}</div>
+ <div class="text-destructive/90">{{ t("connection.sshHostKeyChangedMessage", { host: current.host, port: current.port }) }}</div>
+ </div>
+ </div>
+ <div class="space-y-2 text-sm">
+ <div class="space-y-1">
+ <div class="text-muted-foreground">{{ t("connection.sshHostKeyChangedCurrent", { keyType: current.key_type || "—" }) }}</div>
+ <div class="break-all rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs font-medium leading-5">{{ fingerprintBody(current.fingerprint) || "—" }}</div>
+ </div>
+ <div class="space-y-1">
+ <div class="text-destructive">{{ t("connection.sshHostKeyChangedSaved") }}</div>
+ <div class="break-all rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 font-mono text-xs font-medium leading-5 text-destructive">{{ fingerprintBody(current.previous_fingerprint) || "—" }}</div>
+ </div>
+ <p class="text-xs text-muted-foreground">{{ t("connection.sshHostKeyChangedWarning") }}</p>
+ </div>
+ </div>
+
+ <div v-else-if="current.kind === 'HostKeyVerify' || current.kind === 'WorkerUploadConsent'" class="space-y-3 rounded-md border border-border bg-muted/40 p-3 text-sm">
<div class="space-y-1">
<div class="text-muted-foreground">{{ current.kind === "WorkerUploadConsent" ? t("connection.sshWorkerUploadConsentDigest") : t("connection.sshHostKeyVerifyKeyType") }}</div>
<div class="break-all font-mono text-xs font-medium leading-5">{{ current.kind === "WorkerUploadConsent" ? current.fingerprint || "—" : current.key_type || "—" }}</div>
@@ -292,9 +340,17 @@ function submitSecret() {
<DialogFooter class="shrink-0">
<Button variant="outline" :disabled="resolving" @click="reject">
- {{ t(isSecretPrompt ? "connection.sshInteractiveCancel" : isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentReject" : "connection.sshHostKeyVerifyReject") }}
+ {{ t(isSecretPrompt ? "connection.sshInteractiveCancel" : isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentReject" : isHostKeyChanged ? "connection.sshHostKeyChangedClose" : "connection.sshHostKeyVerifyReject") }}
</Button>
- <Button v-if="current?.kind !== 'SecretInput'" :disabled="resolving" @click="accept">
+ <template v-if="isHostKeyChanged">
+ <Button variant="outline" :disabled="resolving" @click="acceptSessionOnly">
+ {{ t("connection.sshHostKeyChangedContinue") }}
+ </Button>
+ <Button :disabled="resolving" @click="acceptAndUpdate">
+ {{ t("connection.sshHostKeyChangedUpdate") }}
+ </Button>
+ </template>
+ <Button v-else-if="current?.kind !== 'SecretInput'" :disabled="resolving" @click="accept">
{{ t(isWorkerUploadPrompt ? "connection.sshWorkerUploadConsentAccept" : "connection.sshHostKeyVerifyAccept") }}
</Button>
<Button v-else :disabled="resolving || !secretCode" @click="submitSecret">
diff --git a/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts b/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
index 2fbe901e44..3b4296822a 100644
--- a/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
+++ b/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
@@ -168,6 +168,77 @@ describe("SshHostKeyPromptDialog web bridge", () => {
});
});
+ it("shows a changed host-key prompt and updates the saved fingerprint", async () => {
+ await mountDialog();
+
+ const eventSource = MockEventSource.instances[0];
+ eventSource?.emit({
+ type: "prompt",
+ request: {
+ id: "changed-1",
+ kind: "HostKeyChanged",
+ host: "192.168.1.111",
+ port: 22,
+ key_type: "ssh-ed25519",
+ fingerprint: "SHA256:new-fingerprint",
+ previous_fingerprint: "SHA256:old-fingerprint",
+ },
+ });
+ await nextTick();
+
+ expect(document.body.textContent).toContain("Host fingerprint has changed");
+ expect(document.body.textContent).toContain("new-fingerprint");
+ expect(document.body.textContent).toContain("old-fingerprint");
+ expect(document.body.textContent).toContain("Saved fingerprint");
+
+ const buttons = [...document.body.querySelectorAll("button")].map((button) => button.textContent?.trim());
+ expect(buttons).toContain("Close");
+ expect(buttons).toContain("Continue");
+ expect(buttons).toContain("Update and Continue");
+
+ const update = [...document.body.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "Update and Continue");
+ update?.click();
+
+ await vi.waitFor(() => {
+ expect(resolveSshPromptMock).toHaveBeenCalledWith({
+ id: "changed-1",
+ action: "accept",
+ remember: true,
+ secret: undefined,
+ });
+ });
+ });
+
+ it("continues a changed host key for this session only", async () => {
+ await mountDialog();
+
+ MockEventSource.instances[0]?.emit({
+ type: "prompt",
+ request: {
+ id: "changed-2",
+ kind: "HostKeyChanged",
+ host: "board.example.test",
+ port: 22,
+ key_type: "ssh-ed25519",
+ fingerprint: "SHA256:new",
+ previous_fingerprint: "SHA256:old",
+ },
+ });
+ await nextTick();
+
+ const cont = [...document.body.querySelectorAll<HTMLButtonElement>("button")].find((button) => button.textContent?.trim() === "Continue");
+ cont?.click();
+
+ await vi.waitFor(() => {
+ expect(resolveSshPromptMock).toHaveBeenCalledWith({
+ id: "changed-2",
+ action: "accept",
+ remember: false,
+ secret: undefined,
+ });
+ });
+ });
+
it("clears prompts that are no longer pending after an SSE reconnect snapshot", async () => {
await mountDialog();
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index a58c09bccf..3b5d8eeb09 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1102,6 +1102,14 @@ export default {
sshHostKeyVerifyRemember: "Trust this host (remember this key for future connections)",
sshHostKeyVerifyAccept: "Accept & Connect",
sshHostKeyVerifyReject: "Cancel",
+ sshHostKeyChangedTitle: "Host fingerprint has changed",
+ sshHostKeyChangedMessage: "The saved fingerprint for {host} does not match the current server.",
+ sshHostKeyChangedCurrent: "{keyType} fingerprint is SHA256:",
+ sshHostKeyChangedSaved: "Saved fingerprint",
+ sshHostKeyChangedWarning: "Continue only if you are sure this host has actually changed.",
+ sshHostKeyChangedClose: "Close",
+ sshHostKeyChangedContinue: "Continue",
+ sshHostKeyChangedUpdate: "Update and Continue",
sshInteractiveTitle: "SSH Verification Required",
sshInteractiveMessage: "The SSH server at {host}:{port} requires additional verification.",
sshInteractiveDefaultPrompt: "Enter the requested verification response.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 4577884bea..de500b01a6 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1029,6 +1029,14 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "信任此主机(记住该密钥用于以后的连接)",
sshHostKeyVerifyAccept: "接受并连接",
sshHostKeyVerifyReject: "取消",
+ sshHostKeyChangedTitle: "主机指纹已变化",
+ sshHostKeyChangedMessage: "{host} 的已保存指纹与当前服务器不一致。",
+ sshHostKeyChangedCurrent: "{keyType} 指纹为 SHA256:",
+ sshHostKeyChangedSaved: "已保存的指纹",
+ sshHostKeyChangedWarning: "只有在你确认这台主机确实变更过时才继续。",
+ sshHostKeyChangedClose: "关闭",
+ sshHostKeyChangedContinue: "继续",
+ sshHostKeyChangedUpdate: "更新并继续",
sshInteractiveTitle: "需要 SSH 验证",
sshInteractiveMessage: "SSH 服务器 {host}:{port} 要求完成额外验证。",
sshInteractiveDefaultPrompt: "请输入服务器要求的验证信息。",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index ca31674d29..1165a718de 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1085,6 +1085,14 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "信任此主機(記住此金鑰用於之後的連線)",
sshHostKeyVerifyAccept: "接受並連線",
sshHostKeyVerifyReject: "取消",
+ sshHostKeyChangedTitle: "主機指紋已變化",
+ sshHostKeyChangedMessage: "{host} 的已儲存指紋與目前伺服器不一致。",
+ sshHostKeyChangedCurrent: "{keyType} 指紋為 SHA256:",
+ sshHostKeyChangedSaved: "已儲存的指紋",
+ sshHostKeyChangedWarning: "只有在你確認這台主機確實變更過時才繼續。",
+ sshHostKeyChangedClose: "關閉",
+ sshHostKeyChangedContinue: "繼續",
+ sshHostKeyChangedUpdate: "更新並繼續",
sshInteractiveTitle: "需要 SSH 驗證",
sshInteractiveMessage: "SSH 伺服器 {host}:{port} 要求完成額外驗證。",
sshInteractiveDefaultPrompt: "請輸入伺服器要求的驗證資訊。",
diff --git a/crates/dbx-core/src/db/sqlite_worker.rs b/crates/dbx-core/src/db/sqlite_worker.rs
index e74248f264..8b5dd3c457 100644
--- a/crates/dbx-core/src/db/sqlite_worker.rs
+++ b/crates/dbx-core/src/db/sqlite_worker.rs
@@ -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,
};
diff --git a/crates/dbx-core/src/db/ssh_host_key.rs b/crates/dbx-core/src/db/ssh_host_key.rs
index 6334941df5..1c9f3509ff 100644
--- a/crates/dbx-core/src/db/ssh_host_key.rs
+++ b/crates/dbx-core/src/db/ssh_host_key.rs
@@ -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 {
diff --git a/crates/dbx-core/src/db/ssh_prompt.rs b/crates/dbx-core/src/db/ssh_prompt.rs
index c0268cf8ef..ac7927d70c 100644
--- a/crates/dbx-core/src/db/ssh_prompt.rs
+++ b/crates/dbx-core/src/db/ssh_prompt.rs
@@ -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,
}
diff --git a/crates/dbx-core/src/db/ssh_tunnel.rs b/crates/dbx-core/src/db/ssh_tunnel.rs
index 3745e4ffc7..d880926bfc 100644
--- a/crates/dbx-core/src/db/ssh_tunnel.rs
+++ b/crates/dbx-core/src/db/ssh_tunnel.rs
@@ -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]
diff --git a/crates/dbx-web/src/ssh_prompt.rs b/crates/dbx-web/src/ssh_prompt.rs
index aa89bbe991..48e32274f1 100644
--- a/crates/dbx-web/src/ssh_prompt.rs
+++ b/crates/dbx-web/src/ssh_prompt.rs
@@ -132,6 +132,7 @@ mod tests {
port: 22,
key_type: Some("ssh-ed25519".to_string()),
fingerprint: Some("SHA256:test".to_string()),
+ previous_fingerprint: None,
prompt: None,
echo: false,
}
diff --git a/docs/content/docs/ssh-tunnel.cn.mdx b/docs/content/docs/ssh-tunnel.cn.mdx
index 83d9cd6b2a..f53b0e968d 100644
--- a/docs/content/docs/ssh-tunnel.cn.mdx
+++ b/docs/content/docs/ssh-tunnel.cn.mdx
@@ -75,7 +75,7 @@ DBX 会在发送凭据前验证 SSH 主机密钥。已知密钥从系统 `known_
- 第一次连接到未知主机时,DBX 会显示指纹并要求明确接受;
- 可以只信任本次连接,也可以记住到 DBX 的 `known_hosts`;
-- 已记录主机的密钥发生变化时,DBX 会拒绝连接;
+- 已保存在 DBX `known_hosts` 中的主机密钥变化时,会弹出指纹对比。可以选择关闭、仅本次继续,或更新已保存指纹并继续。DBX 不会改写 `~/.ssh/known_hosts`,那里的不一致仍会直接拒绝;
- 如果确认窗口不可用、超时或被拒绝,连接会失败,并且不会发送密码或私钥。
### 允许局域网访问
diff --git a/docs/content/docs/ssh-tunnel.mdx b/docs/content/docs/ssh-tunnel.mdx
index 32cffc5413..a0fd778799 100644
--- a/docs/content/docs/ssh-tunnel.mdx
+++ b/docs/content/docs/ssh-tunnel.mdx
@@ -75,7 +75,7 @@ DBX verifies the SSH host key before it sends a credential. Trusted keys come fr
- An unknown host prompts you to review and explicitly accept its fingerprint.
- You can trust it for the current connection only or remember it in DBX's `known_hosts`.
-- DBX rejects a changed key for a previously known host.
+- A changed key for a host already saved in DBX's `known_hosts` prompts you to compare fingerprints. You can close, continue for this session only, or update the saved key and continue. DBX never edits `~/.ssh/known_hosts`; a mismatch there still fails closed.
- If the confirmation UI is unavailable, times out, or rejects the key, the connection fails without sending a password or private key.
### Expose Tunnel to LAN
diff --git a/docs/content/docs/ssh-tunnel.tr.mdx b/docs/content/docs/ssh-tunnel.tr.mdx
index 16de403e9a..432c73a4b8 100644
--- a/docs/content/docs/ssh-tunnel.tr.mdx
+++ b/docs/content/docs/ssh-tunnel.tr.mdx
@@ -75,7 +75,7 @@ DBX, bir kimlik bilgisi göndermeden önce SSH sunucu anahtarını doğrular. G
- Bilinmeyen bir sunucu, parmak izini incelemenizi ve açıkça kabul etmenizi ister.
- Yalnızca geçerli bağlantı için güvenebilir ya da DBX'in `known_hosts` dosyasında hatırlayabilirsiniz.
-- DBX, daha önce bilinen bir sunucu için değişmiş bir anahtarı reddeder.
+- DBX `known_hosts` dosyasında kayıtlı bir sunucunun anahtarı değiştiğinde parmak izlerini karşılaştırmanız istenir. Kapatabilir, yalnızca bu oturum için devam edebilir veya kayıtlı anahtarı güncelleyip devam edebilirsiniz. DBX `~/.ssh/known_hosts` dosyasını düzenlemez; oradaki bir uyumsuzluk hâlâ bağlantıyı reddeder.
- Onay arayüzü kullanılamıyorsa, zaman aşımına uğrarsa ya da anahtar reddedilirse bağlantı parola veya özel anahtar gönderilmeden başarısız olur.
### Tüneli Yerel Ağa Açma
diff --git a/src-tauri/src/commands/ssh_prompt.rs b/src-tauri/src/commands/ssh_prompt.rs
index da1ea8bc05..9a9729248c 100644
--- a/src-tauri/src/commands/ssh_prompt.rs
+++ b/src-tauri/src/commands/ssh_prompt.rs
@@ -263,6 +263,7 @@ mod tests {
port: 22,
key_type: Some("ssh-ed25519".to_string()),
fingerprint: Some("SHA256:test".to_string()),
+ previous_fingerprint: None,
prompt: None,
echo: false,
}