From 3a2dc4225aff9241e0f180f35f781d382a388620 Mon Sep 17 00:00:00 2001 From: huijiangyuan Date: Sun, 26 Jul 2026 17:52:33 +0800 Subject: [PATCH] feat(ssh): support key+password combined authentication --- .gitignore | 1 + .../connection/ConnectionDialog.vue | 35 +- .../connection/TunnelProfileManager.vue | 42 +- .../src/components/layout/AppDialogs.vue | 2 + .../components/ssh/SshHostKeyPromptDialog.vue | 205 +++++++ apps/desktop/src/i18n/locales/en.ts | 12 + apps/desktop/src/i18n/locales/es.ts | 12 + apps/desktop/src/i18n/locales/it.ts | 12 + apps/desktop/src/i18n/locales/ja.ts | 12 + apps/desktop/src/i18n/locales/pt-BR.ts | 12 + apps/desktop/src/i18n/locales/zh-CN.ts | 12 + apps/desktop/src/i18n/locales/zh-TW.ts | 12 + .../connectionDialogScrolling.spec.ts | 17 + apps/desktop/src/types/database.ts | 5 +- crates/dbx-core/src/connection.rs | 3 +- crates/dbx-core/src/db/mod.rs | 2 + crates/dbx-core/src/db/ssh_host_key.rs | 115 ++++ crates/dbx-core/src/db/ssh_prompt.rs | 168 ++++++ crates/dbx-core/src/db/ssh_tunnel.rs | 550 +++++++++++++++++- crates/dbx-core/src/models/connection.rs | 4 +- crates/dbx-core/src/ssh_config.rs | 10 + crates/dbx-core/src/storage.rs | 14 +- docs/content/docs/ssh-tunnel.cn.mdx | 11 +- docs/content/docs/ssh-tunnel.mdx | 11 +- src-tauri/src/commands/mod.rs | 1 + src-tauri/src/commands/ssh_prompt.rs | 317 ++++++++++ src-tauri/src/lib.rs | 6 + 27 files changed, 1566 insertions(+), 37 deletions(-) create mode 100644 apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue create mode 100644 apps/desktop/src/lib/__tests__/connection/connectionDialogScrolling.spec.ts create mode 100644 crates/dbx-core/src/db/ssh_host_key.rs create mode 100644 crates/dbx-core/src/db/ssh_prompt.rs create mode 100644 src-tauri/src/commands/ssh_prompt.rs diff --git a/.gitignore b/.gitignore index e9c502dbc4..af321acf03 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ node_modules/ .claude/ .codex/ +.workbuddy/ .superpowers/ .trellis/ .worktrees/ diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue index 75b85f48d3..6b6d4439b5 100644 --- a/apps/desktop/src/components/connection/ConnectionDialog.vue +++ b/apps/desktop/src/components/connection/ConnectionDialog.vue @@ -2721,7 +2721,8 @@ const sqlServerDriverMode = computed<"auto" | "legacy">(() => (sqlServerUsesLega const shouldUseWideConnectionDialog = computed(() => dialogStep.value === "config" && (canChooseVisibleDatabases.value || (canChooseVisibleSchemas.value && !visibleFilterUsesSchemas.value))); const connectionDialogContentClass = computed(() => { if (dialogStep.value === "select") return "connection-dialog-content--picker sm:h-[720px] sm:max-w-[880px]"; - return shouldUseWideConnectionDialog.value ? "connection-dialog-content--wide sm:max-w-[660px]" : "connection-dialog-content--standard sm:max-w-[560px]"; + const widthClass = shouldUseWideConnectionDialog.value ? "connection-dialog-content--wide sm:max-w-[660px]" : "connection-dialog-content--standard sm:max-w-[560px]"; + return `${widthClass} connection-dialog-content--config`; }); const connectionLabelClass = "justify-self-start text-left"; const connectionLabelSmallClass = `${connectionLabelClass} text-xs`; @@ -4103,15 +4104,16 @@ function isLegacySshAgentMethod(hop: Partial | null | undefined function updateSelectedSshAuthMethod(value: unknown) { const layer = selectedSshLayer.value; if (!layer) return; - layer.auth_method = value === "key" ? "key" : value === "none" ? "none" : "password"; + layer.auth_method = value === "key" ? "key" : value === "key+password" ? "key+password" : value === "none" ? "none" : "password"; // Scrub credential fields that do not apply to the selected method so // they are not accidentally submitted or used by the backend fallback. - if (layer.auth_method !== "password") layer.password = ""; - if (layer.auth_method !== "key") { + // "key+password" keeps both key and password fields. + if (layer.auth_method !== "password" && layer.auth_method !== "key+password") layer.password = ""; + if (layer.auth_method !== "key" && layer.auth_method !== "key+password") { layer.key_path = ""; layer.key_passphrase = ""; } - if (layer.auth_method !== "key") { + if (layer.auth_method !== "key" && layer.auth_method !== "key+password") { layer.use_ssh_agent = false; } resetTestState(); @@ -6611,12 +6613,13 @@ function openExternalUrl(url: string) { {{ t("connection.sshAuthMethodPassword") }} {{ t("connection.sshAuthMethodKey") }} + {{ t("connection.sshAuthMethodKeyPassword") }} {{ t("connection.sshAuthMethodNone") }} {{ t("connection.sshAuthMethodAgentLegacy") }} -
+
@@ -6630,11 +6633,11 @@ function openExternalUrl(url: string) {
-
+
-
+
@@ -6984,6 +6987,22 @@ function openExternalUrl(url: string) { max-height: calc(var(--dbx-viewport-height) - 2rem); } +.connection-dialog-content--config { + min-height: 0; +} + +@media (max-height: 720px) { + .connection-dialog-content--config { + /* A definite flex height lets tab bodies shrink and scroll above the fixed footer. */ + height: calc(var(--dbx-viewport-height) - 2rem); + } + + .connection-dialog-content--config .connection-form-body { + /* Keep grid rows compact when the scroll viewport is taller than the form. */ + align-content: start; + } +} + /* Legacy responsive layout rules live in public/connection-dialog-legacy.css * so the production build cannot rewrite their classic media queries. */ @supports not (color: oklch(0.5 0.1 180)) { diff --git a/apps/desktop/src/components/connection/TunnelProfileManager.vue b/apps/desktop/src/components/connection/TunnelProfileManager.vue index b22b7d5fe3..528ab0dc8e 100644 --- a/apps/desktop/src/components/connection/TunnelProfileManager.vue +++ b/apps/desktop/src/components/connection/TunnelProfileManager.vue @@ -6,7 +6,9 @@ import { Input } from "@/components/ui/input"; import PasswordInput from "@/components/ui/PasswordInput.vue"; import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; -import { Loader2, Plus, Trash2 } from "@lucide/vue"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; +import { Loader2, Plus, Trash2, FolderOpen } from "@lucide/vue"; +import { isTauriRuntime } from "@/lib/backend/tauriRuntime"; import { useToast } from "@/composables/useToast"; import { useTunnelProfileStore } from "@/stores/tunnelProfileStore"; import { createTunnelProfile, createTunnelProfileTestGuard, tunnelProfileSummary, type TunnelProfileType } from "@/lib/connection/tunnelProfiles"; @@ -119,9 +121,9 @@ function removeSelected() { function updateSshAuthMethod(value: unknown) { const profile = selectedSsh.value; if (!profile) return; - profile.auth_method = value === "key" ? "key" : value === "none" ? "none" : "password"; - if (profile.auth_method !== "password") profile.password = ""; - if (profile.auth_method !== "key") { + profile.auth_method = value === "key" ? "key" : value === "key+password" ? "key+password" : value === "none" ? "none" : "password"; + if (profile.auth_method !== "password" && profile.auth_method !== "key+password") profile.password = ""; + if (profile.auth_method !== "key" && profile.auth_method !== "key+password") { profile.key_path = ""; profile.key_passphrase = ""; } @@ -133,6 +135,19 @@ function updateProxyType(value: unknown) { profile.proxy_type = value === "http" ? "http" : "socks5"; } +async function browseSshKeyPath(target?: { key_path?: string } | null) { + if (isTauriRuntime()) { + const { open } = await import("@tauri-apps/plugin-dialog"); + const selected = await open({ + title: "Select SSH Private Key", + multiple: false, + }); + if (selected && typeof selected === "string" && target) { + target.key_path = selected; + } + } +} + async function save() { if (isSaving.value) return; invalidateProfileTest(); @@ -229,19 +244,30 @@ async function testSelected() { {{ t("connection.sshAuthMethodPassword") }} {{ t("connection.sshAuthMethodKey") }} + {{ t("connection.sshAuthMethodKeyPassword") }} {{ t("connection.sshAuthMethodNone") }}
-
+
-
+
- +
+ + + + + + {{ t("connection.sshKeyPathBrowse") }} + +
-
+
diff --git a/apps/desktop/src/components/layout/AppDialogs.vue b/apps/desktop/src/components/layout/AppDialogs.vue index 5b76c2fb72..e4389314b3 100644 --- a/apps/desktop/src/components/layout/AppDialogs.vue +++ b/apps/desktop/src/components/layout/AppDialogs.vue @@ -15,6 +15,7 @@ const TableImportDialog = defineAsyncComponent(() => import("@/components/import const FieldLineageDialog = defineAsyncComponent(() => import("@/components/lineage/FieldLineageDialog.vue")); const ConfigPassphraseDialog = defineAsyncComponent(() => import("@/components/config/ConfigPassphraseDialog.vue")); const DatabaseSearchDialog = defineAsyncComponent(() => import("@/components/search/DatabaseSearchDialog.vue")); +const SshHostKeyPromptDialog = defineAsyncComponent(() => import("@/components/ssh/SshHostKeyPromptDialog.vue")); const DatabaseExportDialog = defineAsyncComponent(() => import("@/components/export/DatabaseExportDialog.vue")); const DataGenerateDialog = defineAsyncComponent(() => import("@/components/generate/DataGenerateDialog.vue")); import { useConnectionStore } from "@/stores/connectionStore"; @@ -262,4 +263,5 @@ watch( + diff --git a/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue b/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue new file mode 100644 index 0000000000..3dd66034f9 --- /dev/null +++ b/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue @@ -0,0 +1,205 @@ + + + diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts index c8f4f45365..2a753a929d 100644 --- a/apps/desktop/src/i18n/locales/en.ts +++ b/apps/desktop/src/i18n/locales/en.ts @@ -542,6 +542,7 @@ export default { sshAuthMethod: "Login Method", sshAuthMethodPassword: "Password", sshAuthMethodKey: "Private Key", + sshAuthMethodKeyPassword: "Private Key + Password", sshAuthMethodNone: "None", sshAuthMethodNoneHint: "No credentials will be sent. Use this for bastions or proxies that accept unauthenticated connections.", sshAuthMethodAgentLegacy: "SSH Agent (legacy)", @@ -569,6 +570,17 @@ export default { sshUseAgent: "Use ssh-agent", sshAgentSockPath: "Agent Socket Path", sshAgentSockPathPlaceholder: "e.g. ~/.ssh/agent.sock", + sshHostKeyVerifyTitle: "Confirm Unknown SSH Host Key", + sshHostKeyVerifyMessage: "The authenticity of host '{host}:{port}' could not be established. To protect against man-in-the-middle attacks, verify the host key fingerprint with your server administrator before continuing.", + sshHostKeyVerifyKeyType: "Key type", + sshHostKeyVerifyFingerprint: "Fingerprint", + sshHostKeyVerifyRemember: "Trust this host (remember this key for future connections)", + sshHostKeyVerifyAccept: "Accept & Connect", + sshHostKeyVerifyReject: "Cancel", + sshHostKeyNoticeChanged: "Host key for {host}:{port} changed — this may indicate a man-in-the-middle attack. Remove the old entry and reconnect only if you expect this change.", + sshHostKeyNoticeRejected: "You rejected the host key for {host}:{port}; the connection was aborted and no credentials were sent.", + sshHostKeyNoticeLearnFailed: "Could not save the host key for {host}:{port} — the host is trusted for this session only and you will be asked to verify it again next time.", + sshHostKeyNoticeGeneric: "SSH host key verification failed for {host}:{port}.", sshHopInvalidTimeout: "{hop}: SSH timeout must be between 1 and 300 seconds", connectTimeout: "Connection Timeout (seconds)", queryTimeout: "Query Timeout (seconds)", diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts index 2ce001b7f8..f2715d2e8c 100644 --- a/apps/desktop/src/i18n/locales/es.ts +++ b/apps/desktop/src/i18n/locales/es.ts @@ -425,6 +425,7 @@ export default withEnglishFallback({ sshAuthMethod: "Método de acceso", sshAuthMethodPassword: "Contraseña", sshAuthMethodKey: "Clave privada", + sshAuthMethodKeyPassword: "Clave privada + Contraseña", sshAuthMethodNone: "Ninguno", sshAuthMethodNoneHint: "No se enviarán credenciales. Úsalo para bastiones o proxies que aceptan conexiones sin autenticación.", sshAuthMethodAgentLegacy: "SSH Agent (heredado)", @@ -623,6 +624,17 @@ export default withEnglishFallback({ rocketmqSecretKey: "Secret Key", rocketmqAclAuth: "ACL", jdbcMissingRuntimeDependencyHint: "El controlador JDBC actual carece de dependencias de ejecución. Utilice las coordenadas Maven en 'Administración de controladores' para instalar, o importe el controlador y todos los JAR de dependencia de una vez.", + sshHostKeyVerifyTitle: "Confirmar clave de host SSH desconocida", + sshHostKeyVerifyMessage: "No se puede confirmar la autenticidad del host '{host}:{port}'. Para evitar ataques de intermediario, verifique la huella digital de la clave del host con el administrador del servidor antes de continuar.", + sshHostKeyVerifyKeyType: "Tipo de clave", + sshHostKeyVerifyFingerprint: "Huella digital", + sshHostKeyVerifyRemember: "Confiar en este host (recordar esta clave para futuras conexiones)", + sshHostKeyVerifyAccept: "Aceptar y conectar", + sshHostKeyVerifyReject: "Cancelar", + sshHostKeyNoticeChanged: "La clave del host {host}:{port} ha cambiado, puede haber un ataque de intermediario. Si es esperado, elimine el registro antiguo y vuelva a conectar.", + sshHostKeyNoticeRejected: "Ha rechazado la verificación de la clave del host {host}:{port}. La conexión se ha abortado, no se enviaron credenciales.", + sshHostKeyNoticeGeneric: "Falló la verificación de la clave del host SSH {host}:{port}.", + sshHostKeyNoticeLearnFailed: "No se pudo guardar la clave de host de {host}:{port} — este host solo es de confianza en esta sesión, la próxima conexión requerirá confirmación nuevamente.", }, editor: { pressToExecute: "Presiona {mod}+Enter para ejecutar", diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts index 2e4498eed8..3d68a364d2 100644 --- a/apps/desktop/src/i18n/locales/it.ts +++ b/apps/desktop/src/i18n/locales/it.ts @@ -423,6 +423,7 @@ export default withEnglishFallback({ sshAuthMethod: "Metodo di accesso", sshAuthMethodPassword: "Password", sshAuthMethodKey: "Chiave privata", + sshAuthMethodKeyPassword: "Chiave privata + Password", sshAuthMethodNone: "Nessuno", sshAuthMethodNoneHint: "Non verrà inviata alcuna credenziale. Usalo per bastion host o proxy che accettano connessioni senza autenticazione.", sshAuthMethodAgentLegacy: "SSH Agent (legacy)", @@ -621,6 +622,17 @@ export default withEnglishFallback({ rocketmqSecretKey: "Secret Key", rocketmqAclAuth: "ACL", jdbcMissingRuntimeDependencyHint: "Il driver JDBC corrente manca di dipendenze runtime. Installare utilizzando le coordinate Maven in 'Gestione driver', o importare il driver e tutti i JAR delle dipendenze in una volta.", + sshHostKeyVerifyTitle: "Conferma chiave host SSH sconosciuta", + sshHostKeyVerifyMessage: "Impossibile confermare l'autenticità dell'host '{host}:{port}'. Per prevenire attacchi man-in-the-middle, verifica l'impronta della chiave host con l'amministratore del server prima di procedere.", + sshHostKeyVerifyKeyType: "Tipo di chiave", + sshHostKeyVerifyFingerprint: "Impronta", + sshHostKeyVerifyRemember: "Fidati di questo host (ricorda la chiave per connessioni future)", + sshHostKeyVerifyAccept: "Accetta e connetti", + sshHostKeyVerifyReject: "Annulla", + sshHostKeyNoticeChanged: "La chiave dell'host {host}:{port} è cambiata, potrebbe esserci un attacco man-in-the-middle. Se il cambiamento è previsto, elimina il vecchio record e riconnettiti.", + sshHostKeyNoticeRejected: "Hai rifiutato la verifica della chiave host di {host}:{port}, la connessione è stata interrotta e le credenziali non sono state inviate.", + sshHostKeyNoticeGeneric: "Verifica della chiave host SSH {host}:{port} fallita.", + sshHostKeyNoticeLearnFailed: "Impossibile salvare la chiave host di {host}:{port} — Questo host è considerato affidabile solo per questa sessione, alla prossima connessione sarà necessaria una nuova conferma.", }, editor: { pressToExecute: "Premi {mod}+Enter per eseguire", diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts index aceaf048a3..f844c91c0b 100644 --- a/apps/desktop/src/i18n/locales/ja.ts +++ b/apps/desktop/src/i18n/locales/ja.ts @@ -417,6 +417,7 @@ export default withEnglishFallback({ sshAuthMethod: "ログイン方式", sshAuthMethodPassword: "パスワード", sshAuthMethodKey: "秘密鍵", + sshAuthMethodKeyPassword: "秘密鍵 + パスワード", sshAuthMethodNone: "なし", sshAuthMethodNoneHint: "認証情報は送信されません。無認証接続を許可する踏み台やプロキシに使用してください。", sshAuthMethodAgentLegacy: "SSH Agent(旧)", @@ -621,6 +622,17 @@ export default withEnglishFallback({ rocketmqSecretKey: "Secret Key", rocketmqAclAuth: "ACL", jdbcMissingRuntimeDependencyHint: "現在のJDBCドライバーには実行依存関係が不足しています。「ドライバ管理」でMaven座標を使用してインストールするか、ドライバーとすべての依存JARを一度にインポートしてください。", + sshHostKeyVerifyTitle: "不明なSSHホストキーの確認", + sshHostKeyVerifyMessage: "ホスト '{host}:{port}' の正当性を確認できません。中間者攻撃を防ぐため、続行する前にサーバー管理者にホストキーのフィンガープリントを確認してください。", + sshHostKeyVerifyKeyType: "キータイプ", + sshHostKeyVerifyFingerprint: "フィンガープリント", + sshHostKeyVerifyRemember: "このホストを信頼する(今後の接続のためにキーを記憶する)", + sshHostKeyVerifyAccept: "承諾して接続", + sshHostKeyVerifyReject: "キャンセル", + sshHostKeyNoticeChanged: "ホスト {host}:{port} のキーが変更されました。中間者攻撃の可能性があります。予期された変更である場合は、古いレコードを削除して再接続してください。", + sshHostKeyNoticeRejected: "ホスト {host}:{port} のホストキー検証を拒否しました。接続は中止され、資格情報は送信されませんでした。", + sshHostKeyNoticeGeneric: "SSHホスト {host}:{port} のキー検証に失敗しました。", + sshHostKeyNoticeLearnFailed: "{host}:{port} のホストキーを保存できません — このホストは現在のセッションでのみ信頼され、次回の接続時に再確認が必要です。", }, editor: { pressToExecute: "{mod}+Enter で実行", diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts index 7e0479954b..10d38c4052 100644 --- a/apps/desktop/src/i18n/locales/pt-BR.ts +++ b/apps/desktop/src/i18n/locales/pt-BR.ts @@ -424,6 +424,7 @@ export default withEnglishFallback({ sshAuthMethod: "Método de login", sshAuthMethodPassword: "Senha", sshAuthMethodKey: "Chave privada", + sshAuthMethodKeyPassword: "Chave privada + Senha", sshAuthMethodNone: "Nenhum", sshAuthMethodNoneHint: "Nenhuma credencial será enviada. Use para bastiões ou proxies que aceitam conexões sem autenticação.", sshAuthMethodAgentLegacy: "SSH Agent (legado)", @@ -622,6 +623,17 @@ export default withEnglishFallback({ rocketmqSecretKey: "Secret Key", rocketmqAclAuth: "ACL", jdbcMissingRuntimeDependencyHint: "O driver JDBC atual está sem dependências de execução. Por favor, instale-o usando as coordenadas Maven no 'Gerenciamento de Drivers' ou importe o driver e todos os JARs de dependência de uma só vez.", + sshHostKeyVerifyTitle: "Confirmar chave de host SSH desconhecida", + sshHostKeyVerifyMessage: "Não foi possível confirmar a autenticidade do host '{host}:{port}'. Para evitar ataques man-in-the-middle, verifique a impressão digital da chave do host com o administrador do servidor antes de continuar.", + sshHostKeyVerifyKeyType: "Tipo de chave", + sshHostKeyVerifyFingerprint: "Impressão digital", + sshHostKeyVerifyRemember: "Confiar neste host (lembrar desta chave para conexões futuras)", + sshHostKeyVerifyAccept: "Aceitar e conectar", + sshHostKeyVerifyReject: "Cancelar", + sshHostKeyNoticeChanged: "A chave do host {host}:{port} foi alterada, pode haver um ataque man-in-the-middle. Se esta alteração era esperada, exclua o registro antigo e reconecte.", + sshHostKeyNoticeRejected: "Você rejeitou a verificação da chave do host {host}:{port}. A conexão foi abortada e as credenciais não foram enviadas.", + sshHostKeyNoticeGeneric: "Falha na verificação da chave do host SSH {host}:{port}.", + sshHostKeyNoticeLearnFailed: "Não foi possível salvar a chave do host {host}:{port} — o host é confiável apenas nesta sessão, necessitando reconfirmação na próxima conexão.", }, editor: { pressToExecute: "Pressione {mod}+Enter para executar", diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts index bcfda846ed..ea9059310d 100644 --- a/apps/desktop/src/i18n/locales/zh-CN.ts +++ b/apps/desktop/src/i18n/locales/zh-CN.ts @@ -545,6 +545,7 @@ export default withEnglishFallback({ sshAuthMethod: "登录方式", sshAuthMethodPassword: "密码", sshAuthMethodKey: "私钥", + sshAuthMethodKeyPassword: "私钥 + 密码", sshAuthMethodNone: "无认证", sshAuthMethodNoneHint: "不会发送任何凭据,适用于接受无认证连接的 bastion 或代理。", sshAuthMethodAgentLegacy: "SSH Agent(旧版)", @@ -572,6 +573,17 @@ export default withEnglishFallback({ sshUseAgent: "使用 ssh-agent", sshAgentSockPath: "Agent Socket 路径", sshAgentSockPathPlaceholder: "如 ~/.ssh/agent.sock", + sshHostKeyVerifyTitle: "确认未知的 SSH 主机密钥", + sshHostKeyVerifyMessage: "无法确认主机 '{host}:{port}' 的真实性。为防止中间人攻击,请在继续前与服务器管理员核对主机密钥指纹。", + sshHostKeyVerifyKeyType: "密钥类型", + sshHostKeyVerifyFingerprint: "指纹", + sshHostKeyVerifyRemember: "信任此主机(记住该密钥用于以后的连接)", + sshHostKeyVerifyAccept: "接受并连接", + sshHostKeyVerifyReject: "取消", + sshHostKeyNoticeChanged: "主机 {host}:{port} 的密钥已变更,可能存在中间人攻击。如确属预期,请删除旧记录后重新连接。", + sshHostKeyNoticeRejected: "你已拒绝 {host}:{port} 的主机密钥验证,连接已中止,凭据未发送。", + sshHostKeyNoticeLearnFailed: "无法保存 {host}:{port} 的主机密钥 — 该主机仅在本次会话内受信任,下次连接仍需重新确认。", + sshHostKeyNoticeGeneric: "SSH 主机 {host}:{port} 的密钥验证失败。", sshHopInvalidTimeout: "{hop}:SSH 超时时间必须在 1 到 300 秒之间", connectTimeout: "连接超时(秒)", queryTimeout: "查询超时(秒)", diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts index 19c348286e..c7ff6e644b 100644 --- a/apps/desktop/src/i18n/locales/zh-TW.ts +++ b/apps/desktop/src/i18n/locales/zh-TW.ts @@ -423,6 +423,7 @@ export default withEnglishFallback({ sshAuthMethod: "登入方式", sshAuthMethodPassword: "密碼", sshAuthMethodKey: "私鑰", + sshAuthMethodKeyPassword: "私鑰 + 密碼", sshAuthMethodNone: "無認證", sshAuthMethodNoneHint: "不會傳送任何憑證,適用於接受無認證連線的 bastion 或代理伺服器。", sshAuthMethodAgentLegacy: "SSH Agent(舊版)", @@ -621,6 +622,17 @@ export default withEnglishFallback({ rocketmqSecretKey: "Secret Key", rocketmqAclAuth: "ACL", jdbcMissingRuntimeDependencyHint: "目前 JDBC 驅動缺少執行依賴。請在「驅動管理」中使用 Maven 座標安裝,或一次匯入驅動及全部依賴 JAR。", + sshHostKeyVerifyTitle: "確認未知的 SSH 主機金鑰", + sshHostKeyVerifyMessage: "無法確認主機 '{host}:{port}' 的真實性。為防止中間人攻擊,請在繼續前與伺服器管理員核對主機金鑰指紋。", + sshHostKeyVerifyKeyType: "金鑰類型", + sshHostKeyVerifyFingerprint: "指紋", + sshHostKeyVerifyRemember: "信任此主機(記住此金鑰用於之後的連線)", + sshHostKeyVerifyAccept: "接受並連線", + sshHostKeyVerifyReject: "取消", + sshHostKeyNoticeChanged: "主機 {host}:{port} 的金鑰已變更,可能存在中間人攻擊。如確屬預期,請刪除舊記錄後重新連線。", + sshHostKeyNoticeRejected: "您已拒絕 {host}:{port} 的主機金鑰驗證,連線已中止,憑證未發送。", + sshHostKeyNoticeGeneric: "SSH 主機 {host}:{port} 的金鑰驗證失敗。", + sshHostKeyNoticeLearnFailed: "無法儲存 {host}:{port} 的主機金鑰 — 該主機僅在本次會話內受信任,下次連線仍需重新確認。", }, editor: { pressToExecute: "按 {mod}+Enter 執行查詢", diff --git a/apps/desktop/src/lib/__tests__/connection/connectionDialogScrolling.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionDialogScrolling.spec.ts new file mode 100644 index 0000000000..80152b9e2a --- /dev/null +++ b/apps/desktop/src/lib/__tests__/connection/connectionDialogScrolling.spec.ts @@ -0,0 +1,17 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; + +const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8"); + +describe("connection dialog scrolling", () => { + it("gives the configuration step a definite viewport-constrained height", () => { + expect(dialogSource).toContain("return `${widthClass} connection-dialog-content--config`;"); + expect(dialogSource).toMatch(/\.connection-dialog-content--config\s*\{[\s\S]*?min-height:\s*0;[\s\S]*?@media \(max-height: 720px\)[\s\S]*?height:\s*calc\(var\(--dbx-viewport-height\) - 2rem\);/); + expect(dialogSource).toMatch(/\.connection-dialog-content--config \.connection-form-body\s*\{[\s\S]*?align-content:\s*start;/); + }); + + it("keeps the transport form inside a shrinkable scroll viewport", () => { + expect(dialogSource).toContain(''); + expect(dialogSource).toContain('class="connection-form-body grid h-full min-h-0 gap-4 overflow-y-auto overflow-x-hidden pt-4 pr-2"'); + }); +}); diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts index c3f1b3ec88..cc9442be6a 100644 --- a/apps/desktop/src/types/database.ts +++ b/apps/desktop/src/types/database.ts @@ -219,11 +219,14 @@ export interface SshTunnelConfig { * back to key > password > agent based on which fields are non-empty, * independent of this selector (see `db/ssh_tunnel.rs`). * + * `"key+password"` tries private key auth first and falls back to + * password auth if the key is rejected. + * * `"agent"` is a legacy value: it's no longer offered as a dropdown * choice for new connections, but is preserved and displayed read-only * for connections that already have `use_ssh_agent` configured. */ - auth_method?: "password" | "key" | "agent" | "none"; + auth_method?: "password" | "key" | "key+password" | "agent" | "none"; /** * When set, this layer references a shared tunnel profile; the profile's * configuration replaces this layer's fields at connect time (only `id` diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs index 4f53f140df..fd13b0ac4f 100644 --- a/crates/dbx-core/src/connection.rs +++ b/crates/dbx-core/src/connection.rs @@ -627,6 +627,7 @@ impl AppState { agent_dir: PathBuf, app_version: impl Into, ) -> Self { + let data_dir = storage.data_dir().to_path_buf(); Self { connections: Arc::new(RwLock::new(HashMap::new())), task_supervisor: TaskSupervisor::new(), @@ -635,7 +636,7 @@ impl AppState { connection_attempts: RwLock::new(HashMap::new()), configs: RwLock::new(HashMap::new()), running_queries: RunningQueries::default(), - tunnels: TunnelManager::new(), + tunnels: TunnelManager::new(data_dir), proxy_tunnels: ProxyTunnelManager::new(), http_tunnels: HttpTunnelManager::new(), storage, diff --git a/crates/dbx-core/src/db/mod.rs b/crates/dbx-core/src/db/mod.rs index c40a97ca41..fda73dd093 100644 --- a/crates/dbx-core/src/db/mod.rs +++ b/crates/dbx-core/src/db/mod.rs @@ -30,6 +30,8 @@ pub mod redis_driver; pub mod rqlite_driver; pub mod sqlite; pub mod sqlserver; +pub mod ssh_host_key; +pub mod ssh_prompt; pub mod ssh_tunnel; pub mod starrocks; pub mod transport_layer_tunnel; diff --git a/crates/dbx-core/src/db/ssh_host_key.rs b/crates/dbx-core/src/db/ssh_host_key.rs new file mode 100644 index 0000000000..6334941df5 --- /dev/null +++ b/crates/dbx-core/src/db/ssh_host_key.rs @@ -0,0 +1,115 @@ +//! Host-key verification for the SSH tunnel client. +//! +//! Before any credential is sent, russh invokes +//! [`russh::client::Handler::check_server_key`]. The original implementation +//! accepted *every* server key, which let a man-in-the-middle endpoint reject +//! the public key and trick the client into sending the password instead. +//! This module makes that callback actually verify the server identity. +//! +//! Design +//! ------ +//! Verification is layered and **fail-closed**, reusing russh's own OpenSSH- +//! format `known_hosts` module instead of a hand-rolled store: +//! +//! 1. The user's system `~/.ssh/known_hosts` is checked **read-only**. Reusing +//! it means a host already trusted in a terminal is also trusted here, and a +//! key change recorded there is detected here too. dbx never *writes* to it. +//! 2. dbx's own store at `/known_hosts` (OpenSSH format, managed by +//! russh's `known_hosts` module) is checked. This is where dbx-accepted host +//! keys live — NOT `~/.ssh` — so we never pollute the user's SSH config. +//! 3. An unknown host is reported as [`HostKeyState::Unknown`]; the caller +//! (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`]. +//! +//! 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. +//! * If an unknown host's key **cannot be persisted** (e.g. no write permission +//! on ``), `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 russh::keys::known_hosts::{check_known_hosts, check_known_hosts_path, learn_known_hosts_path}; +use russh::keys::ssh_key::PublicKey; + +/// Outcome of checking a server key against the known-hosts stores. +#[derive(Debug, Clone, Copy, 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, +} + +/// Host-key verifier backed by russh's OpenSSH-format known-hosts store. +/// +/// `known_hosts_path` is the dbx-managed store (typically +/// `/known_hosts`). The system `~/.ssh/known_hosts` is also consulted +/// read-only via [`check_known_hosts`]. +pub struct HostKeyVerifier { + known_hosts_path: PathBuf, +} + +impl HostKeyVerifier { + /// Creates a verifier that records/reads accepted host keys at `known_hosts_path`. + pub fn new(known_hosts_path: PathBuf) -> Self { + 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. + pub fn check(&self, host: &str, port: u16, key: &PublicKey) -> Result { + // 1. System known_hosts (read-only). A changed key there is a hard reject. + match check_known_hosts(host, port, key) { + Ok(true) => return Ok(HostKeyState::Trusted), + Err(russh::keys::Error::KeyChanged { line }) => { + return Err(host_key_changed_error(host, port, line, "~/.ssh/known_hosts")); + } + // Missing system file, no home dir, or an unreadable system file: + // don't fail the whole connection on it; fall through to the dbx + // store / TOFU, which still protects against MITM. + _ => {} + } + + // 2. dbx-managed known_hosts. + 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())); + } + // Unknown (or an unreadable dbx store): report as a candidate for TOFU. + _ => {} + } + + Ok(HostKeyState::Unknown) + } + + /// Records a host key into the dbx store (TOFU persistence). Called by the + /// caller only after the user explicitly accepts the key. A write failure + /// is reported (so the caller knows persistence did not happen) but does + /// not by itself abort the session — the host may simply be trusted for + /// this session only. + pub fn learn(&self, host: &str, port: u16, key: &PublicKey) -> Result<(), io::Error> { + learn_known_hosts_path(host, port, key, &self.known_hosts_path).map_err(|e| { + io::Error::new( + io::ErrorKind::PermissionDenied, + format!( + "Failed to persist host key for {host}:{port} to {} ({e}). \ + The host is trusted for this session only.", + self.known_hosts_path.display() + ), + ) + }) + } +} + +fn host_key_changed_error(host: &str, port: u16, line: usize, store: &str) -> io::Error { + io::Error::other(format!( + "Host key for {host}:{port} changed (recorded at {store}, line {line}). \ + This may indicate a man-in-the-middle attack. Remove the old entry and reconnect only if you expect this change." + )) +} diff --git a/crates/dbx-core/src/db/ssh_prompt.rs b/crates/dbx-core/src/db/ssh_prompt.rs new file mode 100644 index 0000000000..a17f17dfbb --- /dev/null +++ b/crates/dbx-core/src/db/ssh_prompt.rs @@ -0,0 +1,168 @@ +//! Interactive SSH prompt bridge between the backend (russh handshake / +//! authentication callbacks) and the frontend UI. +//! +//! russh invokes `Handler::check_server_key` *before* any credential is sent, +//! and (in the future) drives keyboard-interactive challenges mid-auth. Both +//! need to pause the backend task, ask the user via a dialog, and resume with +//! the answer. This module provides a process-wide gateway so the backend can +//! suspend on a `oneshot` while the Tauri layer forwards the request to the UI +//! and the UI answers through a command. +//! +//! The gateway is installed once at app startup by the Tauri layer +//! (`install_ssh_prompt_gateway`). In headless / test contexts where no +//! gateway is installed, `request_ssh_prompt` returns `None` and callers MUST +//! fail closed — never trust an unverified host, never send a credential. + +use std::sync::Mutex; + +use serde::{Deserialize, Serialize}; +use tokio::sync::{mpsc, oneshot}; +use uuid::Uuid; + +/// What kind of input the UI should present. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SshPromptKind { + /// Confirm/deny a server host key (explicit TOFU). + HostKeyVerify, + /// Collect a secret typed by the user (e.g. a dynamic verification code). + /// Reserved for the future keyboard-interactive flow. + SecretInput, +} + +/// A request for user input, sent from the backend to the UI. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SshPromptRequest { + /// Unique id; the UI echoes it back when answering. + pub id: String, + pub kind: SshPromptKind, + pub host: String, + pub port: u16, + /// HostKeyVerify: key algorithm, e.g. `ssh-ed25519`. + #[serde(default)] + pub key_type: Option, + /// HostKeyVerify: SHA256 fingerprint string, e.g. `SHA256:xxxx`. + #[serde(default)] + pub fingerprint: Option, + /// SecretInput: the challenge text to show the user. + #[serde(default)] + pub prompt: Option, +} + +/// The user's answer, sent from the UI back to the backend. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum SshPromptAnswer { + /// Accept and (for HostKeyVerify) optionally persist the key. + Accept { remember: bool }, + /// Reject. + Reject, + /// A typed secret (SecretInput). + Secret(String), +} + +/// Internal envelope: the request plus the channel to deliver the answer on. +pub struct SshPromptEnvelope { + pub request: SshPromptRequest, + pub responder: oneshot::Sender, +} + +static PROMPT_GATEWAY: Mutex>> = Mutex::new(None); + +/// Install the prompt gateway. Called once at app startup by the Tauri layer. +/// Tests may call it to inject their own gateway (overwriting any previous one). +pub fn install_ssh_prompt_gateway(tx: mpsc::Sender) { + *PROMPT_GATEWAY.lock().unwrap() = Some(tx); +} + +/// Clear the gateway (mainly for tests). +pub fn clear_ssh_prompt_gateway() { + *PROMPT_GATEWAY.lock().unwrap() = None; +} + +/// Request input from the UI. Returns the receiver the caller should await, or +/// `None` if no gateway is installed (caller must fail closed). +pub fn request_ssh_prompt(request: SshPromptRequest) -> Option> { + let tx = PROMPT_GATEWAY.lock().unwrap().clone()?; + let (responder_tx, responder_rx) = oneshot::channel(); + match tx.try_send(SshPromptEnvelope { request, responder: responder_tx }) { + // Channel full or disconnected: treat as unavailable -> fail closed. + Ok(()) => Some(responder_rx), + Err(_) => None, + } +} + +/// Build a [`SshPromptRequest`] for host-key verification with a fresh id. +pub fn host_key_verify_request( + host: &str, + port: u16, + key_type: Option, + fingerprint: Option, +) -> SshPromptRequest { + SshPromptRequest { + id: Uuid::new_v4().to_string(), + kind: SshPromptKind::HostKeyVerify, + host: host.to_string(), + port, + key_type, + fingerprint, + prompt: None, + } +} + +/// Out-of-band notice about host-key verification outcomes that the user should +/// see even when the connection ultimately fails (e.g. the key changed => a +/// possible MITM, or the user explicitly rejected the host). Unlike +/// [`SshPromptRequest`] these do not block the handshake — they are fired +/// best-effort so the UI can surface a clear, human-readable reason for the +/// failure. They never affect the connection outcome, which is decided by the +/// caller's return value (fail-closed always wins). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SshHostKeyNoticeKind { + /// The server's key changed vs a known entry — possible man-in-the-middle. + Changed, + /// The user rejected the host key in the explicit-TOFU dialog. + Rejected, + /// The user accepted the host key (with "remember this host") but the + /// host-key store could not be written — the host is therefore trusted + /// for this session only and will be re-prompted on the next connect. + LearnFailed, +} + +/// A best-effort notice delivered to the UI (see [`SshHostKeyNoticeKind`]). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SshHostKeyNotice { + pub kind: SshHostKeyNoticeKind, + pub host: String, + pub port: u16, + /// Human-readable detail (e.g. the recorded location/line for a changed + /// key). The UI may show this verbatim or use `kind` to pick a translation. + pub message: String, +} + +static NOTICE_GATEWAY: Mutex>> = Mutex::new(None); + +/// Install the host-key notice gateway. Called once at app startup by the Tauri +/// layer. Tests generally do not install it; see [`notify_host_key`]. +pub fn install_ssh_notice_gateway(tx: mpsc::Sender) { + *NOTICE_GATEWAY.lock().unwrap() = Some(tx); +} + +/// Clear the notice gateway (mainly for tests). +pub fn clear_ssh_notice_gateway() { + *NOTICE_GATEWAY.lock().unwrap() = None; +} + +/// Best-effort: deliver a host-key notice to the UI. Returns `false` (and +/// silently no-ops) when no UI gateway is installed, when the channel is full, +/// or when the receiver is gone. This is purely informational and must never +/// change the connection decision taken by the caller. +pub fn notify_host_key(kind: SshHostKeyNoticeKind, host: &str, port: u16, message: &str) -> bool { + let tx = match NOTICE_GATEWAY.lock().unwrap().clone() { + Some(tx) => tx, + None => return false, + }; + match tx.try_send(SshHostKeyNotice { kind, host: host.to_string(), port, message: message.to_string() }) { + Ok(()) => true, + // Channel full or disconnected: treat as unavailable -> silently drop. + Err(_) => false, + } +} diff --git a/crates/dbx-core/src/db/ssh_tunnel.rs b/crates/dbx-core/src/db/ssh_tunnel.rs index e4fd0d240f..4b9b56e66e 100644 --- a/crates/dbx-core/src/db/ssh_tunnel.rs +++ b/crates/dbx-core/src/db/ssh_tunnel.rs @@ -1,15 +1,19 @@ use std::borrow::Cow; use std::collections::HashMap; use std::fs; +use std::path::{Path, PathBuf}; use crate::path_utils::expand_tilde; use std::sync::Arc; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use base64::Engine; -use russh::client::{self, Config, Handle}; +use russh::client::{self, AuthResult, Config, Handle}; use russh::keys::agent::{client::AgentClient, AgentIdentity}; +use russh::keys::ssh_key::HashAlg; use russh::keys::{decode_secret_key, key::PrivateKeyWithHashAlg, PrivateKey}; +use russh::MethodKind; +use russh::MethodSet; use russh::{kex, mac, ChannelMsg, Preferred}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpListener; @@ -17,6 +21,8 @@ use tokio::sync::Mutex; use tokio::task::JoinHandle; use tokio::time::{Duration, MissedTickBehavior}; +use crate::db::ssh_host_key::{HostKeyState, HostKeyVerifier}; +use crate::db::ssh_prompt; use crate::models::connection::SshTunnelConfig; use super::file_validator::validate_file_path; @@ -31,17 +37,112 @@ const MAX_RECONNECT_ATTEMPTS: u32 = 10; const IDLE_SESSION_CHECK_INTERVAL: Duration = Duration::from_secs(30); /// Maximum time to wait for an explicit SSH ping response. const IDLE_SESSION_PING_TIMEOUT: Duration = Duration::from_secs(10); +/// Maximum time to wait for the UI to answer a host-key verification prompt +/// (explicit TOFU). Fail-closed: if the UI does not answer in time, the host +/// is rejected and no credential is sent. +const TOFU_PROMPT_TIMEOUT: Duration = Duration::from_secs(300); -struct SshClient; +/// SSH client handler. Holds a host-key verifier so that +/// [`client::Handler::check_server_key`] can reject untrusted/changed server +/// keys *before* any credential is sent. +struct SshClient { + host_key_verifier: Arc, + host: String, + port: u16, +} impl client::Handler for SshClient { type Error = russh::Error; async fn check_server_key( &mut self, - _server_public_key: &russh::keys::ssh_key::PublicKey, + server_public_key: &russh::keys::ssh_key::PublicKey, ) -> Result { - Ok(true) + // 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. + 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, + Err(e) => { + // Changed host key => possible MITM. Surface it to the user as a + // clear notice (best-effort; never affects the fail-closed below). + let msg = e.to_string(); + let _ = + ssh_prompt::notify_host_key(ssh_prompt::SshHostKeyNoticeKind::Changed, &self.host, self.port, &msg); + Err(russh::Error::from(e)) + } + } + } +} + +impl SshClient { + /// Explicit TOFU: ask the UI to confirm an unknown host key. Fail-closed: + /// if no gateway is installed, or the user rejects, or the prompt times + /// out, the host is not trusted and the handshake is aborted — so no + /// credential is ever sent to an unverified endpoint. + async fn prompt_for_host_key( + &mut self, + server_public_key: &russh::keys::ssh_key::PublicKey, + ) -> Result { + 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 Some(responder_rx) = ssh_prompt::request_ssh_prompt(request) else { + log::warn!( + "No SSH prompt gateway installed; refusing to trust unknown host {}:{} (fail-closed)", + self.host, + self.port + ); + return Ok(false); + }; + + let answer = tokio::time::timeout(TOFU_PROMPT_TIMEOUT, responder_rx).await; + 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) { + // 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 + // warn the user (otherwise they will be silently + // re-prompted on next connect with no explanation). + let detail = + format!("Could not persist host key for {}:{} to known_hosts: {e}", self.host, self.port); + log::warn!("{detail}"); + let _ = ssh_prompt::notify_host_key( + ssh_prompt::SshHostKeyNoticeKind::LearnFailed, + &self.host, + self.port, + &detail, + ); + } + } + Ok(true) + } + Ok(Ok(ssh_prompt::SshPromptAnswer::Reject)) => { + // User explicitly rejected -> tell them, then fail-closed. + let _ = ssh_prompt::notify_host_key( + ssh_prompt::SshHostKeyNoticeKind::Rejected, + &self.host, + self.port, + &format!("User rejected the host key for {}:{}.", self.host, self.port), + ); + log::warn!("Host key for {}:{} was rejected by the user; aborting handshake", self.host, self.port); + Ok(false) + } + Ok(Ok(ssh_prompt::SshPromptAnswer::Secret(_))) | Ok(Err(_)) | Err(_) => { + log::warn!( + "Host key for {}:{} was not accepted (prompt timed out or was cancelled); aborting handshake", + self.host, + self.port + ); + Ok(false) + } + } } } @@ -67,6 +168,21 @@ fn ssh_client_config() -> Config { Config { nodelay: true, keepalive_interval: Some(Duration::from_secs(30)), preferred, ..Default::default() } } +/// Returns `true` only when the server explicitly advertised `password` among +/// the authentication methods that may continue the dialog. +/// +/// Per RFC 4252 §5.1, the "authentications that can continue" name-list is the +/// authoritative signal of what the server will accept next. A `partial_success` +/// flag alone is NOT a license to send a password: it merely reports that the +/// preceding step succeeded, and the next method may be something other than +/// `password` (e.g. `keyboard-interactive`). Honoring only the advertised list +/// prevents leaking the password to a server that never offered password auth +/// (the MITM credential-harvest case), while still covering publickey+password +/// MFA (where `password` IS present in the list). +fn server_offers_password(remaining_methods: &MethodSet) -> bool { + remaining_methods.contains(&MethodKind::Password) +} + #[allow(clippy::too_many_arguments)] async fn connect_and_authenticate( ssh_host: &str, @@ -79,15 +195,29 @@ async fn connect_and_authenticate( ssh_agent_sock_path: &str, auth_method: &str, connect_timeout_secs: u64, + known_hosts_path: &Path, ) -> Result, String> { let config = Arc::new(ssh_client_config()); let connect_timeout = Duration::from_secs(connect_timeout_secs); - let mut session = - tokio::time::timeout(connect_timeout, client::connect(config, (ssh_host, ssh_port), SshClient {})) - .await - .map_err(|_| format!("SSH connection timed out ({connect_timeout_secs}s)"))? - .map_err(|e| format!("SSH connection failed: {e}"))?; + // Verify server identity against the known-hosts store before sending any + // credential. The store lives at `/known_hosts` (NOT `~/.ssh`): + // an unknown host is trusted on first use (TOFU) and recorded there, a + // changed host key is rejected, and an unknown host whose key cannot be + // persisted fails closed instead of being silently trusted. + let host_key_verifier = Arc::new(HostKeyVerifier::new(known_hosts_path.to_path_buf())); + + let mut session = tokio::time::timeout( + connect_timeout, + client::connect( + config, + (ssh_host, ssh_port), + SshClient { host_key_verifier: host_key_verifier.clone(), host: ssh_host.to_string(), port: ssh_port }, + ), + ) + .await + .map_err(|_| format!("SSH connection timed out ({connect_timeout_secs}s)"))? + .map_err(|e| format!("SSH connection failed: {e}"))?; // Probe with "none" authentication first. Some SSH proxies and jump-hosts // accept connections without any credential, and this is also the standard @@ -106,6 +236,75 @@ async fn connect_and_authenticate( return Err("SSH authentication failed: server rejected the connection without credentials".to_string()); } + // "key+password": try private key first, fall back to password on failure. + // Both credential fields are expected to be filled in by the UI. + if auth_method == "key+password" { + // Attempt the private key first (when supplied), then decide whether a + // password fallback is safe to attempt. + let try_password = if ssh_key_path.is_empty() { + // No key configured: only attempt password if the "none" probe + // showed the server advertises it — otherwise we would leak the + // password to any endpoint that rejected our (empty) key. + match &none_res { + AuthResult::Failure { remaining_methods, .. } => server_offers_password(remaining_methods), + _ => false, + } + } else { + validate_file_path(ssh_key_path, |_| false)?; + + let passphrase = if ssh_key_passphrase.is_empty() { None } else { Some(ssh_key_passphrase) }; + let key_pair = + load_ssh_private_key(ssh_key_path, passphrase).map_err(|e| format!("Failed to load SSH key: {e}"))?; + let auth_res = tokio::time::timeout( + connect_timeout, + session.authenticate_publickey( + ssh_user, + PrivateKeyWithHashAlg::new( + Arc::new(key_pair), + session.best_supported_rsa_hash().await.ok().flatten().flatten(), + ), + ), + ) + .await + .map_err(|_| format!("SSH key auth timed out ({connect_timeout_secs}s)"))? + .map_err(|e| format!("SSH key auth failed: {e}"))?; + + match auth_res { + AuthResult::Success => return Ok(session), + AuthResult::Failure { remaining_methods, partial_success } => { + // Only fall back to password when the server still offers it. + // This prevents sending the password to a server that never + // advertised password auth — the MITM credential-harvest + // case — and preserves the protocol state needed for + // publickey+password MFA (where `password` IS in the list). + if server_offers_password(&remaining_methods) { + true + } else { + return Err(format!( + "SSH key rejected and the server does not offer password authentication \ + (remaining_methods={remaining_methods:?}, partial_success={partial_success})" + )); + } + } + } + }; + + if try_password && !ssh_password.is_empty() { + let auth_res = tokio::time::timeout(connect_timeout, session.authenticate_password(ssh_user, ssh_password)) + .await + .map_err(|_| format!("SSH password auth timed out ({connect_timeout_secs}s)"))? + .map_err(|e| format!("SSH password auth failed: {e}"))?; + match auth_res { + AuthResult::Success => return Ok(session), + AuthResult::Failure { partial_success, .. } => { + return Err(format!("SSH password authentication failed (partial_success={partial_success})")); + } + } + } + + return Err("SSH authentication failed: both key and password were rejected".to_string()); + } + // "none" was rejected — fall back to the configured credential method. // When auth_method is set, only try the matching method. let try_key = auth_method.is_empty() && !ssh_key_path.is_empty() || auth_method == "key"; @@ -486,6 +685,7 @@ async fn tunnel_reconnect_loop( ssh_agent_sock_path: String, auth_method: String, connect_timeout_secs: u64, + known_hosts_path: PathBuf, listener: TcpListener, remote_host: String, remote_port: u16, @@ -522,6 +722,7 @@ async fn tunnel_reconnect_loop( &ssh_agent_sock_path, &auth_method, connect_timeout_secs, + &known_hosts_path, ) .await { @@ -566,17 +767,21 @@ struct PlannedTunnel { pub struct TunnelManager { tunnels: Mutex>, + /// dbx-managed known_hosts path (`/known_hosts`) threaded into + /// every SSH connection for host-key verification. + known_hosts_path: PathBuf, } impl Default for TunnelManager { fn default() -> Self { - Self::new() + Self::new(PathBuf::new()) } } impl TunnelManager { - pub fn new() -> Self { - Self { tunnels: Mutex::new(HashMap::new()) } + pub fn new(data_dir: PathBuf) -> Self { + let known_hosts_path = data_dir.join("known_hosts"); + Self { tunnels: Mutex::new(HashMap::new()), known_hosts_path } } #[allow(clippy::too_many_arguments)] @@ -617,6 +822,7 @@ impl TunnelManager { ssh_agent_sock_path, auth_method, connect_timeout_secs, + &self.known_hosts_path, remote_host, remote_port, expose_to_lan, @@ -688,6 +894,7 @@ impl TunnelManager { &hop.ssh_agent_sock_path, &hop.auth_method, effective_hop_timeout(hop), + &self.known_hosts_path, &target_host, target_port, is_last && hop.expose_lan, @@ -749,6 +956,7 @@ async fn spawn_tunnel( ssh_agent_sock_path: &str, auth_method: &str, connect_timeout_secs: u64, + known_hosts_path: &Path, remote_host: &str, remote_port: u16, expose_to_lan: bool, @@ -771,6 +979,7 @@ async fn spawn_tunnel( ssh_agent_sock_path, auth_method, connect_timeout_secs, + known_hosts_path, ) .await?; @@ -786,6 +995,7 @@ async fn spawn_tunnel( ssh_agent_sock_path.to_string(), auth_method.to_string(), connect_timeout_secs, + known_hosts_path.to_path_buf(), listener, remote_host.to_string(), remote_port, @@ -802,6 +1012,12 @@ fn effective_hop_timeout(hop: &SshTunnelConfig) -> u64 { } } +/// Serializes every test that mutates the process-global SSH prompt gateway so +/// they cannot clobber each other's gateway (or the MITM fail-closed test, +/// which relies on *no* gateway being installed). Test-only. +#[cfg(test)] +static PROMPT_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + #[cfg(test)] fn plan_chain( hops: &[SshTunnelConfig], @@ -830,11 +1046,26 @@ fn plan_chain( #[cfg(test)] mod tests { + use super::SshClient; + use super::PROMPT_TEST_LOCK; use super::{ effective_hop_timeout, openssh_padding_len, plan_chain, read_ssh_string, - sanitize_unencrypted_openssh_comment_bytes, ssh_client_config, PlannedTunnel, TunnelManager, + sanitize_unencrypted_openssh_comment_bytes, server_offers_password, ssh_client_config, HostKeyState, + HostKeyVerifier, PlannedTunnel, TunnelManager, }; + use crate::db::ssh_prompt; use crate::models::connection::{default_ssh_connect_timeout_secs, SshTunnelConfig}; + use russh::client; + use russh::client::Handler; + use russh::keys::decode_secret_key; + use russh::keys::ssh_key::PublicKey; + use russh::server::{self, Auth, Server}; + use russh::MethodKind; + use russh::MethodSet; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; + use tempfile::tempdir; + use tokio::sync::mpsc; fn push_u32(bytes: &mut Vec, value: u32) { bytes.extend_from_slice(&value.to_be_bytes()); @@ -966,9 +1197,300 @@ mod tests { #[tokio::test] async fn local_port_reuses_existing_chain_entry() { - let manager = TunnelManager::new(); + let manager = TunnelManager::new(std::env::temp_dir().to_path_buf()); assert_eq!(manager.local_port("missing").await, None); manager.stop_tunnel("missing").await; } + + // --- Host-key verification (MITM hardening) --------------------------------- + + /// Builds the public key embedded in [`TEST_SERVER_KEY_PEM`]. The comment + /// is cleared so it matches the comment-less key parsed back from the + /// known_hosts file (real server keys presented during KEX carry no + /// comment, so this mirrors production behaviour). + fn test_server_public_key() -> PublicKey { + let mut key = + decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key").public_key().clone(); + key.set_comment(""); + key + } + + #[test] + fn tofu_unknown_host_check_then_learn_records_it() { + let dir = tempdir().unwrap(); + let path = dir.path().join("known_hosts"); + let verifier = HostKeyVerifier::new(path.clone()); + + let key = test_server_public_key(); + // Unknown host -> candidate for explicit TOFU (not silently trusted). + assert_eq!(verifier.check("db.example.com", 22, &key).unwrap(), HostKeyState::Unknown); + // User accepts -> record it via learn(). + verifier.learn("db.example.com", 22, &key).unwrap(); + // Second contact with the same key is now trusted (read back from file). + assert_eq!(verifier.check("db.example.com", 22, &key).unwrap(), HostKeyState::Trusted); + // And the key really landed in the store. + let contents = std::fs::read_to_string(&path).unwrap(); + assert!(contents.contains("db.example.com"), "recorded host missing: {contents}"); + } + + #[test] + fn changed_host_key_is_rejected() { + let dir = tempdir().unwrap(); + let path = dir.path().join("known_hosts"); + // Pre-seed the store with a *different* (valid) ed25519 key for the host. + std::fs::write( + &path, + "db.example.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIA6rWI3G1sz07DnfFlrouTcysQlj2P+jpNSOEWD9OJ3X\n", + ) + .unwrap(); + let verifier = HostKeyVerifier::new(path); + + // 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)"); + } + + #[test] + fn unknown_host_without_persist_permission_is_rejected() { + let dir = tempdir().unwrap(); + // Make the would-be parent a regular file so the store can never be + // created — this is the "no write permission" edge case. + let frozen = dir.path().join("frozen"); + std::fs::write(&frozen, b"not a directory").unwrap(); + let verifier = HostKeyVerifier::new(frozen.join("known_hosts")); + + let key = test_server_public_key(); + // Fail-closed: the unknown host is reported as a candidate, but it + // cannot be persisted (no write permission), so we must NOT trust it in + // memory — learn() must error rather than silently accept. + assert_eq!(verifier.check("db.example.com", 22, &key).unwrap(), HostKeyState::Unknown); + assert!( + verifier.learn("db.example.com", 22, &key).is_err(), + "learn must fail when the store is unwritable (fail-closed)" + ); + } + + // --- Explicit TOFU prompt bridge (HostKeyVerify) --------------------------- + + /// Spawns a fake UI gateway that answers every prompt with `answer`. + fn install_fake_prompt_gateway(answer: ssh_prompt::SshPromptAnswer) { + let (tx, mut rx) = mpsc::channel::(8); + tokio::spawn(async move { + if let Some(env) = rx.recv().await { + let _ = env.responder.send(answer); + } + }); + ssh_prompt::install_ssh_prompt_gateway(tx); + } + + #[tokio::test] + async fn unknown_host_prompt_accept_learns_key() { + let _guard = PROMPT_TEST_LOCK.lock().await; + let dir = tempdir().unwrap(); + let path = dir.path().join("known_hosts"); + 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 }; + + let trusted = client.check_server_key(&key).await.unwrap(); + assert!(trusted, "accepted host key should be trusted"); + // The accepted key must be persisted when remember=true. + let contents = std::fs::read_to_string(&path).unwrap(); + assert!(contents.contains("db.example.com"), "accepted key should be learned: {contents}"); + ssh_prompt::clear_ssh_prompt_gateway(); + } + + #[tokio::test] + async fn unknown_host_prompt_accept_without_remember_is_session_only() { + let _guard = PROMPT_TEST_LOCK.lock().await; + let dir = tempdir().unwrap(); + let path = dir.path().join("known_hosts"); + 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 }; + + let trusted = client.check_server_key(&key).await.unwrap(); + assert!(trusted, "accepted host key should be trusted for the session"); + // remember=false -> key is NOT persisted. + assert!( + !path.exists() || std::fs::read_to_string(&path).unwrap_or_default().is_empty(), + "key must not be persisted when remember=false" + ); + ssh_prompt::clear_ssh_prompt_gateway(); + } + + #[tokio::test] + async fn unknown_host_prompt_reject_aborts_handshake() { + let _guard = PROMPT_TEST_LOCK.lock().await; + let dir = tempdir().unwrap(); + let path = dir.path().join("known_hosts"); + 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 }; + + let trusted = client.check_server_key(&key).await.unwrap(); + assert!(!trusted, "rejected host key must not be trusted"); + // Rejected -> never persisted. + assert!( + !path.exists() || std::fs::read_to_string(&path).unwrap_or_default().is_empty(), + "rejected key must not be persisted" + ); + ssh_prompt::clear_ssh_prompt_gateway(); + } + + #[tokio::test] + async fn unknown_host_without_gateway_fails_closed() { + let _guard = PROMPT_TEST_LOCK.lock().await; + // Ensure no gateway is installed so request_ssh_prompt returns None. + ssh_prompt::clear_ssh_prompt_gateway(); + let dir = tempdir().unwrap(); + let path = dir.path().join("known_hosts"); + let verifier = HostKeyVerifier::new(path); + let key = test_server_public_key(); + + let mut client = + SshClient { host_key_verifier: Arc::new(verifier), host: "db.example.com".to_string(), port: 22 }; + let trusted = client.check_server_key(&key).await.unwrap(); + // No UI to confirm -> fail-closed, host is not trusted. + assert!(!trusted, "without a gateway, an unknown host must be rejected (fail-closed)"); + } + + #[tokio::test] + async fn trusted_host_skips_prompt() { + let _guard = PROMPT_TEST_LOCK.lock().await; + let dir = tempdir().unwrap(); + let path = dir.path().join("known_hosts"); + let verifier = HostKeyVerifier::new(path); + let key = test_server_public_key(); + // Pre-seed the store so the host is already trusted. + verifier.learn("db.example.com", 22, &key).unwrap(); + + // No gateway installed, but the host is trusted so no prompt is needed. + ssh_prompt::clear_ssh_prompt_gateway(); + let mut client = + SshClient { host_key_verifier: Arc::new(verifier), host: "db.example.com".to_string(), port: 22 }; + let trusted = client.check_server_key(&key).await.unwrap(); + assert!(trusted, "a known-trusted host must be accepted without a prompt"); + } + + // --- key+password fallback policy ------------------------------------------ + + #[test] + fn password_fallback_only_when_server_offers_it() { + // Server offers only publickey: never leak the password. + let only_key = MethodSet::from(&[MethodKind::PublicKey][..]); + assert!(!server_offers_password(&only_key)); + + // Server offers password too: safe to fall back. + let with_pw = MethodSet::from(&[MethodKind::PublicKey, MethodKind::Password][..]); + assert!(server_offers_password(&with_pw)); + + // No methods advertised at all: do NOT send the password, even if a + // `partial_success` flag were present — we intentionally ignore it and + // rely solely on the advertised method list (RFC 4252 §5.1). + let empty = MethodSet::empty(); + assert!(!server_offers_password(&empty)); + } + + // --- MITM hardening: a changed/unknown host never receives the password --- + + const TEST_SERVER_KEY_PEM: &str = r#"-----BEGIN OPENSSH PRIVATE KEY----- +b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW +QyNTUxOQAAACAVDlhwKBk+QMZN+WNAUKL6qLr3hf3S5p1TdSK4hMhLxwAAAJD9wI28/cCN +vAAAAAtzc2gtZWQyNTUxOQAAACAVDlhwKBk+QMZN+WNAUKL6qLr3hf3S5p1TdSK4hMhLxw +AAAEDxqdMQX37UdhziSi5Br3kyRM/Xrpo9ZcXoguYkeogq0hUOWHAoGT5Axk35Y0BQovqo +uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU= +-----END OPENSSH PRIVATE KEY-----"#; + + /// Minimal SSH server used to prove the client never sends a password to a + /// host whose key does not match the known-hosts store. `auth_password` + /// flips `password_attempted` so the test can assert it was never called. + struct MitmServer { + password_attempted: Arc, + } + + impl server::Server for MitmServer { + type Handler = MitmHandler; + fn new_client(&mut self, _peer: Option) -> MitmHandler { + MitmHandler { password_attempted: self.password_attempted.clone() } + } + } + + struct MitmHandler { + password_attempted: Arc, + } + + impl server::Handler for MitmHandler { + type Error = russh::Error; + + async fn auth_password(&mut self, _user: &str, _password: &str) -> Result { + self.password_attempted.store(true, Ordering::SeqCst); + Ok(Auth::reject()) + } + } + + #[tokio::test] + async fn unknown_host_without_persist_permission_does_not_leak_password() { + let _guard = PROMPT_TEST_LOCK.lock().await; + // This test proves the client never sends a password to an untrusted + // host. It must run with NO prompt gateway installed so the handshake + // fails closed (no UI to confirm the key -> reject before auth). + ssh_prompt::clear_ssh_prompt_gateway(); + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::Duration; + + let password_attempted = Arc::new(AtomicBool::new(false)); + + let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key"); + // Advertise password auth so it *would* be attempted if the handshake + // ever reached the authentication phase. + let server_config = server::Config { keys: vec![server_key], methods: MethodSet::all(), ..Default::default() }; + + let port = portpicker::pick_unused_port().expect("no free port"); + let mut server = MitmServer { password_attempted: password_attempted.clone() }; + let server_task = tokio::spawn(async move { + let _ = server.run_on_address(Arc::new(server_config), ("127.0.0.1", port)).await; + }); + // Let the listener bind before the client connects. + tokio::time::sleep(Duration::from_millis(300)).await; + + // Point the verifier at a path whose parent is a file, so the unknown + // host key can NEVER be persisted. dbx must fail-closed: abort the + // handshake and never send a password to an untrusted endpoint (the + // old store silently trusted it in memory — this must not happen). + let dir = tempdir().unwrap(); + let frozen = dir.path().join("frozen"); + std::fs::write(&frozen, b"not a directory").unwrap(); + let verifier = HostKeyVerifier::new(frozen.join("known_hosts")); + let handler = SshClient { host_key_verifier: Arc::new(verifier), host: "127.0.0.1".to_string(), port }; + let client_config = Arc::new(ssh_client_config()); + + let connect_result = + tokio::time::timeout(Duration::from_secs(10), client::connect(client_config, ("127.0.0.1", port), handler)) + .await; + + // The handshake must abort at the host-key check, so the server must + // never have been asked for a password. + assert!( + !password_attempted.load(Ordering::SeqCst), + "password auth must NOT be attempted for an untrusted host when the key cannot be persisted" + ); + // And the connection itself must not succeed. + assert!( + connect_result.is_err() || connect_result.unwrap().is_err(), + "connection should fail when the host key cannot be verified/persisted" + ); + + server_task.abort(); + } } diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rs index a1db687881..fd74d2f858 100644 --- a/crates/dbx-core/src/models/connection.rs +++ b/crates/dbx-core/src/models/connection.rs @@ -305,11 +305,13 @@ pub struct SshTunnelConfig { /// the `SSH_AUTH_SOCK` environment variable. #[serde(default)] pub ssh_agent_sock_path: String, - /// Login method: `"password"`, `"key"`, `"agent"`, or `"none"`. + /// Login method: `"password"`, `"key"`, `"key+password"`, `"agent"`, or `"none"`. /// Empty string means an older saved connection predating this field — /// the backend falls back to probing key > password > agent based on /// which fields are non-empty. When set to a specific method the backend /// only tries that method (after the standard `none` probe). + /// `"key+password"` tries private key auth first and falls back to + /// password auth if the key is rejected. #[serde(default)] pub auth_method: String, /// When non-empty, this layer references a shared tunnel profile diff --git a/crates/dbx-core/src/ssh_config.rs b/crates/dbx-core/src/ssh_config.rs index 2429e5cf18..479cc790be 100644 --- a/crates/dbx-core/src/ssh_config.rs +++ b/crates/dbx-core/src/ssh_config.rs @@ -264,6 +264,16 @@ mod tests { assert_eq!(resolved.auth_method, "password"); } + #[test] + fn resolve_preserves_key_plus_password_method() { + let mut ssh = config("myserver"); + ssh.auth_method = "key+password".to_string(); + ssh.password = "secret".to_string(); + let resolved = apply_host_entry(&ssh, entry("myserver")); + assert_eq!(resolved.key_path, "~/.ssh/id_ed25519"); + assert_eq!(resolved.auth_method, "key+password"); + } + #[test] fn resolve_does_not_override_explicit_values() { let mut ssh = config("myserver"); diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rs index 61a64081ac..c5c2412d35 100644 --- a/crates/dbx-core/src/storage.rs +++ b/crates/dbx-core/src/storage.rs @@ -1,5 +1,5 @@ use std::collections::{HashMap, HashSet}; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use log::warn; @@ -106,6 +106,9 @@ pub fn maybe_import_user_data_db( pub struct Storage { db: SqliteHandle, + /// Path to the SQLite database file (`dbx.db`). Its parent directory is the + /// application data dir where dbx-managed state (e.g. `known_hosts`) lives. + path: PathBuf, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -385,13 +388,20 @@ const SCHEMA_STATEMENTS: &[&str] = &[ impl Storage { pub async fn open(db_path: &Path) -> Result { + let path = db_path.to_path_buf(); let db_path = db_path.to_string_lossy().to_string(); let db = connect_path_create_if_missing(&db_path).await?; - let storage = Self { db }; + let storage = Self { db, path }; storage.init_schema().await?; Ok(storage) } + /// Directory containing the SQLite database (`dbx.db`). SSH host keys are + /// stored in `/known_hosts` so dbx never touches `~/.ssh`. + pub fn data_dir(&self) -> &Path { + self.path.parent().unwrap_or_else(|| Path::new(".")) + } + async fn init_schema(&self) -> Result<(), String> { self.db.with_connection(|conn| { for statement in SCHEMA_STATEMENTS { diff --git a/docs/content/docs/ssh-tunnel.cn.mdx b/docs/content/docs/ssh-tunnel.cn.mdx index 72c437469c..c4c384b66c 100644 --- a/docs/content/docs/ssh-tunnel.cn.mdx +++ b/docs/content/docs/ssh-tunnel.cn.mdx @@ -26,7 +26,7 @@ SSH 隧道是内置能力,不需要在终端里手动执行端口转发命令 | SSH 用户 | 登录 SSH 服务器的用户名 | | 连接超时 | DBX 等待 SSH 连接建立的最长时间,默认 5 秒 | - + 选择本地的 SSH 私钥文件,例如 `~/.ssh/id_rsa`、`~/.ssh/id_ed25519`: @@ -36,6 +36,15 @@ SSH 隧道是内置能力,不需要在终端里手动执行端口转发命令 密钥认证比密码认证更安全,推荐优先使用。 + + 以私钥为主要认证方式,密码作为回退。DBX 会先尝试密钥认证,如果服务器拒绝了密钥且仍支持密码认证,会自动回退到密码认证。 + + - **密钥路径**:浏览并选择私钥文件。 + - **密钥密码**:如果私钥设置了密码保护,在这里输入。 + - **密码**:输入 SSH 密码作为回退。 + + 适用于密钥可能被临时撤销、或多跳隧道中不同跳板需要不同认证方式的场景。 + 直接输入 SSH 用户的登录密码。适用于允许密码登录的服务器。 diff --git a/docs/content/docs/ssh-tunnel.mdx b/docs/content/docs/ssh-tunnel.mdx index 85dbf417e3..f282053c77 100644 --- a/docs/content/docs/ssh-tunnel.mdx +++ b/docs/content/docs/ssh-tunnel.mdx @@ -26,7 +26,7 @@ SSH tunnels are built in. You do not need to create a manual terminal port forwa | SSH User | Username for SSH authentication | | Connect Timeout | Maximum time DBX waits while opening the SSH connection; default is 5 seconds | - + Select a private key file (for example `~/.ssh/id_rsa` or `~/.ssh/id_ed25519`): @@ -36,6 +36,15 @@ SSH tunnels are built in. You do not need to create a manual terminal port forwa Key authentication is more secure than password authentication. + + Use a private key as the primary credential with password as a fallback. DBX tries key authentication first; if the server rejects the key and continues to offer password authentication, it automatically falls back to password authentication. + + - **Key Path** — Browse and select your key file. + - **Key Passphrase** — Enter the passphrase if your key is encrypted. + - **Password** — Enter your SSH password as a fallback. + + This is useful when a key may be temporarily revoked or when different hops in a multi-hop tunnel require different methods. + Enter your SSH password directly. This works on servers that allow password authentication. diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index de493f2454..567bf49b36 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -38,6 +38,7 @@ pub mod schema_diff; pub mod sql_file; pub mod sqlite_backup; pub mod ssh_config; +pub mod ssh_prompt; pub mod support_info; pub mod system_fonts; pub mod tab_runtime_cache; diff --git a/src-tauri/src/commands/ssh_prompt.rs b/src-tauri/src/commands/ssh_prompt.rs new file mode 100644 index 0000000000..d2cc2d2702 --- /dev/null +++ b/src-tauri/src/commands/ssh_prompt.rs @@ -0,0 +1,317 @@ +//! Bridges dbx-core's backend-driven SSH prompt gateway to the frontend. +//! +//! dbx-core suspends the SSH handshake / auth on a `oneshot` and ships the +//! request through a process-wide mpsc gateway (see `dbx_core::db::ssh_prompt`). +//! This module installs that gateway at app startup, forwards each request to +//! the UI via the `ssh-prompt` event, remembers the `oneshot` responder keyed +//! by request id, and the `resolve_ssh_prompt` command answers it when the +//! user confirms/rejects (or later types a dynamic verification code). + +use std::collections::HashMap; +use std::mem; +use std::sync::Mutex; +use std::time::Duration; + +use dbx_core::db::ssh_prompt::{self, SshHostKeyNotice, SshPromptAnswer, SshPromptEnvelope, SshPromptRequest}; +use serde::Deserialize; +use tauri::{AppHandle, Emitter, Manager, State}; + +/// Tracks in-flight SSH prompts (host-key verification now; dynamic +/// verification codes later) whose answers are supplied by the frontend. +pub struct SshPromptState { + pending: Mutex>, + frontend: Mutex, +} + +struct PendingSshPrompt { + request: SshPromptRequest, + responder: tokio::sync::oneshot::Sender, +} + +struct FrontendPromptState { + ready: bool, + queued: Vec, +} + +impl SshPromptState { + pub fn new() -> Self { + Self { + pending: Mutex::new(HashMap::new()), + frontend: Mutex::new(FrontendPromptState { ready: false, queued: Vec::new() }), + } + } + + fn register_prompt( + &self, + request: SshPromptRequest, + responder: tokio::sync::oneshot::Sender, + ) -> bool { + let id = request.id.clone(); + self.pending.lock().unwrap().insert(id.clone(), PendingSshPrompt { request, responder }); + + let mut frontend = self.frontend.lock().unwrap(); + if frontend.ready { + true + } else { + if !frontend.queued.iter().any(|queued_id| queued_id == &id) { + frontend.queued.push(id); + } + false + } + } + + fn mark_frontend_ready(&self) -> Vec { + let queued = { + let mut frontend = self.frontend.lock().unwrap(); + frontend.ready = true; + mem::take(&mut frontend.queued) + }; + + let pending = self.pending.lock().unwrap(); + queued.into_iter().filter_map(|id| pending.get(&id).map(|prompt| prompt.request.clone())).collect() + } + + fn mark_frontend_not_ready(&self) { + let pending_ids: Vec = self.pending.lock().unwrap().keys().cloned().collect(); + let mut frontend = self.frontend.lock().unwrap(); + frontend.ready = false; + for id in pending_ids { + if !frontend.queued.iter().any(|queued_id| queued_id == &id) { + frontend.queued.push(id); + } + } + } + + fn remove_pending(&self, id: &str) -> Option { + let pending = self.pending.lock().unwrap().remove(id); + self.remove_queued(id); + pending + } + + fn remove_queued(&self, id: &str) { + self.frontend.lock().unwrap().queued.retain(|queued_id| queued_id != id); + } +} + +/// Install the dbx-core SSH prompt gateway and spawn the forwarding task that +/// bridges backend prompts to the frontend. Must be called *after* +/// `SshPromptState` has been registered with `app.manage(...)`. Call once +/// during app setup. +pub fn install_ssh_prompt_bridge(app: &AppHandle) { + // Fail fast if the state was not registered — the bridge cannot function. + let _ = app.state::(); + + let (tx, mut rx) = tokio::sync::mpsc::channel::(16); + ssh_prompt::install_ssh_prompt_gateway(tx); + + let bridge_app = app.clone(); + tauri::async_runtime::spawn(async move { + while let Some(envelope) = rx.recv().await { + let id = envelope.request.id.clone(); + let Some(state) = bridge_app.try_state::() else { + // State missing -> cannot answer; drop the responder and let the + // backend fail closed on its timeout. + continue; + }; + + // Tauri events do not replay for listeners registered later. Keep + // the request pending until the dialog has installed all listeners. + let emit_now = state.register_prompt(envelope.request, envelope.responder); + if emit_now { + emit_prompt(&bridge_app, state.inner(), &id); + } + } + }); + + // Sweeper: when a backend prompt times out or is otherwise cancelled, its + // oneshot receiver is dropped, leaving a *closed* sender in `pending`. Reap + // those so they never accumulate or block, and notify the UI to close the + // orphaned dialog. Best-effort; failures are ignored. + let sweeper_app = app.clone(); + tauri::async_runtime::spawn(async move { + let mut interval = tokio::time::interval(Duration::from_secs(5)); + loop { + interval.tick().await; + let Some(state) = sweeper_app.try_state::() else { + continue; + }; + let stale: Vec = { + let mut pending = state.pending.lock().unwrap(); + let mut stale = Vec::new(); + pending.retain(|id, prompt| { + if prompt.responder.is_closed() { + stale.push(id.clone()); + false + } else { + true + } + }); + stale + }; + for id in &stale { + state.remove_queued(id); + let _ = sweeper_app.emit("ssh-prompt-dismiss", id); + } + } + }); +} + +/// Install the dbx-core SSH host-key *notice* gateway and spawn the forwarding +/// task that delivers out-of-band host-key events (key changed => possible +/// MITM, or the user rejected the host) to the frontend via the +/// `ssh-host-key-notice` event. The frontend shows these as toasts so the user +/// understands *why* a connection failed. Call once during app setup, after +/// `SshPromptState` is registered. +pub fn install_ssh_notice_bridge(app: &AppHandle) { + let (tx, mut rx) = tokio::sync::mpsc::channel::(16); + ssh_prompt::install_ssh_notice_gateway(tx); + + let app = app.clone(); + tauri::async_runtime::spawn(async move { + while let Some(notice) = rx.recv().await { + let _ = app.emit("ssh-host-key-notice", ¬ice); + } + }); +} + +fn emit_prompt(app: &AppHandle, state: &SshPromptState, id: &str) { + let Some(request) = state.pending.lock().unwrap().get(id).map(|prompt| prompt.request.clone()) else { + return; + }; + + // If the event cannot be delivered, the user can never answer it. Remove + // the responder and close any dialog that may still contain the request. + if app.emit("ssh-prompt", &request).is_err() { + state.remove_pending(id); + let _ = app.emit("ssh-prompt-dismiss", id); + } +} + +/// Marks the SSH prompt dialog ready after it has installed all listeners and +/// replays prompts that arrived during frontend startup or remounting. +#[tauri::command] +pub fn ssh_prompt_ready(app: AppHandle, state: State<'_, SshPromptState>) -> Result<(), String> { + for request in state.mark_frontend_ready() { + emit_prompt(&app, state.inner(), &request.id); + } + Ok(()) +} + +/// Marks the SSH prompt dialog unavailable so future prompts are queued until +/// the dialog is mounted again. Existing prompts are replayed on the next ready +/// handshake instead of being lost during a frontend lifecycle transition. +#[tauri::command] +pub fn ssh_prompt_not_ready(state: State<'_, SshPromptState>) -> Result<(), String> { + state.mark_frontend_not_ready(); + Ok(()) +} + +/// The frontend's answer to a prompt it received via the `ssh-prompt` event. +#[derive(Debug, Deserialize)] +pub struct SshPromptResolution { + /// Id of the prompt being answered (matches the emitted `ssh-prompt` event). + pub id: String, + /// One of: `accept`, `reject`, `secret`. + pub action: String, + /// HostKeyVerify: persist the accepted key for future sessions. + #[serde(default)] + pub remember: Option, + /// SecretInput: the typed verification code. + #[serde(default)] + pub secret: Option, +} + +/// Answers a pending SSH prompt (host-key confirmation or dynamic code) and +/// resumes the suspended backend task. +#[tauri::command] +pub async fn resolve_ssh_prompt( + resolution: SshPromptResolution, + state: State<'_, SshPromptState>, +) -> Result<(), String> { + // Validate the action first so an unknown action does not consume the + // responder — a later, well-formed retry must still be able to answer the + // same prompt. + let answer = match resolution.action.as_str() { + "accept" => SshPromptAnswer::Accept { remember: resolution.remember.unwrap_or(false) }, + "reject" => SshPromptAnswer::Reject, + "secret" => SshPromptAnswer::Secret(resolution.secret.unwrap_or_default()), + other => return Err(format!("Unknown SSH prompt action: {other}")), + }; + + let Some(pending) = state.remove_pending(&resolution.id) else { + return Err(format!("No pending SSH prompt with id {}", resolution.id)); + }; + + if pending.responder.send(answer).is_err() { + // The backend already gave up (timed out or cancelled), so its receiver + // was dropped. Report this so the UI can advance its queue. + return Err(format!("SSH prompt {} was already cancelled", resolution.id)); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use dbx_core::db::ssh_prompt::SshPromptKind; + + fn request(id: &str) -> SshPromptRequest { + SshPromptRequest { + id: id.to_string(), + kind: SshPromptKind::HostKeyVerify, + host: "example.test".to_string(), + port: 22, + key_type: Some("ssh-ed25519".to_string()), + fingerprint: Some("SHA256:test".to_string()), + prompt: None, + } + } + + #[test] + fn queues_prompts_until_frontend_is_ready() { + let state = SshPromptState::new(); + let (responder, _receiver) = tokio::sync::oneshot::channel(); + + assert!(!state.register_prompt(request("first"), responder)); + assert!(state.frontend.lock().unwrap().queued == vec!["first"]); + } + + #[test] + fn ready_replays_only_pending_prompts_once() { + let state = SshPromptState::new(); + let (first_responder, _first_receiver) = tokio::sync::oneshot::channel(); + let (second_responder, _second_receiver) = tokio::sync::oneshot::channel(); + + state.register_prompt(request("first"), first_responder); + state.register_prompt(request("second"), second_responder); + state.remove_pending("first"); + + let replayed = state.mark_frontend_ready(); + assert_eq!(replayed.iter().map(|prompt| prompt.id.as_str()).collect::>(), vec!["second"]); + assert!(state.mark_frontend_ready().is_empty()); + } + + #[test] + fn prompts_arriving_after_ready_are_not_queued() { + let state = SshPromptState::new(); + assert!(state.mark_frontend_ready().is_empty()); + let (responder, _receiver) = tokio::sync::oneshot::channel(); + + assert!(state.register_prompt(request("after-ready"), responder)); + assert!(state.frontend.lock().unwrap().queued.is_empty()); + } + + #[test] + fn not_ready_requeues_existing_prompts_for_remount() { + let state = SshPromptState::new(); + let (responder, _receiver) = tokio::sync::oneshot::channel(); + + state.mark_frontend_ready(); + assert!(state.register_prompt(request("remount"), responder)); + state.mark_frontend_not_ready(); + state.mark_frontend_not_ready(); + + assert_eq!(state.frontend.lock().unwrap().queued, vec!["remount"]); + assert_eq!(state.mark_frontend_ready().len(), 1); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index cb724d4383..494f3480c1 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1245,6 +1245,9 @@ pub fn run() { app.manage(commands::external_db::ExternalDbOpenState::default()); app.manage(commands::deep_link::DeepLinkOpenState::default()); app.manage(commands::update::PendingUpdateState::default()); + app.manage(commands::ssh_prompt::SshPromptState::new()); + commands::ssh_prompt::install_ssh_prompt_bridge(app.handle()); + commands::ssh_prompt::install_ssh_notice_bridge(app.handle()); #[cfg(target_os = "macos")] macos_app_delegate::install_dock_quit_handler(app.handle()); let startup_links = commands::deep_link::connection_deep_links_from_args(std::env::args().skip(1)); @@ -1820,6 +1823,9 @@ pub fn run() { commands::agents::import_agent_jar_cmd, commands::system_fonts::list_system_fonts, commands::ssh_config::list_ssh_config_hosts, + commands::ssh_prompt::ssh_prompt_ready, + commands::ssh_prompt::ssh_prompt_not_ready, + commands::ssh_prompt::resolve_ssh_prompt, commands::tunnel_profiles::load_tunnel_profiles, commands::tunnel_profiles::save_tunnel_profiles, commands::tunnel_profiles::test_tunnel_profile,