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): support JumpServer keyboard-interactive authentication

Rson9947cc16d9236
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index 2b0b6fdc99..684d18acf4 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -309,6 +309,7 @@ function defaultSshTunnel(): SshTunnelConfig {
use_ssh_agent: false,
ssh_agent_sock_path: "",
auth_method: "password",
+ allow_exec_channel_proxy: false,
};
}
@@ -342,6 +343,7 @@ function normalizeSshTunnel(hop: Partial<SshTunnelConfig>): SshTunnelConfig {
use_ssh_agent: !!hop.use_ssh_agent,
ssh_agent_sock_path: hop.ssh_agent_sock_path || "",
auth_method: hop.auth_method || inferSshAuthMethod(hop),
+ allow_exec_channel_proxy: !!hop.allow_exec_channel_proxy,
profile_id: hop.profile_id || undefined,
};
}
@@ -6978,6 +6980,13 @@ function openExternalUrl(url: string) {
<span class="text-xs text-muted-foreground">{{ t("connection.sshExposeLan") }}</span>
</label>
</div>
+ <div class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <label class="col-span-3 flex items-start gap-2 cursor-pointer">
+ <input type="checkbox" v-model="selectedSshLayer.allow_exec_channel_proxy" class="mt-0.5 mr-0" :disabled="selectedSshLayer.enabled === false" />
+ <span class="text-xs text-muted-foreground">{{ t("connection.sshAllowExecChannelProxy") }}</span>
+ </label>
+ </div>
<div class="grid grid-cols-4 items-center gap-4">
<Label :class="connectionLabelSmallClass">{{ t("connection.sshConnectTimeout") }}</Label>
<Input v-model.number="selectedSshLayer.connect_timeout_secs" type="number" min="1" max="300" step="1" class="col-span-3" :disabled="selectedSshLayer.enabled === false" />
diff --git a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
index 42ca4dfc08..bba6d265b0 100644
--- a/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
+++ b/apps/desktop/src/components/sidebar/SidebarTreeRuntimeHost.vue
@@ -528,10 +528,10 @@ async function toggle() {
node.isExpanded = false;
if (!connectionStore.sidebarSearchQuery) connectionStore.releaseCollapsedTreeNodeChildren(node.id);
connectionStore.cancelTreeNodeLoad(node.id);
- emit("node-toggled", node, true);
+ emitNodeToggled(node, true, false);
} else {
node.isExpanded = true;
- emit("node-toggled", node, false);
+ emitNodeToggled(node, false);
}
return;
}
@@ -541,13 +541,13 @@ async function toggle() {
if (node.type === "connection-group") {
node.isExpanded = !node.isExpanded;
connectionStore.toggleConnectionGroupCollapsed(node.id);
- emit("node-toggled", node, wasExpanded);
+ emitNodeToggled(node, wasExpanded);
return;
}
if (node.type === "group-partitions") {
node.isExpanded = !node.isExpanded;
- emit("node-toggled", node, wasExpanded);
+ emitNodeToggled(node, wasExpanded);
return;
}
@@ -558,27 +558,27 @@ async function toggle() {
if (databaseObjectGroup && connectionStore.canUseLoadedTreeNodeToggle(node)) {
node.isExpanded = !node.isExpanded;
if (wasExpanded && !connectionStore.sidebarSearchQuery) connectionStore.releaseCollapsedTreeNodeChildren(node.id);
- emit("node-toggled", node, wasExpanded);
+ emitNodeToggled(node, wasExpanded);
return;
}
if (node.type === "group-extensions" && connectionStore.canUseLoadedTreeNodeToggle(node)) {
node.isExpanded = !node.isExpanded;
if (wasExpanded && !connectionStore.sidebarSearchQuery) connectionStore.releaseCollapsedTreeNodeChildren(node.id);
- emit("node-toggled", node, wasExpanded);
+ emitNodeToggled(node, wasExpanded);
return;
}
if (node.isExpanded) {
node.isExpanded = false;
if (!connectionStore.sidebarSearchQuery) connectionStore.releaseCollapsedTreeNodeChildren(node.id);
- emit("node-toggled", node, wasExpanded);
+ emitNodeToggled(node, wasExpanded, false);
return;
}
try {
if (await loadSidebarObjectGroup(node, connectionStore)) {
- emit("node-toggled", node, wasExpanded);
+ emitNodeToggled(node, wasExpanded);
return;
}
@@ -715,7 +715,7 @@ async function toggle() {
} else if (node.type === "group-extensions" && node.connectionId && hasTreeNodeDatabaseContext(node)) {
await connectionStore.refreshTreeNode(node);
}
- emit("node-toggled", node, wasExpanded);
+ emitNodeToggled(node, wasExpanded);
} catch (e: any) {
if (!wasExpanded) node.isExpanded = false;
const errMsg = e?.message || String(e);
@@ -4673,6 +4673,15 @@ function activateRuntimeNode(node: TreeNode) {
activeNode.value = node;
}
+// Async loaders can rebuild a connection node while awaiting the backend.
+// Publish the live tree node so a stale rendered row cannot reset expansion.
+function emitNodeToggled(node: TreeNode, wasExpanded: boolean, expandedOverride?: boolean) {
+ const liveNode = findSidebarActionTarget(connectionStore.treeNodes, createSidebarActionTarget(node)) ?? node;
+ if (expandedOverride !== undefined) liveNode.isExpanded = expandedOverride;
+ activeNode.value = liveNode;
+ emit("node-toggled", liveNode, wasExpanded);
+}
+
function activateActionTarget(target: SidebarActionTarget) {
activeNode.value = findSidebarActionTarget(connectionStore.treeNodes, target) ?? target;
}
diff --git a/apps/desktop/src/components/sidebar/__tests__/crossDatabaseTablePaste.spec.ts b/apps/desktop/src/components/sidebar/__tests__/crossDatabaseTablePaste.spec.ts
index cd010cc11c..76528d1c28 100644
--- a/apps/desktop/src/components/sidebar/__tests__/crossDatabaseTablePaste.spec.ts
+++ b/apps/desktop/src/components/sidebar/__tests__/crossDatabaseTablePaste.spec.ts
@@ -4,6 +4,14 @@ import { describe, expect, it } from "vitest";
const runtimeSource = readFileSync(new URL("../SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
describe("cross-database table paste", () => {
+ it("publishes the live node after async tree loads", () => {
+ expect(runtimeSource).toContain("function emitNodeToggled(node: TreeNode, wasExpanded: boolean, expandedOverride?: boolean)");
+ expect(runtimeSource).toContain("findSidebarActionTarget(connectionStore.treeNodes, createSidebarActionTarget(node)) ?? node");
+ expect(runtimeSource).toContain("emitNodeToggled(node, wasExpanded, false)");
+ expect(runtimeSource).toMatch(/await connectionStore\.loadMongoDatabases\(node\.connectionId\);[\s\S]*?emitNodeToggled\(node, wasExpanded\)/);
+ expect(runtimeSource).toContain("connectionStore.cancelTreeNodeLoad(node.id)");
+ });
+
it("routes a table clipboard from another context to data transfer", () => {
expect(runtimeSource).toContain("function canTransferTreeClipboardToCurrentNode()");
expect(runtimeSource).toContain("function openTransferFromTreeClipboard()");
diff --git a/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue b/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
index 79970d0539..27d9716f6a 100644
--- a/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
+++ b/apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue
@@ -17,6 +17,7 @@ interface SshPromptRequest {
key_type?: string | null;
fingerprint?: string | null;
prompt?: string | null;
+ echo?: boolean;
}
interface SshHostKeyNotice {
@@ -35,6 +36,7 @@ const { toast } = useToast();
// Using a queue keyed by request id means every prompt is shown and answered.
const queue = ref<SshPromptRequest[]>([]);
const current = computed<SshPromptRequest | null>(() => queue.value[0] ?? null);
+const isSecretPrompt = computed(() => current.value?.kind === "SecretInput");
const visible = ref(false);
const remember = ref(true);
@@ -235,17 +237,19 @@ function submitSecret() {
</script>
<template>
- <Dialog v-model:open="visible" :dismissible="false">
- <DialogContent class="sm:max-w-[460px]">
+ <Dialog v-model:open="visible">
+ <DialogContent class="sm:max-w-[460px]" :show-close-button="false" @interact-outside.prevent @escape-key-down.prevent>
<DialogHeader>
- <DialogTitle>{{ t("connection.sshHostKeyVerifyTitle") }}</DialogTitle>
+ <DialogTitle>
+ {{ t(isSecretPrompt ? "connection.sshInteractiveTitle" : "connection.sshHostKeyVerifyTitle") }}
+ </DialogTitle>
<DialogDescription class="text-muted-foreground">
- {{ t("connection.sshHostKeyVerifyMessage", { host: current?.host ?? "", port: current?.port ?? "" }) }}
+ {{ t(isSecretPrompt ? "connection.sshInteractiveMessage" : "connection.sshHostKeyVerifyMessage", { host: current?.host ?? "", port: current?.port ?? "" }) }}
</DialogDescription>
</DialogHeader>
<div v-if="current" class="space-y-3 py-1">
- <div class="rounded-md border border-border bg-muted/40 p-3 text-sm">
+ <div v-if="current.kind === 'HostKeyVerify'" class="rounded-md border border-border bg-muted/40 p-3 text-sm">
<div class="flex items-center justify-between gap-3">
<span class="text-muted-foreground">{{ t("connection.sshHostKeyVerifyKeyType") }}</span>
<span class="font-medium">{{ current.key_type || "—" }}</span>
@@ -262,18 +266,29 @@ function submitSecret() {
</label>
<div v-else-if="current.kind === 'SecretInput'" class="space-y-2">
- <p class="text-sm text-muted-foreground">{{ current.prompt || "Enter verification code" }}</p>
- <input v-model="secretCode" type="text" autocomplete="off" class="w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-sm outline-none focus:ring-2 focus:ring-ring" :placeholder="'••••••'" />
+ <p class="whitespace-pre-wrap text-sm text-muted-foreground">
+ {{ current.prompt || t("connection.sshInteractiveDefaultPrompt") }}
+ </p>
+ <input
+ v-model="secretCode"
+ :type="current.echo ? 'text' : 'password'"
+ autocomplete="one-time-code"
+ class="w-full rounded-md border border-border bg-background px-3 py-2 font-mono text-sm outline-none focus:ring-2 focus:ring-ring"
+ :placeholder="t('connection.sshInteractivePlaceholder')"
+ @keydown.enter="submitSecret"
+ />
</div>
</div>
<DialogFooter>
- <Button variant="outline" :disabled="resolving" @click="reject">{{ t("connection.sshHostKeyVerifyReject") }}</Button>
+ <Button variant="outline" :disabled="resolving" @click="reject">
+ {{ t(isSecretPrompt ? "connection.sshInteractiveCancel" : "connection.sshHostKeyVerifyReject") }}
+ </Button>
<Button v-if="current?.kind !== 'SecretInput'" :disabled="resolving" @click="accept">
{{ t("connection.sshHostKeyVerifyAccept") }}
</Button>
<Button v-else :disabled="resolving || !secretCode" @click="submitSecret">
- {{ t("connection.sshHostKeyVerifyAccept") }}
+ {{ t("connection.sshInteractiveSubmit") }}
</Button>
</DialogFooter>
</DialogContent>
diff --git a/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts b/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
index bca1a8cea0..66ce055127 100644
--- a/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
+++ b/apps/desktop/src/components/ssh/__tests__/SshHostKeyPromptDialog.spec.ts
@@ -1,5 +1,7 @@
// @vitest-environment happy-dom
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
import { createApp, defineComponent, h, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
@@ -49,6 +51,8 @@ vi.mock("@/components/ui/button", async () => {
import SshHostKeyPromptDialog from "@/components/ssh/SshHostKeyPromptDialog.vue";
+const dialogSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/ssh/SshHostKeyPromptDialog.vue"), "utf8");
+
class MockEventSource {
static instances: MockEventSource[] = [];
@@ -113,6 +117,13 @@ async function mountDialog() {
}
describe("SshHostKeyPromptDialog web bridge", () => {
+ it("requires an explicit answer for blocking SSH prompts", () => {
+ expect(dialogSource).toContain(':show-close-button="false"');
+ expect(dialogSource).toContain("@interact-outside.prevent");
+ expect(dialogSource).toContain("@escape-key-down.prevent");
+ expect(dialogSource).not.toContain(':dismissible="false"');
+ });
+
it("shows an SSE host-key prompt and posts the user's acceptance", async () => {
await mountDialog();
@@ -217,4 +228,44 @@ describe("SshHostKeyPromptDialog web bridge", () => {
eventSource?.error();
expect(setSpy).toHaveBeenCalledTimes(2);
});
+
+ it("submits a keyboard-interactive TOTP challenge as a secret response", async () => {
+ await mountDialog();
+
+ const eventSource = MockEventSource.instances[0];
+ eventSource?.emit({
+ type: "prompt",
+ request: {
+ id: "totp-1",
+ kind: "SecretInput",
+ host: "jump.example.test",
+ port: 2222,
+ prompt: "JumpServer\n\nOTP Code:",
+ echo: false,
+ },
+ });
+ await nextTick();
+
+ expect(document.body.textContent).toContain("SSH Verification Required");
+ expect(document.body.textContent).toContain("OTP Code:");
+
+ const input = document.body.querySelector<HTMLInputElement>("input");
+ expect(input?.type).toBe("password");
+ if (!input) throw new Error("TOTP input was not rendered");
+ input.value = "123456";
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ await nextTick();
+
+ const buttons = document.body.querySelectorAll<HTMLButtonElement>("button");
+ buttons.item(buttons.length - 1).click();
+
+ await vi.waitFor(() => {
+ expect(resolveSshPromptMock).toHaveBeenCalledWith({
+ id: "totp-1",
+ action: "secret",
+ remember: undefined,
+ secret: "123456",
+ });
+ });
+ });
});
diff --git a/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts b/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts
index 6d5911a9c2..65bed0e664 100644
--- a/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts
+++ b/apps/desktop/src/i18n/__tests__/backendErrors.spec.ts
@@ -54,6 +54,11 @@ const WINDOWS_JRE_REMOVE_ERROR = [
// Every backend message changed away from hardcoded Chinese, paired with the
// key and params it must resolve to.
const CASES: { name: string; message: string; key: string; params?: Record<string, string> }[] = [
+ {
+ name: "SSH TOTP prompt cancelled",
+ message: "SSH layer 1 failed: SSH keyboard-interactive authentication was cancelled",
+ key: "connection.sshTotpCancelled",
+ },
{
name: "streaming export unsupported",
message: "Streaming export is unsupported for this query. Simplify it or use a supported driver.",
diff --git a/apps/desktop/src/i18n/backend-errors.ts b/apps/desktop/src/i18n/backend-errors.ts
index dfe5753e27..94b963faee 100644
--- a/apps/desktop/src/i18n/backend-errors.ts
+++ b/apps/desktop/src/i18n/backend-errors.ts
@@ -66,6 +66,9 @@ const patterns: [RegExp, string][] = [
[/^SOCKS proxy connect rejected \(code (\d+)\)$/, "settings.tunnelsSocksConnectRejected"],
[/^Unsupported SOCKS bound address type: (\d+)$/, "settings.tunnelsSocksUnsupportedAddrType"],
+ // SSH keyboard-interactive prompts (for example JumpServer TOTP).
+ [/^(?:SSH layer \d+ failed:\s*)?SSH keyboard-interactive authentication was cancelled$/, "connection.sshTotpCancelled"],
+
// Query result export limits (crates/dbx-core/src/query_result_export.rs)
[/^Streaming export is unsupported for this query\. Simplify it or use a supported driver\.$/, "exportProgress.streamingUnsupported"],
[/^Streaming export needs a result-set session, but this driver returned no session_id\.$/, "exportProgress.agentSessionMissing"],
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index b8ab0ff4c8..1d0bece0d4 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -625,6 +625,7 @@ export default {
sshKeyPassphrasePlaceholder: "Leave empty if key is not encrypted",
sshKeyPathBrowse: "Browse",
sshExposeLan: "Expose tunnel to LAN",
+ sshAllowExecChannelProxy: "Enable SSH exec-channel fallback (nc)",
sshConnectTimeout: "SSH Timeout (seconds)",
sshHops: "Tunnel / Proxy Layers",
sshHopAdd: "Add SSH layer",
@@ -649,6 +650,12 @@ export default {
sshHostKeyVerifyRemember: "Trust this host (remember this key for future connections)",
sshHostKeyVerifyAccept: "Accept & Connect",
sshHostKeyVerifyReject: "Cancel",
+ sshInteractiveTitle: "SSH Verification Required",
+ sshInteractiveMessage: "The SSH server at {host}:{port} requires additional verification.",
+ sshInteractiveDefaultPrompt: "Enter the requested verification response.",
+ sshInteractivePlaceholder: "Enter verification code",
+ sshInteractiveSubmit: "Verify",
+ sshInteractiveCancel: "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.",
@@ -727,6 +734,7 @@ export default {
colorCustom: "Custom color",
cancelConnecting: "Cancel connecting",
connectCancelled: "Connection cancelled",
+ sshTotpCancelled: "One-time code entry cancelled",
},
editor: {
duckdbDraining: "The previous DuckDB query is still stopping. Please try again shortly.",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index cd653384d3..8370ff2595 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -498,6 +498,7 @@ export default withEnglishFallback({
sshKeyPassphrasePlaceholder: "Dejar vacío si la clave no está cifrada",
sshKeyPathBrowse: "Examinar",
sshExposeLan: "Exponer túnel a la red local",
+ sshAllowExecChannelProxy: "Activar fallback del canal exec SSH (nc)",
sshConnectTimeout: "Tiempo de espera SSH (segundos)",
sshHops: "Capas de túnel SSH / proxy",
sshHopAdd: "Agregar capa SSH",
@@ -576,6 +577,7 @@ export default withEnglishFallback({
colorCustom: "Color personalizado",
cancelConnecting: "Cancelar conexión",
connectCancelled: "Conexión cancelada",
+ sshTotpCancelled: "Se canceló la introducción del código de un solo uso",
kafkaKerberosPrincipal: "Principal",
kafkaKerberosKeytab: "Keytab",
kafkaKerberosServiceName: "Nombre del servicio",
@@ -697,6 +699,12 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "Confiar en este host (recordar esta clave para futuras conexiones)",
sshHostKeyVerifyAccept: "Aceptar y conectar",
sshHostKeyVerifyReject: "Cancelar",
+ sshInteractiveTitle: "Se requiere verificación SSH",
+ sshInteractiveMessage: "El servidor SSH {host}:{port} requiere verificación adicional.",
+ sshInteractiveDefaultPrompt: "Introduzca la respuesta de verificación solicitada.",
+ sshInteractivePlaceholder: "Introducir código de verificación",
+ sshInteractiveSubmit: "Verificar",
+ sshInteractiveCancel: "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}.",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index 4c2391ebc9..9176c2af6f 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -496,6 +496,7 @@ export default withEnglishFallback({
sshKeyPassphrasePlaceholder: "Lascia vuoto se la chiave non è crittografata",
sshKeyPathBrowse: "Sfoglia",
sshExposeLan: "Esponi tunnel alla LAN",
+ sshAllowExecChannelProxy: "Abilita il fallback del canale exec SSH (nc)",
sshConnectTimeout: "Timeout SSH (secondi)",
sshHops: "Livelli tunnel SSH / proxy",
sshHopAdd: "Aggiungi livello SSH",
@@ -574,6 +575,7 @@ export default withEnglishFallback({
colorCustom: "Colore personalizzato",
cancelConnecting: "Annulla connessione",
connectCancelled: "Connessione annullata",
+ sshTotpCancelled: "Inserimento del codice monouso annullato",
kafkaKerberosPrincipal: "Principal",
kafkaKerberosKeytab: "Keytab",
kafkaKerberosServiceName: "Nome del servizio",
@@ -695,6 +697,12 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "Fidati di questo host (ricorda la chiave per connessioni future)",
sshHostKeyVerifyAccept: "Accetta e connetti",
sshHostKeyVerifyReject: "Annulla",
+ sshInteractiveTitle: "Verifica SSH richiesta",
+ sshInteractiveMessage: "Il server SSH {host}:{port} richiede una verifica aggiuntiva.",
+ sshInteractiveDefaultPrompt: "Inserisci la risposta di verifica richiesta.",
+ sshInteractivePlaceholder: "Inserisci il codice di verifica",
+ sshInteractiveSubmit: "Verifica",
+ sshInteractiveCancel: "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.",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 05b67ca0e9..ac1430e2bd 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -490,6 +490,7 @@ export default withEnglishFallback({
sshKeyPassphrasePlaceholder: "鍵が暗号化されていない場合は空のまま",
sshKeyPathBrowse: "参照",
sshExposeLan: "トンネルをLANに公開",
+ sshAllowExecChannelProxy: "SSH 実行チャネルのフォールバックを有効化(nc)",
sshConnectTimeout: "SSHタイムアウト(秒)",
sshHops: "SSHトンネル / プロキシ階層",
sshHopAdd: "SSH階層を追加",
@@ -574,6 +575,7 @@ export default withEnglishFallback({
zookeeperCreateModeEphemeralSequential: "エフェメラル順序",
cancelConnecting: "接続をキャンセル",
connectCancelled: "接続がキャンセルされました",
+ sshTotpCancelled: "ワンタイムコードの入力をキャンセルしました",
kafkaKerberosPrincipal: "プリンシパル",
kafkaKerberosKeytab: "Keytab",
kafkaKerberosServiceName: "サービス名",
@@ -695,6 +697,12 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "このホストを信頼する(今後の接続のためにキーを記憶する)",
sshHostKeyVerifyAccept: "承諾して接続",
sshHostKeyVerifyReject: "キャンセル",
+ sshInteractiveTitle: "SSH検証が必要です",
+ sshInteractiveMessage: "SSHサーバー {host}:{port} で追加の検証が必要です。",
+ sshInteractiveDefaultPrompt: "サーバーから要求された検証情報を入力してください。",
+ sshInteractivePlaceholder: "検証コードを入力",
+ sshInteractiveSubmit: "検証",
+ sshInteractiveCancel: "キャンセル",
sshHostKeyNoticeChanged: "ホスト {host}:{port} のキーが変更されました。中間者攻撃の可能性があります。予期された変更である場合は、古いレコードを削除して再接続してください。",
sshHostKeyNoticeRejected: "ホスト {host}:{port} のホストキー検証を拒否しました。接続は中止され、資格情報は送信されませんでした。",
sshHostKeyNoticeGeneric: "SSHホスト {host}:{port} のキー検証に失敗しました。",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 7dbabb6277..396cad9a90 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -612,6 +612,7 @@ export default withEnglishFallback({
sshKeyPassphrasePlaceholder: "키가 암호화되지 않은 경우 비워 두세요",
sshKeyPathBrowse: "찾아보기",
sshExposeLan: "터널을 LAN에 노출",
+ sshAllowExecChannelProxy: "SSH exec 채널 대체(nc) 활성화",
sshConnectTimeout: "SSH 제한 시간 (초)",
sshHops: "터널 / 프록시 계층",
sshHopAdd: "SSH 계층 추가",
@@ -636,6 +637,12 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "이 호스트 신뢰 (향후 연결을 위해 이 키 기억)",
sshHostKeyVerifyAccept: "수락 후 연결",
sshHostKeyVerifyReject: "취소",
+ sshInteractiveTitle: "SSH 인증 필요",
+ sshInteractiveMessage: "SSH 서버 {host}:{port}에서 추가 인증을 요구합니다.",
+ sshInteractiveDefaultPrompt: "서버에서 요청한 인증 정보를 입력하세요.",
+ sshInteractivePlaceholder: "인증 코드 입력",
+ sshInteractiveSubmit: "인증",
+ sshInteractiveCancel: "취소",
sshHostKeyNoticeChanged: "{host}:{port}의 호스트 키가 변경되었습니다 — 이는 중간자 공격을 나타낼 수 있습니다. 이 변경을 예상한 경우에만 이전 항목을 제거하고 다시 연결하세요.",
sshHostKeyNoticeRejected: "{host}:{port}의 호스트 키를 거부했습니다. 연결이 중단되고 자격 증명이 전송되지 않았습니다.",
sshHostKeyNoticeLearnFailed: "{host}:{port}의 호스트 키를 저장할 수 없습니다 — 이 호스트는 이 세션에만 신뢰되며 다음에 다시 확인을 요청받습니다.",
@@ -714,6 +721,7 @@ export default withEnglishFallback({
colorCustom: "사용자 지정 색상",
cancelConnecting: "연결 취소",
connectCancelled: "연결이 취소되었습니다",
+ sshTotpCancelled: "일회용 코드 입력이 취소되었습니다",
},
editor: {
duckdbDraining: "이전 DuckDB 쿼리가 아직 중지 중입니다. 잠시 후 다시 시도해 주세요.",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 1ba5887ec4..1fc7495298 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -497,6 +497,7 @@ export default withEnglishFallback({
sshKeyPassphrasePlaceholder: "Deixe vazio se a chave não estiver criptografada",
sshKeyPathBrowse: "Procurar",
sshExposeLan: "Expor túnel à LAN",
+ sshAllowExecChannelProxy: "Ativar fallback do canal exec SSH (nc)",
sshConnectTimeout: "Timeout SSH (segundos)",
sshHops: "Camadas de túnel SSH / proxy",
sshHopAdd: "Adicionar camada SSH",
@@ -575,6 +576,7 @@ export default withEnglishFallback({
colorCustom: "Cor personalizada",
cancelConnecting: "Cancelar conexão",
connectCancelled: "Conexão cancelada",
+ sshTotpCancelled: "Entrada do código de uso único cancelada",
kafkaKerberosPrincipal: "Principal",
kafkaKerberosKeytab: "Keytab",
kafkaKerberosServiceName: "Nome do serviço",
@@ -696,6 +698,12 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "Confiar neste host (lembrar desta chave para conexões futuras)",
sshHostKeyVerifyAccept: "Aceitar e conectar",
sshHostKeyVerifyReject: "Cancelar",
+ sshInteractiveTitle: "Verificação SSH necessária",
+ sshInteractiveMessage: "O servidor SSH {host}:{port} exige verificação adicional.",
+ sshInteractiveDefaultPrompt: "Digite a resposta de verificação solicitada.",
+ sshInteractivePlaceholder: "Digite o código de verificação",
+ sshInteractiveSubmit: "Verificar",
+ sshInteractiveCancel: "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}.",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 56c854ecf3..f823137d74 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -564,6 +564,7 @@ export default withEnglishFallback({
connecting: "正在连接 {name}...",
cancelConnecting: "取消连接",
connectCancelled: "连接已取消",
+ sshTotpCancelled: "已取消输入一次性验证码",
connectSuccess: "已连接 {name}",
connectFailed: "连接失败:{message}",
driverNotInstalled: "{driver} 驱动未安装,请在驱动管理器中安装。",
@@ -628,6 +629,7 @@ export default withEnglishFallback({
sshKeyPassphrasePlaceholder: "密钥未加密则留空",
sshKeyPathBrowse: "浏览",
sshExposeLan: "允许局域网访问隧道",
+ sshAllowExecChannelProxy: "启用 SSH 执行通道回退(nc)",
sshConnectTimeout: "SSH 超时时间(秒)",
sshHops: "隧道/代理层级",
sshHopAdd: "添加 SSH 层",
@@ -652,6 +654,12 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "信任此主机(记住该密钥用于以后的连接)",
sshHostKeyVerifyAccept: "接受并连接",
sshHostKeyVerifyReject: "取消",
+ sshInteractiveTitle: "需要 SSH 验证",
+ sshInteractiveMessage: "SSH 服务器 {host}:{port} 要求完成额外验证。",
+ sshInteractiveDefaultPrompt: "请输入服务器要求的验证信息。",
+ sshInteractivePlaceholder: "输入验证码",
+ sshInteractiveSubmit: "验证",
+ sshInteractiveCancel: "取消",
sshHostKeyNoticeChanged: "主机 {host}:{port} 的密钥已变更,可能存在中间人攻击。如确属预期,请删除旧记录后重新连接。",
sshHostKeyNoticeRejected: "你已拒绝 {host}:{port} 的主机密钥验证,连接已中止,凭据未发送。",
sshHostKeyNoticeLearnFailed: "无法保存 {host}:{port} 的主机密钥 — 该主机仅在本次会话内受信任,下次连接仍需重新确认。",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index 01ce6742c2..2fac4787f9 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -496,6 +496,7 @@ export default withEnglishFallback({
sshKeyPassphrasePlaceholder: "金鑰未加密則留空",
sshKeyPathBrowse: "瀏覽",
sshExposeLan: "允許區域網路存取隧道",
+ sshAllowExecChannelProxy: "啟用 SSH 執行通道回退(nc)",
sshConnectTimeout: "SSH 逾時時間(秒)",
sshHops: "SSH 隧道/代理層級",
sshHopAdd: "新增 SSH 層",
@@ -574,6 +575,7 @@ export default withEnglishFallback({
colorCustom: "自訂顏色",
cancelConnecting: "取消連接",
connectCancelled: "連接已取消",
+ sshTotpCancelled: "已取消輸入一次性驗證碼",
kafkaKerberosPrincipal: "Principal",
kafkaKerberosKeytab: "Keytab",
kafkaKerberosServiceName: "服務名稱",
@@ -695,6 +697,12 @@ export default withEnglishFallback({
sshHostKeyVerifyRemember: "信任此主機(記住此金鑰用於之後的連線)",
sshHostKeyVerifyAccept: "接受並連線",
sshHostKeyVerifyReject: "取消",
+ sshInteractiveTitle: "需要 SSH 驗證",
+ sshInteractiveMessage: "SSH 伺服器 {host}:{port} 要求完成額外驗證。",
+ sshInteractiveDefaultPrompt: "請輸入伺服器要求的驗證資訊。",
+ sshInteractivePlaceholder: "輸入驗證碼",
+ sshInteractiveSubmit: "驗證",
+ sshInteractiveCancel: "取消",
sshHostKeyNoticeChanged: "主機 {host}:{port} 的金鑰已變更,可能存在中間人攻擊。如確屬預期,請刪除舊記錄後重新連線。",
sshHostKeyNoticeRejected: "您已拒絕 {host}:{port} 的主機金鑰驗證,連線已中止,憑證未發送。",
sshHostKeyNoticeGeneric: "SSH 主機 {host}:{port} 的金鑰驗證失敗。",
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index a03dfb7a14..98bc1b639a 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -239,6 +239,8 @@ export interface SshTunnelConfig {
* for connections that already have `use_ssh_agent` configured.
*/
auth_method?: "password" | "key" | "key+password" | "agent" | "none";
+ /** Allow `nc` through an SSH exec channel when direct-tcpip is prohibited. */
+ allow_exec_channel_proxy?: boolean;
/**
* 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/cloud_sync.rs b/crates/dbx-core/src/cloud_sync.rs
index bd76655db3..acdfad3d21 100644
--- a/crates/dbx-core/src/cloud_sync.rs
+++ b/crates/dbx-core/src/cloud_sync.rs
@@ -1658,6 +1658,7 @@ mod tests {
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
+ allow_exec_channel_proxy: false,
}),
TransportLayerConfig::HttpTunnel(crate::models::connection::HttpTunnelConfig {
profile_id: String::new(),
@@ -2168,6 +2169,7 @@ mod tests {
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
+ allow_exec_channel_proxy: false,
profile_id: String::new(),
});
storage.save_tunnel_profiles(std::slice::from_ref(&profile)).await.unwrap();
diff --git a/crates/dbx-core/src/connection.rs b/crates/dbx-core/src/connection.rs
index ea8725ca63..c10f61230b 100644
--- a/crates/dbx-core/src/connection.rs
+++ b/crates/dbx-core/src/connection.rs
@@ -2312,6 +2312,7 @@ impl AppState {
"127.0.0.1",
1,
false,
+ ssh.allow_exec_channel_proxy,
)
.await;
self.tunnels.stop_tunnel(&probe_id).await;
@@ -5546,6 +5547,7 @@ mod tests {
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
+ allow_exec_channel_proxy: false,
profile_id: String::new(),
});
assert!(state.test_tunnel_profile(&ssh).await.is_err());
@@ -7220,6 +7222,7 @@ for line in sys.stdin:
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: String::new(),
+ allow_exec_channel_proxy: false,
profile_id: profile_id.to_string(),
}
}
diff --git a/crates/dbx-core/src/connection_secrets.rs b/crates/dbx-core/src/connection_secrets.rs
index ea6f276a12..89e993ce80 100644
--- a/crates/dbx-core/src/connection_secrets.rs
+++ b/crates/dbx-core/src/connection_secrets.rs
@@ -807,6 +807,7 @@ mod tests {
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: "key".to_string(),
+ allow_exec_channel_proxy: false,
}
}
diff --git a/crates/dbx-core/src/db/mongo_driver.rs b/crates/dbx-core/src/db/mongo_driver.rs
index 780668a46c..2aa7299440 100644
--- a/crates/dbx-core/src/db/mongo_driver.rs
+++ b/crates/dbx-core/src/db/mongo_driver.rs
@@ -1,6 +1,9 @@
use mongodb::{
bson::{doc, oid::ObjectId, Bson, DateTime, Document},
- options::{ClientOptions, Collation, GridFsBucketOptions, IndexOptions, UpdateModifications},
+ options::{
+ ClientOptions, Collation, GridFsBucketOptions, IndexOptions, ReadPreference, SelectionCriteria,
+ UpdateModifications,
+ },
Client, Cursor, Database, IndexModel,
};
use serde::{Deserialize, Serialize};
@@ -214,7 +217,38 @@ fn collection_stats_field(result: &Document, key: &str) -> serde_json::Value {
}
pub async fn list_databases(client: &Client) -> Result<Vec<String>, String> {
- client.list_database_names().await.map_err(|e| e.to_string())
+ match client.list_database_names().await {
+ Ok(databases) => Ok(databases),
+ Err(error) if list_databases_requires_secondary_fallback(&error.to_string()) => {
+ let result = client
+ .database("admin")
+ .run_command(doc! { "listDatabases": 1, "nameOnly": true })
+ .selection_criteria(list_databases_secondary_selection())
+ .await
+ .map_err(|fallback| fallback.to_string())?;
+ let databases = result
+ .get_array("databases")
+ .map_err(|error| format!("MongoDB listDatabases response is invalid: {error}"))?
+ .iter()
+ .filter_map(|database| database.as_document()?.get_str("name").ok().map(str::to_string))
+ .collect();
+ Ok(databases)
+ }
+ Err(error) => Err(error.to_string()),
+ }
+}
+
+fn list_databases_secondary_selection() -> SelectionCriteria {
+ SelectionCriteria::ReadPreference(ReadPreference::SecondaryPreferred { options: None })
+}
+
+fn list_databases_requires_secondary_fallback(error: &str) -> bool {
+ let error = error.to_ascii_lowercase();
+ error.contains("not master")
+ || error.contains("not primary")
+ || error.contains("notmaster")
+ || error.contains("notwritableprimary")
+ || error.contains("slaveok=false")
}
/// MongoDB collection kind from `listCollections` (not GridFS buckets).
@@ -2179,6 +2213,21 @@ mod tests {
assert_eq!(resolve_mongo_find_total(Ok(250), false, 100, 25), (250, false));
}
+ #[test]
+ fn detects_mongo_secondary_only_list_databases_errors() {
+ assert!(list_databases_requires_secondary_fallback("NotWritablePrimary: not master"));
+ assert!(list_databases_requires_secondary_fallback("not master and slaveOk=false"));
+ assert!(!list_databases_requires_secondary_fallback("Unauthorized: listDatabases"));
+ }
+
+ #[test]
+ fn list_databases_fallback_selects_secondary_preferred() {
+ assert!(matches!(
+ list_databases_secondary_selection(),
+ SelectionCriteria::ReadPreference(ReadPreference::SecondaryPreferred { .. })
+ ));
+ }
+
#[test]
fn parse_aggregate_options_document_keeps_official_fields() {
let doc = parse_aggregate_options_document(Some(
diff --git a/crates/dbx-core/src/db/ssh_prompt.rs b/crates/dbx-core/src/db/ssh_prompt.rs
index a17f17dfbb..12c24e4699 100644
--- a/crates/dbx-core/src/db/ssh_prompt.rs
+++ b/crates/dbx-core/src/db/ssh_prompt.rs
@@ -2,7 +2,7 @@
//! 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
+//! and 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
@@ -25,7 +25,6 @@ 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,
}
@@ -46,6 +45,10 @@ pub struct SshPromptRequest {
/// SecretInput: the challenge text to show the user.
#[serde(default)]
pub prompt: Option<String>,
+ /// SecretInput: whether the server allows the response to be echoed.
+ /// Passwords and verification codes normally set this to false.
+ #[serde(default)]
+ pub echo: bool,
}
/// The user's answer, sent from the UI back to the backend.
@@ -105,6 +108,21 @@ pub fn host_key_verify_request(
key_type,
fingerprint,
prompt: None,
+ echo: false,
+ }
+}
+
+/// Build a [`SshPromptRequest`] for a keyboard-interactive challenge.
+pub fn secret_input_request(host: &str, port: u16, prompt: String, echo: bool) -> SshPromptRequest {
+ SshPromptRequest {
+ id: Uuid::new_v4().to_string(),
+ kind: SshPromptKind::SecretInput,
+ host: host.to_string(),
+ port,
+ key_type: None,
+ 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 48810fcfc2..f409f67776 100644
--- a/crates/dbx-core/src/db/ssh_tunnel.rs
+++ b/crates/dbx-core/src/db/ssh_tunnel.rs
@@ -8,14 +8,13 @@ use std::sync::Arc;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine;
-use russh::client::{self, AuthResult, Config, Handle};
+use russh::client::{self, AuthResult, Config, Handle, KeyboardInteractiveAuthResponse};
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 russh::{kex, mac, ChannelOpenFailure, Preferred};
use tokio::net::TcpListener;
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
@@ -41,6 +40,9 @@ const IDLE_SESSION_PING_TIMEOUT: Duration = Duration::from_secs(10);
/// (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);
+/// Maximum time to wait for the user to answer one keyboard-interactive
+/// challenge (for example a TOTP code).
+const KEYBOARD_INTERACTIVE_PROMPT_TIMEOUT: Duration = Duration::from_secs(300);
/// SSH client handler. Holds a host-key verifier so that
/// [`client::Handler::check_server_key`] can reject untrusted/changed server
@@ -183,6 +185,95 @@ fn server_offers_password(remaining_methods: &MethodSet) -> bool {
remaining_methods.contains(&MethodKind::Password)
}
+fn server_offers_keyboard_interactive(remaining_methods: &MethodSet) -> bool {
+ remaining_methods.contains(&MethodKind::KeyboardInteractive)
+}
+
+fn auth_result_offers_keyboard_interactive(result: &AuthResult) -> bool {
+ matches!(
+ result,
+ AuthResult::Failure { remaining_methods, .. }
+ if server_offers_keyboard_interactive(remaining_methods)
+ )
+}
+
+fn keyboard_interactive_prompt_text(name: &str, instructions: &str, prompt: &str) -> String {
+ [name.trim(), instructions.trim(), prompt.trim()]
+ .into_iter()
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join("\n\n")
+}
+
+async fn request_keyboard_interactive_answer(
+ host: &str,
+ port: u16,
+ name: &str,
+ instructions: &str,
+ prompt: &russh::client::Prompt,
+) -> Result<String, String> {
+ let prompt_text = keyboard_interactive_prompt_text(name, instructions, &prompt.prompt);
+ let request = ssh_prompt::secret_input_request(host, port, prompt_text, prompt.echo);
+ let Some(responder_rx) = ssh_prompt::request_ssh_prompt(request) else {
+ return Err(
+ "SSH keyboard-interactive authentication requires user input, but no prompt UI is available".to_string()
+ );
+ };
+
+ match tokio::time::timeout(KEYBOARD_INTERACTIVE_PROMPT_TIMEOUT, responder_rx).await {
+ Ok(Ok(ssh_prompt::SshPromptAnswer::Secret(secret))) => Ok(secret),
+ Ok(Ok(ssh_prompt::SshPromptAnswer::Reject)) => {
+ Err("SSH keyboard-interactive authentication was cancelled".to_string())
+ }
+ Ok(Ok(ssh_prompt::SshPromptAnswer::Accept { .. })) => {
+ Err("SSH keyboard-interactive authentication received an invalid response".to_string())
+ }
+ Ok(Err(_)) => Err("SSH keyboard-interactive authentication prompt was dismissed".to_string()),
+ Err(_) => Err("SSH keyboard-interactive authentication prompt timed out".to_string()),
+ }
+}
+
+async fn authenticate_keyboard_interactive(
+ session: &mut Handle<SshClient>,
+ ssh_user: &str,
+ host: &str,
+ port: u16,
+ connect_timeout: Duration,
+ connect_timeout_secs: u64,
+) -> Result<(), String> {
+ let mut response = tokio::time::timeout(
+ connect_timeout,
+ session.authenticate_keyboard_interactive_start(ssh_user, None::<String>),
+ )
+ .await
+ .map_err(|_| format!("SSH keyboard-interactive auth timed out ({connect_timeout_secs}s)"))?
+ .map_err(|e| format!("SSH keyboard-interactive auth failed: {e}"))?;
+
+ loop {
+ match response {
+ KeyboardInteractiveAuthResponse::Success => return Ok(()),
+ KeyboardInteractiveAuthResponse::Failure { remaining_methods, partial_success } => {
+ return Err(format!(
+ "SSH keyboard-interactive authentication failed \
+ (remaining_methods={remaining_methods:?}, partial_success={partial_success})"
+ ));
+ }
+ KeyboardInteractiveAuthResponse::InfoRequest { name, instructions, prompts } => {
+ let mut answers = Vec::with_capacity(prompts.len());
+ for prompt in &prompts {
+ answers.push(request_keyboard_interactive_answer(host, port, &name, &instructions, prompt).await?);
+ }
+
+ response =
+ tokio::time::timeout(connect_timeout, session.authenticate_keyboard_interactive_respond(answers))
+ .await
+ .map_err(|_| format!("SSH keyboard-interactive auth timed out ({connect_timeout_secs}s)"))?
+ .map_err(|e| format!("SSH keyboard-interactive auth failed: {e}"))?;
+ }
+ }
+ }
+}
+
#[allow(clippy::too_many_arguments)]
async fn connect_and_authenticate(
connect_host: &str,
@@ -277,6 +368,18 @@ async fn connect_and_authenticate(
match auth_res {
AuthResult::Success => return Ok(session),
AuthResult::Failure { remaining_methods, partial_success } => {
+ if server_offers_keyboard_interactive(&remaining_methods) {
+ authenticate_keyboard_interactive(
+ &mut session,
+ ssh_user,
+ host_key_host,
+ host_key_port,
+ connect_timeout,
+ connect_timeout_secs,
+ )
+ .await?;
+ return Ok(session);
+ }
// 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
@@ -301,7 +404,19 @@ async fn connect_and_authenticate(
.map_err(|e| format!("SSH password auth failed: {e}"))?;
match auth_res {
AuthResult::Success => return Ok(session),
- AuthResult::Failure { partial_success, .. } => {
+ AuthResult::Failure { remaining_methods, partial_success } => {
+ if server_offers_keyboard_interactive(&remaining_methods) {
+ authenticate_keyboard_interactive(
+ &mut session,
+ ssh_user,
+ host_key_host,
+ host_key_port,
+ connect_timeout,
+ connect_timeout_secs,
+ )
+ .await?;
+ return Ok(session);
+ }
return Err(format!("SSH password authentication failed (partial_success={partial_success})"));
}
}
@@ -336,7 +451,17 @@ async fn connect_and_authenticate(
.await
.map_err(|_| format!("SSH key auth timed out ({connect_timeout_secs}s)"))?
.map_err(|e| format!("SSH key auth failed: {e}"))?;
- if !auth_res.success() {
+ if auth_result_offers_keyboard_interactive(&auth_res) {
+ authenticate_keyboard_interactive(
+ &mut session,
+ ssh_user,
+ host_key_host,
+ host_key_port,
+ connect_timeout,
+ connect_timeout_secs,
+ )
+ .await?;
+ } else if !auth_res.success() {
return Err("SSH public key authentication failed".to_string());
}
} else if try_password {
@@ -344,14 +469,45 @@ async fn connect_and_authenticate(
.await
.map_err(|_| format!("SSH password auth timed out ({connect_timeout_secs}s)"))?
.map_err(|e| format!("SSH password auth failed: {e}"))?;
- if !auth_res.success() {
+ if auth_result_offers_keyboard_interactive(&auth_res) {
+ authenticate_keyboard_interactive(
+ &mut session,
+ ssh_user,
+ host_key_host,
+ host_key_port,
+ connect_timeout,
+ connect_timeout_secs,
+ )
+ .await?;
+ } else if !auth_res.success() {
return Err("SSH password authentication failed".to_string());
}
} else if try_agent {
match try_authenticate_with_agent(&mut session, ssh_user, ssh_agent_sock_path, &connect_timeout).await {
- Ok(()) => {}
+ Ok(AgentAuthenticationOutcome::Success) => {}
+ Ok(AgentAuthenticationOutcome::KeyboardInteractiveRequired) => {
+ authenticate_keyboard_interactive(
+ &mut session,
+ ssh_user,
+ host_key_host,
+ host_key_port,
+ connect_timeout,
+ connect_timeout_secs,
+ )
+ .await?;
+ }
Err(agent_err) => return Err(agent_err),
}
+ } else if auth_result_offers_keyboard_interactive(&none_res) {
+ authenticate_keyboard_interactive(
+ &mut session,
+ ssh_user,
+ host_key_host,
+ host_key_port,
+ connect_timeout,
+ connect_timeout_secs,
+ )
+ .await?;
} else {
return Err(
"SSH authentication failed: \"none\" was rejected and no password, key, or ssh-agent is configured"
@@ -362,14 +518,20 @@ async fn connect_and_authenticate(
Ok(session)
}
-/// Try to authenticate using ssh-agent identities. Returns `Ok(())` on success,
-/// or an error describing why agent auth failed (unavailable, no identities, all rejected).
+enum AgentAuthenticationOutcome {
+ Success,
+ KeyboardInteractiveRequired,
+}
+
+/// Try to authenticate using ssh-agent identities. A key may be only the first
+/// successful factor, so preserve a server request to continue with
+/// keyboard-interactive instead of discarding it and trying the next identity.
async fn try_authenticate_with_agent(
session: &mut Handle<SshClient>,
ssh_user: &str,
#[cfg_attr(not(unix), allow(unused_variables))] ssh_agent_sock_path: &str,
connect_timeout: &Duration,
-) -> Result<(), String> {
+) -> Result<AgentAuthenticationOutcome, String> {
#[cfg(unix)]
let mut agent = if ssh_agent_sock_path.is_empty() {
match AgentClient::connect_env().await {
@@ -422,7 +584,10 @@ async fn try_authenticate_with_agent(
};
match result {
- Ok(auth_res) if auth_res.success() => return Ok(()),
+ Ok(auth_res) if auth_res.success() => return Ok(AgentAuthenticationOutcome::Success),
+ Ok(auth_res) if auth_result_offers_keyboard_interactive(&auth_res) => {
+ return Ok(AgentAuthenticationOutcome::KeyboardInteractiveRequired)
+ }
Ok(_) => continue,
Err(e) => {
log::debug!("SSH agent identity ({}) auth failed: {e}", identity.comment());
@@ -435,7 +600,7 @@ async fn try_authenticate_with_agent(
.await;
match auth_result {
- Ok(Ok(())) => Ok(()),
+ Ok(Ok(outcome)) => Ok(outcome),
Ok(Err(e)) => Err(e),
Err(_) => Err("No SSH password or key provided, and ssh-agent auth timed out".to_string()),
}
@@ -577,9 +742,27 @@ fn read_u32(bytes: &[u8], pos: &mut usize) -> Result<u32, String> {
Ok(u32::from_be_bytes(value.try_into().map_err(|_| "OpenSSH key field length is invalid".to_string())?))
}
+/// Build a POSIX-shell-safe netcat command for SSH servers (notably
+/// JumpServer/Koko) that reject `direct-tcpip` but allow an exec channel on the
+/// selected asset. The target is single-quoted because it originates in the
+/// connection configuration and is ultimately passed through a remote shell.
+fn netcat_proxy_command(remote_host: &str, remote_port: u16) -> Result<String, String> {
+ if remote_host.is_empty() || remote_host.contains('\0') || remote_host.chars().any(char::is_control) {
+ return Err("SSH tunnel target host is invalid".to_string());
+ }
+ let quoted_host = remote_host.replace('\'', "'\\''");
+ Ok(format!("exec nc '{quoted_host}' {remote_port}"))
+}
+
/// Accept connections on the local listener and forward them through the SSH session.
/// Returns when the SSH session dies (listener error or session.is_closed()).
-async fn forward_loop(session: &Handle<SshClient>, listener: &TcpListener, remote_host: &str, remote_port: u16) {
+async fn forward_loop(
+ session: &Handle<SshClient>,
+ listener: &TcpListener,
+ remote_host: &str,
+ remote_port: u16,
+ allow_exec_channel_proxy: bool,
+) {
let mut idle_check = tokio::time::interval(IDLE_SESSION_CHECK_INTERVAL);
idle_check.set_missed_tick_behavior(MissedTickBehavior::Delay);
@@ -619,7 +802,7 @@ async fn forward_loop(session: &Handle<SshClient>, listener: &TcpListener, remot
break;
}
- let mut channel = match session
+ let channel = match session
.channel_open_direct_tcpip(
remote_host,
remote_port.into(),
@@ -629,6 +812,37 @@ async fn forward_loop(session: &Handle<SshClient>, listener: &TcpListener, remot
.await
{
Ok(c) => c,
+ Err(russh::Error::ChannelOpenFailure(ChannelOpenFailure::AdministrativelyProhibited))
+ if allow_exec_channel_proxy =>
+ {
+ // JumpServer/Koko deliberately disables SSH direct-tcpip even
+ // for a directly selected asset. An exec channel is still
+ // proxied to that asset, so use netcat there as a byte stream.
+ let command = match netcat_proxy_command(remote_host, remote_port) {
+ Ok(command) => command,
+ Err(e) => {
+ log::error!("SSH netcat fallback rejected the target: {e}");
+ continue;
+ }
+ };
+ let channel = match session.channel_open_session().await {
+ Ok(channel) => channel,
+ Err(e) => {
+ log::error!("SSH netcat fallback could not open a session channel: {e}");
+ continue;
+ }
+ };
+ if let Err(e) = channel.exec(true, command).await {
+ log::error!("SSH netcat fallback could not start nc: {e}");
+ continue;
+ }
+ log::info!("SSH direct-tcpip is disabled; forwarding through a remote nc session");
+ channel
+ }
+ Err(russh::Error::ChannelOpenFailure(ChannelOpenFailure::AdministrativelyProhibited)) => {
+ log::warn!("SSH direct-tcpip was administratively prohibited; exec-channel proxy fallback is disabled");
+ break;
+ }
Err(e) => {
log::error!("SSH direct-tcpip failed: {e}");
break;
@@ -636,37 +850,9 @@ async fn forward_loop(session: &Handle<SshClient>, listener: &TcpListener, remot
};
tokio::spawn(async move {
- let mut buf = vec![0u8; 65536];
- let mut stream_closed = false;
-
- loop {
- tokio::select! {
- r = stream.read(&mut buf), if !stream_closed => {
- match r {
- Ok(0) => {
- stream_closed = true;
- let _ = channel.eof().await;
- }
- Ok(n) => {
- if channel.data(&buf[..n]).await.is_err() {
- break;
- }
- }
- Err(_) => break,
- }
- }
- msg = channel.wait() => {
- match msg {
- Some(ChannelMsg::Data { ref data }) => {
- if stream.write_all(data).await.is_err() {
- break;
- }
- }
- Some(ChannelMsg::Eof) | None => break,
- _ => {}
- }
- }
- }
+ let mut channel_stream = channel.into_stream();
+ if let Err(e) = tokio::io::copy_bidirectional(&mut stream, &mut channel_stream).await {
+ log::debug!("SSH tunnel stream ended with an I/O error: {e}");
}
});
}
@@ -696,11 +882,12 @@ async fn tunnel_reconnect_loop(
listener: TcpListener,
remote_host: String,
remote_port: u16,
+ allow_exec_channel_proxy: bool,
) {
loop {
log::info!("SSH tunnel active: {}:{} -> {}:{}", connect_host, connect_port, remote_host, remote_port);
- forward_loop(&session, &listener, &remote_host, remote_port).await;
+ forward_loop(&session, &listener, &remote_host, remote_port, allow_exec_channel_proxy).await;
log::warn!("SSH tunnel connection lost ({}:{}), reconnecting...", connect_host, connect_port);
@@ -824,6 +1011,7 @@ impl TunnelManager {
remote_host: &str,
remote_port: u16,
expose_to_lan: bool,
+ allow_exec_channel_proxy: bool,
) -> Result<u16, String> {
{
let mut tunnels = self.tunnels.lock().await;
@@ -859,6 +1047,7 @@ impl TunnelManager {
remote_host,
remote_port,
expose_to_lan,
+ allow_exec_channel_proxy,
)
.await?;
@@ -933,6 +1122,7 @@ impl TunnelManager {
&target_host,
target_port,
is_last && hop.expose_lan,
+ hop.allow_exec_channel_proxy,
)
.await
.map_err(|err| format!("SSH hop {} failed: {err}", index + 1))?;
@@ -1008,6 +1198,7 @@ async fn spawn_tunnel(
remote_host: &str,
remote_port: u16,
expose_to_lan: bool,
+ allow_exec_channel_proxy: bool,
) -> Result<(JoinHandle<()>, u16), String> {
let local_port = portpicker::pick_unused_port().ok_or("No available port")?;
@@ -1051,6 +1242,7 @@ async fn spawn_tunnel(
listener,
remote_host.to_string(),
remote_port,
+ allow_exec_channel_proxy,
));
Ok((handle, local_port))
@@ -1108,9 +1300,9 @@ mod tests {
use super::SshClient;
use super::PROMPT_TEST_LOCK;
use super::{
- connect_and_authenticate, effective_hop_timeout, openssh_padding_len, plan_chain, read_ssh_string,
- sanitize_unencrypted_openssh_comment_bytes, server_offers_password, ssh_client_config, HostKeyState,
- HostKeyVerifier, PlannedTunnel, TunnelManager,
+ connect_and_authenticate, effective_hop_timeout, netcat_proxy_command, openssh_padding_len, plan_chain,
+ read_ssh_string, sanitize_unencrypted_openssh_comment_bytes, server_offers_keyboard_interactive,
+ 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};
@@ -1118,12 +1310,16 @@ mod tests {
use russh::client::Handler;
use russh::keys::decode_secret_key;
use russh::keys::ssh_key::PublicKey;
- use russh::server::{self, Auth, Server};
+ use russh::server::{self, Auth, Response, Server};
use russh::MethodKind;
use russh::MethodSet;
+ use russh::{Channel, ChannelId};
+ use std::borrow::Cow;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use tempfile::tempdir;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::TcpStream;
use tokio::sync::mpsc;
fn push_u32(bytes: &mut Vec<u8>, value: u32) {
@@ -1175,6 +1371,7 @@ mod tests {
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
+ allow_exec_channel_proxy: false,
}
}
@@ -1465,6 +1662,22 @@ mod tests {
assert!(!server_offers_password(&empty));
}
+ #[test]
+ fn detects_keyboard_interactive_auth_method() {
+ let keyboard_interactive = MethodSet::from(&[MethodKind::KeyboardInteractive][..]);
+ assert!(server_offers_keyboard_interactive(&keyboard_interactive));
+
+ let password_only = MethodSet::from(&[MethodKind::Password][..]);
+ assert!(!server_offers_keyboard_interactive(&password_only));
+ }
+
+ #[test]
+ fn netcat_fallback_quotes_the_target_for_the_remote_shell() {
+ assert_eq!(netcat_proxy_command("10.0.0.5", 5432).unwrap(), "exec nc '10.0.0.5' 5432");
+ assert_eq!(netcat_proxy_command("db'prod.internal", 3306).unwrap(), "exec nc 'db'\\''prod.internal' 3306");
+ assert!(netcat_proxy_command("db.internal\nmalicious-command", 5432).is_err());
+ }
+
// --- MITM hardening: a changed/unknown host never receives the password ---
const TEST_SERVER_KEY_PEM: &str = r#"-----BEGIN OPENSSH PRIVATE KEY-----
@@ -1475,6 +1688,172 @@ AAAEDxqdMQX37UdhziSi5Br3kyRM/Xrpo9ZcXoguYkeogq0hUOWHAoGT5Axk35Y0BQovqo
uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
-----END OPENSSH PRIVATE KEY-----"#;
+ struct PasswordThenTotpServer;
+
+ impl server::Server for PasswordThenTotpServer {
+ type Handler = PasswordThenTotpHandler;
+
+ fn new_client(&mut self, _peer: Option<std::net::SocketAddr>) -> PasswordThenTotpHandler {
+ PasswordThenTotpHandler
+ }
+ }
+
+ struct PasswordThenTotpHandler;
+
+ impl server::Handler for PasswordThenTotpHandler {
+ type Error = russh::Error;
+
+ async fn auth_password(&mut self, _user: &str, password: &str) -> Result<Auth, Self::Error> {
+ if password == "secret" {
+ Ok(Auth::Reject {
+ proceed_with_methods: Some(MethodSet::from(&[MethodKind::KeyboardInteractive][..])),
+ partial_success: true,
+ })
+ } else {
+ Ok(Auth::reject())
+ }
+ }
+
+ async fn auth_publickey(
+ &mut self,
+ _user: &str,
+ _public_key: &russh::keys::ssh_key::PublicKey,
+ ) -> Result<Auth, Self::Error> {
+ Ok(Auth::Reject {
+ proceed_with_methods: Some(MethodSet::from(&[MethodKind::KeyboardInteractive][..])),
+ partial_success: true,
+ })
+ }
+
+ async fn auth_keyboard_interactive<'a>(
+ &'a mut self,
+ _user: &str,
+ _submethods: &str,
+ mut response: Option<Response<'a>>,
+ ) -> Result<Auth, Self::Error> {
+ let Some(ref mut answers) = response else {
+ return Ok(Auth::Partial {
+ name: Cow::Borrowed("JumpServer"),
+ instructions: Cow::Borrowed("Multi-factor authentication"),
+ prompts: Cow::Owned(vec![(Cow::Borrowed("OTP Code: "), false)]),
+ });
+ };
+
+ if answers.next().as_deref() == Some(b"123456") {
+ Ok(Auth::Accept)
+ } else {
+ Ok(Auth::reject())
+ }
+ }
+ }
+
+ async fn start_password_then_totp_server() -> (u16, tokio::task::JoinHandle<()>) {
+ let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
+ let server_config = server::Config {
+ keys: vec![server_key],
+ methods: MethodSet::from(
+ &[MethodKind::Password, MethodKind::PublicKey, MethodKind::KeyboardInteractive][..],
+ ),
+ auth_rejection_time: std::time::Duration::ZERO,
+ auth_rejection_time_initial: Some(std::time::Duration::ZERO),
+ ..Default::default()
+ };
+ let port = portpicker::pick_unused_port().expect("no free port");
+ let mut server = PasswordThenTotpServer;
+ let task = tokio::spawn(async move {
+ let _ = server.run_on_address(Arc::new(server_config), ("127.0.0.1", port)).await;
+ });
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ (port, task)
+ }
+
+ #[tokio::test]
+ async fn password_auth_continues_with_keyboard_interactive_totp() {
+ let _guard = PROMPT_TEST_LOCK.lock().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+ let (port, server_task) = start_password_then_totp_server().await;
+ let dir = tempdir().unwrap();
+ let known_hosts_path = dir.path().join("known_hosts");
+ HostKeyVerifier::new(known_hosts_path.clone()).learn("127.0.0.1", port, &test_server_public_key()).unwrap();
+
+ let (gateway_tx, mut gateway_rx) = mpsc::channel::<ssh_prompt::SshPromptEnvelope>(1);
+ let (observed_tx, observed_rx) = tokio::sync::oneshot::channel();
+ tokio::spawn(async move {
+ let envelope = gateway_rx.recv().await.expect("TOTP prompt");
+ let _ = observed_tx.send((envelope.request.kind, envelope.request.prompt.clone(), envelope.request.echo));
+ let _ = envelope.responder.send(ssh_prompt::SshPromptAnswer::Secret("123456".to_string()));
+ });
+ ssh_prompt::install_ssh_prompt_gateway(gateway_tx);
+
+ let session = connect_and_authenticate(
+ "127.0.0.1",
+ port,
+ "127.0.0.1",
+ port,
+ "user",
+ "secret",
+ "",
+ "",
+ false,
+ "",
+ "password",
+ 5,
+ &known_hosts_path,
+ )
+ .await
+ .expect("password + TOTP authentication should succeed");
+
+ let (kind, prompt, echo) = observed_rx.await.unwrap();
+ assert_eq!(kind, ssh_prompt::SshPromptKind::SecretInput);
+ assert!(prompt.unwrap().contains("OTP Code"));
+ assert!(!echo, "TOTP response should not be echoed");
+
+ drop(session);
+ ssh_prompt::clear_ssh_prompt_gateway();
+ server_task.abort();
+ }
+
+ #[tokio::test]
+ async fn public_key_auth_continues_with_keyboard_interactive_totp() {
+ let _guard = PROMPT_TEST_LOCK.lock().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+ let (port, server_task) = start_password_then_totp_server().await;
+ let dir = tempdir().unwrap();
+ let known_hosts_path = dir.path().join("known_hosts");
+ let key_path = dir.path().join("id_ed25519");
+ std::fs::write(&key_path, TEST_SERVER_KEY_PEM).unwrap();
+ HostKeyVerifier::new(known_hosts_path.clone()).learn("127.0.0.1", port, &test_server_public_key()).unwrap();
+
+ let (gateway_tx, mut gateway_rx) = mpsc::channel::<ssh_prompt::SshPromptEnvelope>(1);
+ tokio::spawn(async move {
+ let envelope = gateway_rx.recv().await.expect("TOTP prompt");
+ let _ = envelope.responder.send(ssh_prompt::SshPromptAnswer::Secret("123456".to_string()));
+ });
+ ssh_prompt::install_ssh_prompt_gateway(gateway_tx);
+
+ let session = connect_and_authenticate(
+ "127.0.0.1",
+ port,
+ "127.0.0.1",
+ port,
+ "user",
+ "",
+ key_path.to_str().unwrap(),
+ "",
+ false,
+ "",
+ "key",
+ 5,
+ &known_hosts_path,
+ )
+ .await
+ .expect("public key + TOTP authentication should succeed");
+
+ drop(session);
+ ssh_prompt::clear_ssh_prompt_gateway();
+ server_task.abort();
+ }
+
struct AcceptNoneServer;
impl server::Server for AcceptNoneServer {
@@ -1507,6 +1886,176 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
(port, task)
}
+ struct NetcatFallbackServer {
+ command: Arc<std::sync::Mutex<Vec<u8>>>,
+ }
+
+ impl server::Server for NetcatFallbackServer {
+ type Handler = NetcatFallbackHandler;
+
+ fn new_client(&mut self, _peer: Option<std::net::SocketAddr>) -> NetcatFallbackHandler {
+ NetcatFallbackHandler { command: self.command.clone() }
+ }
+ }
+
+ struct NetcatFallbackHandler {
+ command: Arc<std::sync::Mutex<Vec<u8>>>,
+ }
+
+ impl server::Handler for NetcatFallbackHandler {
+ type Error = russh::Error;
+
+ async fn auth_none(&mut self, _user: &str) -> Result<Auth, Self::Error> {
+ Ok(Auth::Accept)
+ }
+
+ async fn channel_open_direct_tcpip(
+ &mut self,
+ _channel: Channel<server::Msg>,
+ _host_to_connect: &str,
+ _port_to_connect: u32,
+ _originator_address: &str,
+ _originator_port: u32,
+ _session: &mut server::Session,
+ ) -> Result<bool, Self::Error> {
+ Ok(false)
+ }
+
+ async fn channel_open_session(
+ &mut self,
+ _channel: Channel<server::Msg>,
+ _session: &mut server::Session,
+ ) -> Result<bool, Self::Error> {
+ Ok(true)
+ }
+
+ async fn exec_request(
+ &mut self,
+ channel: ChannelId,
+ data: &[u8],
+ session: &mut server::Session,
+ ) -> Result<(), Self::Error> {
+ *self.command.lock().unwrap() = data.to_vec();
+ session.channel_success(channel)?;
+ Ok(())
+ }
+
+ async fn data(
+ &mut self,
+ channel: ChannelId,
+ data: &[u8],
+ session: &mut server::Session,
+ ) -> Result<(), Self::Error> {
+ session.data(channel, data.to_vec())?;
+ Ok(())
+ }
+ }
+
+ #[tokio::test]
+ async fn tunnel_falls_back_to_netcat_when_direct_tcpip_is_prohibited() {
+ let _guard = PROMPT_TEST_LOCK.lock().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+ let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
+ let server_config = server::Config { keys: vec![server_key], ..Default::default() };
+ let port = portpicker::pick_unused_port().expect("no free port");
+ let command = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let mut server = NetcatFallbackServer { command: command.clone() };
+ let server_task = tokio::spawn(async move {
+ let _ = server.run_on_address(Arc::new(server_config), ("127.0.0.1", port)).await;
+ });
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+
+ let dir = tempdir().unwrap();
+ let known_hosts_path = dir.path().join("known_hosts");
+ HostKeyVerifier::new(known_hosts_path.clone()).learn("127.0.0.1", port, &test_server_public_key()).unwrap();
+ let manager = TunnelManager::new(dir.path().to_path_buf());
+ let local_port = manager
+ .start_tunnel(
+ "netcat-fallback",
+ "127.0.0.1",
+ port,
+ "127.0.0.1",
+ port,
+ "user",
+ "",
+ "",
+ "",
+ false,
+ "",
+ "none",
+ 5,
+ "db.internal",
+ 5432,
+ false,
+ true,
+ )
+ .await
+ .expect("start fallback tunnel");
+
+ let mut client = TcpStream::connect(("127.0.0.1", local_port)).await.unwrap();
+ client.write_all(b"ping").await.unwrap();
+ let mut echoed = [0_u8; 4];
+ tokio::time::timeout(std::time::Duration::from_secs(5), client.read_exact(&mut echoed))
+ .await
+ .expect("fallback echo timeout")
+ .expect("fallback echo read");
+ assert_eq!(&echoed, b"ping");
+ assert_eq!(&*command.lock().unwrap(), b"exec nc 'db.internal' 5432");
+
+ manager.stop_tunnel("netcat-fallback").await;
+ server_task.abort();
+ }
+
+ #[tokio::test]
+ async fn prohibited_direct_tcpip_does_not_run_netcat_by_default() {
+ let _guard = PROMPT_TEST_LOCK.lock().await;
+ ssh_prompt::clear_ssh_prompt_gateway();
+ let server_key = decode_secret_key(TEST_SERVER_KEY_PEM, None).expect("decode test server key");
+ let server_config = server::Config { keys: vec![server_key], ..Default::default() };
+ let port = portpicker::pick_unused_port().expect("no free port");
+ let command = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let mut server = NetcatFallbackServer { command: command.clone() };
+ let server_task = tokio::spawn(async move {
+ let _ = server.run_on_address(Arc::new(server_config), ("127.0.0.1", port)).await;
+ });
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+
+ let dir = tempdir().unwrap();
+ let known_hosts_path = dir.path().join("known_hosts");
+ HostKeyVerifier::new(known_hosts_path.clone()).learn("127.0.0.1", port, &test_server_public_key()).unwrap();
+ let manager = TunnelManager::new(dir.path().to_path_buf());
+ let local_port = manager
+ .start_tunnel(
+ "netcat-disabled-by-default",
+ "127.0.0.1",
+ port,
+ "127.0.0.1",
+ port,
+ "user",
+ "",
+ "",
+ "",
+ false,
+ "",
+ "none",
+ 5,
+ "db.internal",
+ 5432,
+ false,
+ false,
+ )
+ .await
+ .expect("start tunnel");
+
+ let mut client = TcpStream::connect(("127.0.0.1", local_port)).await.unwrap();
+ let _ = client.write_all(b"ping").await;
+ tokio::time::sleep(std::time::Duration::from_millis(300)).await;
+ assert!(command.lock().unwrap().is_empty(), "generic SSH server must not receive an nc command by default");
+
+ manager.stop_tunnel("netcat-disabled-by-default").await;
+ server_task.abort();
+ }
+
#[tokio::test]
async fn forwarded_connection_checks_logical_host_identity() {
let _guard = PROMPT_TEST_LOCK.lock().await;
@@ -1587,6 +2136,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"db.internal",
5432,
false,
+ false,
);
let second = manager.start_tunnel(
"shared-layer",
@@ -1605,6 +2155,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"db.internal",
5432,
false,
+ false,
);
let (first_port, second_port) = tokio::join!(first, second);
diff --git a/crates/dbx-core/src/db/transport_layer_tunnel.rs b/crates/dbx-core/src/db/transport_layer_tunnel.rs
index acd1b688be..7e9a547e62 100644
--- a/crates/dbx-core/src/db/transport_layer_tunnel.rs
+++ b/crates/dbx-core/src/db/transport_layer_tunnel.rs
@@ -92,6 +92,7 @@ pub async fn start_transport_layers(
&target_endpoint.host,
target_endpoint.port,
is_last && resolved.expose_lan,
+ resolved.allow_exec_channel_proxy,
)
.await
.map_err(|err| format!("SSH layer {} failed: {err}", index + 1))?,
@@ -264,6 +265,7 @@ mod tests {
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
+ allow_exec_channel_proxy: false,
})
}
diff --git a/crates/dbx-core/src/models/connection.rs b/crates/dbx-core/src/models/connection.rs
index fee953379c..e257a31a86 100644
--- a/crates/dbx-core/src/models/connection.rs
+++ b/crates/dbx-core/src/models/connection.rs
@@ -320,6 +320,11 @@ pub struct SshTunnelConfig {
/// password auth if the key is rejected.
#[serde(default)]
pub auth_method: String,
+ /// Allow an SSH session exec channel to run `nc` when the server rejects
+ /// `direct-tcpip`. Disabled by default because this can bypass a server's
+ /// TCP-forwarding policy; enable only for trusted JumpServer/Koko setups.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub allow_exec_channel_proxy: bool,
/// When non-empty, this layer references a shared tunnel profile
/// (Settings > Tunnels). The profile's configuration replaces this
/// layer's own fields at connect time; only `id` and `enabled` are
diff --git a/crates/dbx-core/src/ssh_config.rs b/crates/dbx-core/src/ssh_config.rs
index 479cc790be..cd55dc545c 100644
--- a/crates/dbx-core/src/ssh_config.rs
+++ b/crates/dbx-core/src/ssh_config.rs
@@ -194,6 +194,7 @@ mod tests {
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
+ allow_exec_channel_proxy: false,
}
}
diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rs
index 2e870d3e9b..51106e5963 100644
--- a/crates/dbx-core/src/storage.rs
+++ b/crates/dbx-core/src/storage.rs
@@ -4094,6 +4094,7 @@ mod tests {
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
+ allow_exec_channel_proxy: false,
profile_id: String::new(),
})
}
diff --git a/crates/dbx-web/src/ssh_prompt.rs b/crates/dbx-web/src/ssh_prompt.rs
index 23ba5aa5bd..aa89bbe991 100644
--- a/crates/dbx-web/src/ssh_prompt.rs
+++ b/crates/dbx-web/src/ssh_prompt.rs
@@ -133,6 +133,7 @@ mod tests {
key_type: Some("ssh-ed25519".to_string()),
fingerprint: Some("SHA256:test".to_string()),
prompt: None,
+ echo: false,
}
}
diff --git a/src-tauri/src/commands/ssh_prompt.rs b/src-tauri/src/commands/ssh_prompt.rs
index d2cc2d2702..da1ea8bc05 100644
--- a/src-tauri/src/commands/ssh_prompt.rs
+++ b/src-tauri/src/commands/ssh_prompt.rs
@@ -264,6 +264,7 @@ mod tests {
key_type: Some("ssh-ed25519".to_string()),
fingerprint: Some("SHA256:test".to_string()),
prompt: None,
+ echo: false,
}
}