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): select the SSH agent identity instead of every key

wenzuowei8243eae8506e
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vue
index 98afa3b6b5..528f16c437 100644
--- a/apps/desktop/src/components/connection/ConnectionDialog.vue
+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue
@@ -32,6 +32,7 @@ import type {
PluginFormField,
PluginFormFieldValue,
ProxyTunnelConfig,
+ SshAgentIdentity,
SshConfigHostEntry,
SshTunnelConfig,
TransportLayerConfig,
@@ -534,6 +535,7 @@ function defaultSshTunnel(): SshTunnelConfig {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: "",
+ ssh_agent_key_fingerprint: "",
auth_method: "password",
allow_exec_channel_proxy: false,
proxy_command: "",
@@ -555,6 +557,7 @@ function normalizeSshTunnel(hop: Partial<SshTunnelConfig>): SshTunnelConfig {
expose_lan: !!hop.expose_lan,
use_ssh_agent: !!hop.use_ssh_agent,
ssh_agent_sock_path: hop.ssh_agent_sock_path || "",
+ ssh_agent_key_fingerprint: hop.ssh_agent_key_fingerprint || "",
auth_method: hop.auth_method || inferSshAuthMethod(hop),
allow_exec_channel_proxy: !!hop.allow_exec_channel_proxy,
proxy_command: hop.proxy_command || "",
@@ -6933,6 +6936,58 @@ async function browseSshKeyPath(target?: SshTunnelConfig | null) {
}
}
+const SSH_AGENT_ALL_IDENTITIES = "__all__";
+const sshAgentIdentities = ref<SshAgentIdentity[]>([]);
+const sshAgentIdentitiesLoading = ref(false);
+const sshAgentIdentitiesError = ref("");
+let sshAgentIdentitiesTimer: ReturnType<typeof setTimeout> | undefined;
+let sshAgentIdentitiesRequest = 0;
+
+const sshAgentIdentityOptions = computed(() => {
+ const fingerprint = selectedSshLayer.value?.ssh_agent_key_fingerprint || "";
+ if (!fingerprint || sshAgentIdentities.value.some((identity) => identity.fingerprint === fingerprint)) {
+ return sshAgentIdentities.value;
+ }
+ return [{ fingerprint, algorithm: "", comment: "" }, ...sshAgentIdentities.value];
+});
+
+function sshAgentIdentityLabel(identity: SshAgentIdentity) {
+ if (!identity.comment) return identity.fingerprint;
+ return identity.algorithm ? `${identity.comment} (${identity.algorithm})` : identity.comment;
+}
+
+function updateSelectedSshAgentKeyFingerprint(value: unknown) {
+ if (!selectedSshLayer.value) return;
+ const fingerprint = String(value);
+ selectedSshLayer.value.ssh_agent_key_fingerprint = fingerprint === SSH_AGENT_ALL_IDENTITIES ? "" : fingerprint;
+}
+
+async function loadSshAgentIdentities(sshAgentSockPath: string) {
+ const request = ++sshAgentIdentitiesRequest;
+ sshAgentIdentitiesLoading.value = true;
+ sshAgentIdentitiesError.value = "";
+ try {
+ const identities = await api.listSshAgentIdentities(sshAgentSockPath);
+ if (request === sshAgentIdentitiesRequest) sshAgentIdentities.value = identities;
+ } catch (cause) {
+ if (request === sshAgentIdentitiesRequest) {
+ sshAgentIdentitiesError.value = t("connection.sshAgentKeyLoadFailed", { error: cause instanceof Error ? cause.message : String(cause) });
+ }
+ } finally {
+ if (request === sshAgentIdentitiesRequest) sshAgentIdentitiesLoading.value = false;
+ }
+}
+
+watch(
+ () => (selectedSshLayer.value?.auth_method === "agent" ? selectedSshLayer.value.ssh_agent_sock_path || "" : null),
+ (sshAgentSockPath) => {
+ if (sshAgentSockPath === null) return;
+ clearTimeout(sshAgentIdentitiesTimer);
+ sshAgentIdentitiesTimer = setTimeout(() => void loadSshAgentIdentities(sshAgentSockPath), 400);
+ },
+ { immediate: true },
+);
+
async function browseCaCertPath() {
if (isTauriRuntime()) {
const { open } = await import("@tauri-apps/plugin-dialog");
@@ -10931,6 +10986,35 @@ function openExternalUrl(url: string) {
<Label :class="connectionLabelSmallClass">{{ t("connection.sshAgentSockPath") }}</Label>
<Input v-model="selectedSshLayer.ssh_agent_sock_path" class="col-span-3" :placeholder="t('connection.sshAgentSockPathPlaceholder')" :disabled="selectedSshLayer.enabled === false" />
</div>
+ <div v-if="selectedSshLayer.auth_method === 'agent'" class="grid grid-cols-4 items-center gap-4">
+ <Label :class="connectionLabelSmallClass">{{ t("connection.sshAgentKey") }}</Label>
+ <div class="col-span-3 flex min-w-0 items-center gap-1">
+ <div class="min-w-0 flex-1">
+ <Select :model-value="selectedSshLayer.ssh_agent_key_fingerprint || SSH_AGENT_ALL_IDENTITIES" :disabled="selectedSshLayer.enabled === false" @update:model-value="updateSelectedSshAgentKeyFingerprint">
+ <SelectTrigger class="h-9 w-full min-w-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem :value="SSH_AGENT_ALL_IDENTITIES">{{ t("connection.sshAgentKeyAll") }}</SelectItem>
+ <SelectItem v-for="identity in sshAgentIdentityOptions" :key="identity.fingerprint" :value="identity.fingerprint" :title="identity.fingerprint">
+ {{ sshAgentIdentityLabel(identity) }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :title="t('connection.sshAgentKeyRefresh')" :disabled="selectedSshLayer.enabled === false || sshAgentIdentitiesLoading" @click="loadSshAgentIdentities(selectedSshLayer.ssh_agent_sock_path || '')">
+ <Loader2 v-if="sshAgentIdentitiesLoading" class="h-4 w-4 animate-spin" />
+ <RefreshCw v-else class="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ <div v-if="selectedSshLayer.auth_method === 'agent'" class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <div class="col-span-3 text-xs text-muted-foreground">
+ <p>{{ t("connection.sshAgentKeyHint") }}</p>
+ <p v-if="sshAgentIdentitiesError" class="mt-1">{{ sshAgentIdentitiesError }}</p>
+ </div>
+ </div>
<div class="grid grid-cols-4 items-center gap-4">
<span />
<label class="col-span-3 flex items-center gap-2 cursor-pointer">
diff --git a/apps/desktop/src/components/connection/TunnelProfileManager.vue b/apps/desktop/src/components/connection/TunnelProfileManager.vue
index e73339854a..ccadbba6df 100644
--- a/apps/desktop/src/components/connection/TunnelProfileManager.vue
+++ b/apps/desktop/src/components/connection/TunnelProfileManager.vue
@@ -7,7 +7,7 @@ import PasswordInput from "@/components/ui/PasswordInput.vue";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { Loader2, Plus, Trash2, FolderOpen } from "@lucide/vue";
+import { Loader2, Plus, Trash2, FolderOpen, RefreshCw } from "@lucide/vue";
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
import { useToast } from "@/composables/useToast";
import { useTunnelProfileStore } from "@/stores/tunnelProfileStore";
@@ -16,7 +16,7 @@ import { applySshConfigHostAliasPrefill as prefillSshConfigHostAlias } from "@/l
import { applySshAuthMethod } from "@/lib/connection/sshAuthMethod";
import { stripInvisibleCharactersFromLayer } from "@/lib/connection/credentialSanitizer";
import * as api from "@/lib/backend/api";
-import type { SshConfigHostEntry, TunnelProfile } from "@/types/database";
+import type { SshAgentIdentity, SshConfigHostEntry, TunnelProfile } from "@/types/database";
import { translateBackendError } from "@/i18n/backend-errors";
const { t } = useI18n();
@@ -81,6 +81,58 @@ function updateSelectedSshHost(value: string | number) {
void loadSshConfigHosts();
+const SSH_AGENT_ALL_IDENTITIES = "__all__";
+const sshAgentIdentities = ref<SshAgentIdentity[]>([]);
+const sshAgentIdentitiesLoading = ref(false);
+const sshAgentIdentitiesError = ref("");
+let sshAgentIdentitiesTimer: ReturnType<typeof setTimeout> | undefined;
+let sshAgentIdentitiesRequest = 0;
+
+const sshAgentIdentityOptions = computed(() => {
+ const fingerprint = selectedSsh.value?.ssh_agent_key_fingerprint || "";
+ if (!fingerprint || sshAgentIdentities.value.some((identity) => identity.fingerprint === fingerprint)) {
+ return sshAgentIdentities.value;
+ }
+ return [{ fingerprint, algorithm: "", comment: "" }, ...sshAgentIdentities.value];
+});
+
+function sshAgentIdentityLabel(identity: SshAgentIdentity) {
+ if (!identity.comment) return identity.fingerprint;
+ return identity.algorithm ? `${identity.comment} (${identity.algorithm})` : identity.comment;
+}
+
+function updateSelectedSshAgentKeyFingerprint(value: unknown) {
+ if (!selectedSsh.value) return;
+ const fingerprint = String(value);
+ selectedSsh.value.ssh_agent_key_fingerprint = fingerprint === SSH_AGENT_ALL_IDENTITIES ? "" : fingerprint;
+}
+
+async function loadSshAgentIdentities(sshAgentSockPath: string) {
+ const request = ++sshAgentIdentitiesRequest;
+ sshAgentIdentitiesLoading.value = true;
+ sshAgentIdentitiesError.value = "";
+ try {
+ const identities = await api.listSshAgentIdentities(sshAgentSockPath);
+ if (request === sshAgentIdentitiesRequest) sshAgentIdentities.value = identities;
+ } catch (cause) {
+ if (request === sshAgentIdentitiesRequest) {
+ sshAgentIdentitiesError.value = t("connection.sshAgentKeyLoadFailed", { error: cause instanceof Error ? cause.message : String(cause) });
+ }
+ } finally {
+ if (request === sshAgentIdentitiesRequest) sshAgentIdentitiesLoading.value = false;
+ }
+}
+
+watch(
+ () => (selectedSsh.value?.auth_method === "agent" ? selectedSsh.value.ssh_agent_sock_path || "" : null),
+ (sshAgentSockPath) => {
+ if (sshAgentSockPath === null) return;
+ clearTimeout(sshAgentIdentitiesTimer);
+ sshAgentIdentitiesTimer = setTimeout(() => void loadSshAgentIdentities(sshAgentSockPath), 400);
+ },
+ { immediate: true },
+);
+
function invalidateProfileTest() {
testGuard.invalidate();
isTesting.value = false;
@@ -311,6 +363,35 @@ async function testSelected() {
<Label class="text-xs">{{ t("connection.sshAgentSockPath") }}</Label>
<Input v-model="selectedSsh.ssh_agent_sock_path" class="col-span-3" :placeholder="t('connection.sshAgentSockPathPlaceholder')" />
</div>
+ <div v-if="selectedSsh.auth_method === 'agent'" class="grid grid-cols-4 items-center gap-4">
+ <Label class="text-xs">{{ t("connection.sshAgentKey") }}</Label>
+ <div class="col-span-3 flex min-w-0 items-center gap-1">
+ <div class="min-w-0 flex-1">
+ <Select :model-value="selectedSsh.ssh_agent_key_fingerprint || SSH_AGENT_ALL_IDENTITIES" @update:model-value="updateSelectedSshAgentKeyFingerprint">
+ <SelectTrigger class="h-9 w-full min-w-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem :value="SSH_AGENT_ALL_IDENTITIES">{{ t("connection.sshAgentKeyAll") }}</SelectItem>
+ <SelectItem v-for="identity in sshAgentIdentityOptions" :key="identity.fingerprint" :value="identity.fingerprint" :title="identity.fingerprint">
+ {{ sshAgentIdentityLabel(identity) }}
+ </SelectItem>
+ </SelectContent>
+ </Select>
+ </div>
+ <Button variant="outline" size="icon" class="h-9 w-9 shrink-0" :title="t('connection.sshAgentKeyRefresh')" :disabled="sshAgentIdentitiesLoading" @click="loadSshAgentIdentities(selectedSsh.ssh_agent_sock_path || '')">
+ <Loader2 v-if="sshAgentIdentitiesLoading" class="h-4 w-4 animate-spin" />
+ <RefreshCw v-else class="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ <div v-if="selectedSsh.auth_method === 'agent'" class="grid grid-cols-4 items-start gap-4">
+ <span />
+ <div class="col-span-3 text-xs text-muted-foreground">
+ <p>{{ t("connection.sshAgentKeyHint") }}</p>
+ <p v-if="sshAgentIdentitiesError" class="mt-1">{{ sshAgentIdentitiesError }}</p>
+ </div>
+ </div>
<div class="grid grid-cols-4 items-center gap-4">
<span />
<label class="col-span-3 flex cursor-pointer items-center gap-2">
diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.ts
index b453622bb6..cf104a14fe 100644
--- a/apps/desktop/src/i18n/locales/en.ts
+++ b/apps/desktop/src/i18n/locales/en.ts
@@ -1942,6 +1942,11 @@ export default {
sshUseAgent: "Use ssh-agent",
sshAgentSockPath: "Agent Socket Path",
sshAgentSockPathPlaceholder: "e.g. ~/.ssh/agent.sock",
+ sshAgentKey: "Agent key",
+ sshAgentKeyAll: "All identities (try in order)",
+ sshAgentKeyHint: "Pick the key this host authorizes. Servers limit authentication attempts per connection, so offering every agent key can exhaust the limit before the right one is tried.",
+ sshAgentKeyLoadFailed: "Could not read the SSH agent's identities: {error}",
+ sshAgentKeyRefresh: "Refresh",
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",
diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.ts
index f13df78d86..be762dc2b2 100644
--- a/apps/desktop/src/i18n/locales/es.ts
+++ b/apps/desktop/src/i18n/locales/es.ts
@@ -1953,6 +1953,11 @@ export default withEnglishFallback({
redisClientKeyBrowse: "Seleccionar clave privada de cliente de Redis",
redisTlsCertificateHint: "Si el certificado CA se deja vacío, se utiliza el almacén de confianza del sistema; si el servidor requiere autenticación mutua (tls-auth-clients yes), configure también el certificado de cliente y la clave privada.",
redisClientCertPairRequired: "El certificado de cliente y la clave privada para TLS de Redis deben configurarse a la vez",
+ sshAgentKey: "Clave del agente",
+ sshAgentKeyAll: "Todas las identidades (probar en orden)",
+ sshAgentKeyHint: "Seleccione una clave autorizada para este host. El servidor limita el número de intentos de autenticación por conexión; probar todas las claves del agente una por una puede agotar los intentos antes de llegar a la clave correcta.",
+ sshAgentKeyLoadFailed: "No se pudo leer la lista de identidades del agente SSH: {error}",
+ sshAgentKeyRefresh: "Actualizar",
},
editor: {
duckdbDraining: "La consulta anterior de DuckDB aún se está deteniendo. Vuelva a intentarlo en breve.",
diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.ts
index d785324c65..e802c9d9b6 100644
--- a/apps/desktop/src/i18n/locales/it.ts
+++ b/apps/desktop/src/i18n/locales/it.ts
@@ -1862,6 +1862,11 @@ export default withEnglishFallback({
redisClientKeyBrowse: "Seleziona chiave privata client Redis",
redisTlsCertificateHint: "Se il certificato CA viene lasciato vuoto, viene utilizzato il trust store di sistema; se il server richiede l'autenticazione reciproca (tls-auth-clients yes), configurare anche il certificato client e la chiave privata.",
redisClientCertPairRequired: "Il certificato client e la chiave privata TLS di Redis devono essere configurati insieme",
+ sshAgentKey: "Chiave dell'agente",
+ sshAgentKeyAll: "Tutte le identità (prova in ordine)",
+ sshAgentKeyHint: "Seleziona una chiave autorizzata per questo host. Il server limita il numero di tentativi di autenticazione su una singola connessione; provare tutte le chiavi dell'agente una per una potrebbe esaurire i tentativi prima di arrivare a quella corretta.",
+ sshAgentKeyLoadFailed: "Impossibile leggere l'elenco delle identità dell'agente SSH: {error}",
+ sshAgentKeyRefresh: "Aggiorna",
},
editor: {
duckdbDraining: "La query DuckDB precedente è ancora in fase di arresto. Riprova a breve.",
diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.ts
index 1218b32c89..2945566610 100644
--- a/apps/desktop/src/i18n/locales/ja.ts
+++ b/apps/desktop/src/i18n/locales/ja.ts
@@ -1883,6 +1883,11 @@ export default withEnglishFallback({
redisClientKeyBrowse: "Redis クライアント秘密鍵を選択",
redisTlsCertificateHint: "CA 証明書を空欄にするとシステムの信頼ストアを使用します。サーバーが相互認証(tls-auth-clients yes)を要求する場合は、クライアント証明書と秘密鍵も合わせて設定してください。",
redisClientCertPairRequired: "Redis TLS のクライアント証明書と秘密鍵は同時に設定する必要があります",
+ sshAgentKey: "エージェントキー",
+ sshAgentKeyAll: "すべての identity(順番に試行)",
+ sshAgentKeyHint: "このホストで承認済みのキーを選択します。サーバーは単一接続での認証試行回数を制限するため、すべてのエージェントキーを順番に試すと、正しいキーに到達する前に試行回数を使い切る可能性があります。",
+ sshAgentKeyLoadFailed: "SSH エージェントの identity リストを読み取れません:{error}",
+ sshAgentKeyRefresh: "更新",
},
editor: {
duckdbDraining: "前回の DuckDB クエリはまだ停止処理中です。しばらくしてから再試行してください。",
diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.ts
index 74714253f1..04f4e91a61 100644
--- a/apps/desktop/src/i18n/locales/ko.ts
+++ b/apps/desktop/src/i18n/locales/ko.ts
@@ -1790,6 +1790,11 @@ export default withEnglishFallback({
redisClientKeyBrowse: "Redis 클라이언트 개인 키 선택",
redisTlsCertificateHint: "CA 인증서를 비워 두면 시스템 신뢰 저장소를 사용합니다. 서버에서 상호 인증(tls-auth-clients yes)을 요구하는 경우 클라이언트 인증서와 개인 키를 함께 구성하세요.",
redisClientCertPairRequired: "Redis TLS 클라이언트 인증서와 개인 키는 반드시 함께 구성해야 합니다",
+ sshAgentKey: "Agent 키",
+ sshAgentKeyAll: "모든 identity(순서대로 시도)",
+ sshAgentKeyHint: "해당 호스트에 대해 승인된 키를 선택하세요. 서버는 단일 연결에서 인증 시도 횟수를 제한하므로, 모든 agent 키를 하나씩 시도하다 보면 올바른 키 차례가 되기 전에 횟수를 다 써버릴 수 있습니다.",
+ sshAgentKeyLoadFailed: "SSH agent의 identity 목록을 읽을 수 없습니다: {error}",
+ sshAgentKeyRefresh: "새로 고침",
},
editor: {
duckdbDraining: "이전 DuckDB 쿼리가 아직 중지 중입니다. 잠시 후 다시 시도해 주세요.",
diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.ts
index 4804c309d6..8262153803 100644
--- a/apps/desktop/src/i18n/locales/pt-BR.ts
+++ b/apps/desktop/src/i18n/locales/pt-BR.ts
@@ -1863,6 +1863,11 @@ export default withEnglishFallback({
redisClientKeyBrowse: "Selecionar chave privada do cliente do Redis",
redisTlsCertificateHint: "Quando o certificado CA estiver em branco, o repositório de confiança do sistema será usado; se o servidor exigir autenticação mútua (tls-auth-clients yes), configure também o certificado do cliente e a chave privada.",
redisClientCertPairRequired: "O certificado do cliente Redis TLS e a chave privada devem ser configurados juntos",
+ sshAgentKey: "Chave do agente",
+ sshAgentKeyAll: "Todas as identidades (tentar em sequência)",
+ sshAgentKeyHint: "Selecione uma chave já autorizada para este host. O servidor limita o número de tentativas de autenticação por conexão; tentar todas as chaves do agente uma a uma pode esgotar as tentativas antes de chegar à chave correta.",
+ sshAgentKeyLoadFailed: "Não foi possível ler a lista de identidades do agente SSH: {error}",
+ sshAgentKeyRefresh: "Atualizar",
},
editor: {
duckdbDraining: "A consulta anterior do DuckDB ainda está sendo interrompida. Tente novamente em breve.",
diff --git a/apps/desktop/src/i18n/locales/ru.ts b/apps/desktop/src/i18n/locales/ru.ts
index a4bc850756..9371fec292 100644
--- a/apps/desktop/src/i18n/locales/ru.ts
+++ b/apps/desktop/src/i18n/locales/ru.ts
@@ -1863,6 +1863,11 @@ export default withEnglishFallback({
redisClientKeyBrowse: "Выбрать закрытый ключ клиента Redis",
redisTlsCertificateHint: "Если сертификат CA не указан, используется системное хранилище доверенных сертификатов; если сервер требует взаимной аутентификации (tls-auth-clients yes), настройте одновременно клиентский сертификат и закрытый ключ.",
redisClientCertPairRequired: "Для Redis TLS необходимо одновременно настроить клиентский сертификат и закрытый ключ",
+ sshAgentKey: "Ключ агента",
+ sshAgentKeyAll: "Все identity (пробовать по порядку)",
+ sshAgentKeyHint: "Выберите ключ, авторизованный для этого хоста. Сервер ограничивает число попыток аутентификации на одно соединение; при переборе всех ключей агента лимит может закончиться до того, как очередь дойдёт до правильного ключа.",
+ sshAgentKeyLoadFailed: "Не удалось прочитать список identity SSH-агента: {error}",
+ sshAgentKeyRefresh: "Обновить",
},
editor: {
duckdbDraining: "Предыдущий запрос DuckDB ещё завершается. Повторите попытку чуть позже.",
diff --git a/apps/desktop/src/i18n/locales/th.ts b/apps/desktop/src/i18n/locales/th.ts
index a227b889e1..63e189d11c 100644
--- a/apps/desktop/src/i18n/locales/th.ts
+++ b/apps/desktop/src/i18n/locales/th.ts
@@ -2060,6 +2060,11 @@ export default withEnglishFallback({
redisClientKeyBrowse: "เลือกคีย์ส่วนตัวไคลเอนต์ของ Redis",
redisTlsCertificateHint: "เมื่อเว้นว่างใบรับรอง CA ระบบจะใช้ที่เก็บความเชื่อถือของระบบ; เมื่อเซิร์ฟเวอร์ต้องการการตรวจสอบสิทธิ์แบบสองทาง (tls-auth-clients yes) กรุณาตั้งค่าใบรับรองไคลเอนต์และคีย์ส่วนตัวพร้อมกัน",
redisClientCertPairRequired: "ต้องกำหนดค่าใบรับรองไคลเอนต์และคีย์ส่วนตัวสำหรับ Redis TLS พร้อมกัน",
+ sshAgentKey: "คีย์ Agent",
+ sshAgentKeyAll: "identity ทั้งหมด (ลองตามลำดับ)",
+ sshAgentKeyHint: "เลือกคีย์ที่ได้รับอนุญาตสำหรับโฮสต์นี้ เซิร์ฟเวอร์จำกัดจำนวนครั้งในการยืนยันตัวตนต่อการเชื่อมต่อหนึ่งรายการ การลองคีย์ agent ทุกคีย์ทีละคีย์อาจทำให้จำนวนครั้งหมดก่อนที่จะถึงคีย์ที่ถูกต้อง",
+ sshAgentKeyLoadFailed: "ไม่สามารถอ่านรายการ identity ของ SSH agent: {error}",
+ sshAgentKeyRefresh: "รีเฟรช",
},
editor: {
duckdbDraining: "Query DuckDB ก่อนหน้ายังหยุดไม่เสร็จ โปรดลองอีกครั้งในไม่ช้า",
diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.ts
index 008efd0ab6..9971e3f325 100644
--- a/apps/desktop/src/i18n/locales/zh-CN.ts
+++ b/apps/desktop/src/i18n/locales/zh-CN.ts
@@ -1879,6 +1879,11 @@ export default withEnglishFallback({
sshUseAgent: "使用 ssh-agent",
sshAgentSockPath: "Agent Socket 路径",
sshAgentSockPathPlaceholder: "如 ~/.ssh/agent.sock",
+ sshAgentKey: "Agent 密钥",
+ sshAgentKeyAll: "全部 identity(按顺序尝试)",
+ sshAgentKeyHint: "选择该主机已授权的密钥。服务器会限制单个连接上的认证尝试次数,逐个尝试所有 agent 密钥可能在轮到正确的密钥前就把次数用完。",
+ sshAgentKeyLoadFailed: "无法读取 SSH agent 的身份列表:{error}",
+ sshAgentKeyRefresh: "刷新",
sshHostKeyVerifyTitle: "确认未知的 SSH 主机密钥",
sshHostKeyVerifyMessage: "无法确认主机 '{host}:{port}' 的真实性。为防止中间人攻击,请在继续前与服务器管理员核对主机密钥指纹。",
sshHostKeyVerifyKeyType: "密钥类型",
diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.ts
index a4775cea57..24c010202d 100644
--- a/apps/desktop/src/i18n/locales/zh-TW.ts
+++ b/apps/desktop/src/i18n/locales/zh-TW.ts
@@ -1863,6 +1863,11 @@ export default withEnglishFallback({
redisClientKeyBrowse: "選擇 Redis 用戶端私鑰",
redisTlsCertificateHint: "CA 憑證留空時,將使用系統信任存放區;若伺服器要求雙向驗證(tls-auth-clients yes),請同時設定用戶端憑證與私鑰。",
redisClientCertPairRequired: "Redis TLS 用戶端憑證與私鑰必須同時設定",
+ sshAgentKey: "Agent 金鑰",
+ sshAgentKeyAll: "全部 identity(依序嘗試)",
+ sshAgentKeyHint: "選擇該主機已授權的金鑰。伺服器會限制單一連線上的驗證嘗試次數,逐一嘗試所有 agent 金鑰可能在輪到正確的金鑰前就用盡次數。",
+ sshAgentKeyLoadFailed: "無法讀取 SSH agent 的身分列表:{error}",
+ sshAgentKeyRefresh: "重新整理",
},
editor: {
duckdbDraining: "上一筆 DuckDB 查詢仍在停止,請稍後重試。",
diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.ts
index 0f53ad06da..4a40c98273 100644
--- a/apps/desktop/src/lib/backend/api.ts
+++ b/apps/desktop/src/lib/backend/api.ts
@@ -87,6 +87,7 @@ export const loadConnections = forward("loadConnections");
export const loadTunnelProfiles = forward("loadTunnelProfiles");
export const saveTunnelProfiles = forward("saveTunnelProfiles");
export const testTunnelProfile = forward("testTunnelProfile");
+export const listSshAgentIdentities = forward("listSshAgentIdentities");
export const resolveSshPrompt = forward("resolveSshPrompt");
export const readKeychainPassword = forward("readKeychainPassword");
export const readKeychainPasswords = forward("readKeychainPasswords");
diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.ts
index e0595e6749..e537a076ee 100644
--- a/apps/desktop/src/lib/backend/http.ts
+++ b/apps/desktop/src/lib/backend/http.ts
@@ -79,6 +79,7 @@ import type {
SavedSqlLibrary,
SshConfigHostEntry,
LocalSshKey,
+ SshAgentIdentity,
TunnelProfile,
} from "@/types/database";
import type { DetachedTabHandoff } from "@/lib/app/detachedTabHandoff";
@@ -624,6 +625,10 @@ export async function testTunnelProfile(profile: TunnelProfile): Promise<string>
return post("/api/tunnel-profiles/test", profile);
}
+export async function listSshAgentIdentities(_sshAgentSockPath: string): Promise<SshAgentIdentity[]> {
+ return []; // The web backend cannot reach a local SSH agent socket
+}
+
export async function resolveSshPrompt(resolution: SshPromptResolution): Promise<void> {
await post("/api/ssh/prompts/resolve", resolution);
}
diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.ts
index 79ae6609b5..c07f6713a9 100644
--- a/apps/desktop/src/lib/backend/tauri.ts
+++ b/apps/desktop/src/lib/backend/tauri.ts
@@ -111,6 +111,7 @@ import type {
SavedSqlLibrary,
SshConfigHostEntry,
LocalSshKey,
+ SshAgentIdentity,
TunnelProfile,
TransactionLog,
ExternalSqlFileVersion,
@@ -2882,6 +2883,10 @@ export async function testTunnelProfile(profile: TunnelProfile): Promise<string>
return invoke("test_tunnel_profile", { profile });
}
+export async function listSshAgentIdentities(sshAgentSockPath: string): Promise<SshAgentIdentity[]> {
+ return invoke("list_ssh_agent_identities", { sshAgentSockPath });
+}
+
export async function resolveSshPrompt(resolution: SshPromptResolution): Promise<void> {
await invoke("resolve_ssh_prompt", { resolution });
}
diff --git a/apps/desktop/src/lib/connection/tunnelProfiles.ts b/apps/desktop/src/lib/connection/tunnelProfiles.ts
index 2912d0d29b..8d1b15b7ee 100644
--- a/apps/desktop/src/lib/connection/tunnelProfiles.ts
+++ b/apps/desktop/src/lib/connection/tunnelProfiles.ts
@@ -67,6 +67,7 @@ export function createTunnelProfile(type: TunnelProfileType): TunnelProfile {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: "",
+ ssh_agent_key_fingerprint: "",
auth_method: "password",
};
}
diff --git a/apps/desktop/src/lib/settings/settingsSearch.ts b/apps/desktop/src/lib/settings/settingsSearch.ts
index f5d1df5439..2e3a2bd102 100644
--- a/apps/desktop/src/lib/settings/settingsSearch.ts
+++ b/apps/desktop/src/lib/settings/settingsSearch.ts
@@ -555,6 +555,7 @@ export const SETTINGS_SEARCH_DEFINITIONS: readonly SettingsSearchDefinition[] =
"connection.sshKeyPath",
"connection.sshKeyPassphrase",
"connection.sshAgentSockPath",
+ "connection.sshAgentKey",
"connection.sshExposeLan",
"connection.sshConnectTimeout",
"connection.sshAuthMethodPassword",
diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.ts
index b7ae4ece15..c8f449a304 100644
--- a/apps/desktop/src/types/database.ts
+++ b/apps/desktop/src/types/database.ts
@@ -319,6 +319,11 @@ export interface SshTunnelConfig {
expose_lan?: boolean;
use_ssh_agent?: boolean;
ssh_agent_sock_path?: string;
+ /**
+ * SHA-256 fingerprint (`SHA256:...`) of the one SSH agent identity to use.
+ * Empty means every identity the agent reports is tried, in order.
+ */
+ ssh_agent_key_fingerprint?: string;
/**
* UI-facing choice of login method. Drives which credential inputs the
* connection dialog shows; the backend still probes "none" then falls
@@ -350,6 +355,12 @@ export interface SshTunnelConfig {
profile_id?: string;
}
+export interface SshAgentIdentity {
+ fingerprint: string;
+ algorithm: string;
+ comment: string;
+}
+
export interface SshConfigHostEntry {
alias: string;
host_name?: string;
diff --git a/crates/dbx-core/src/connection/connection_secrets.rs b/crates/dbx-core/src/connection/connection_secrets.rs
index 5a4b13dc00..9c12e42a1e 100644
--- a/crates/dbx-core/src/connection/connection_secrets.rs
+++ b/crates/dbx-core/src/connection/connection_secrets.rs
@@ -1185,6 +1185,7 @@ mod tests {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: "key".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
diff --git a/crates/dbx-core/src/connection/mod.rs b/crates/dbx-core/src/connection/mod.rs
index 2bc6fcf393..bc91f48c8b 100644
--- a/crates/dbx-core/src/connection/mod.rs
+++ b/crates/dbx-core/src/connection/mod.rs
@@ -3673,6 +3673,7 @@ impl AppState {
&leaf.key_passphrase,
leaf.use_ssh_agent,
&leaf.ssh_agent_sock_path,
+ &leaf.ssh_agent_key_fingerprint,
&leaf.auth_method,
timeout,
"127.0.0.1",
@@ -9121,6 +9122,7 @@ mod tests {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: "password".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
@@ -12033,6 +12035,7 @@ for line in sys.stdin:
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: String::new(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
diff --git a/crates/dbx-core/src/persistence/cloud_sync.rs b/crates/dbx-core/src/persistence/cloud_sync.rs
index 4b1bbf6edf..ea0e36f326 100644
--- a/crates/dbx-core/src/persistence/cloud_sync.rs
+++ b/crates/dbx-core/src/persistence/cloud_sync.rs
@@ -4142,6 +4142,7 @@ mod tests {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: "password".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
@@ -5829,6 +5830,7 @@ mod tests {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: "password".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
diff --git a/crates/dbx-core/src/persistence/storage.rs b/crates/dbx-core/src/persistence/storage.rs
index a745033272..7c55adb7ef 100644
--- a/crates/dbx-core/src/persistence/storage.rs
+++ b/crates/dbx-core/src/persistence/storage.rs
@@ -11716,6 +11716,7 @@ mod tests {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: "password".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
diff --git a/crates/dbx-driver-support/src/ssh_config.rs b/crates/dbx-driver-support/src/ssh_config.rs
index 49a8419be9..4ca0f1d52b 100644
--- a/crates/dbx-driver-support/src/ssh_config.rs
+++ b/crates/dbx-driver-support/src/ssh_config.rs
@@ -2,6 +2,7 @@ use std::collections::HashSet;
use std::path::{Path, PathBuf};
use glob::{glob_with, MatchOptions};
+use russh::keys::ssh_key::{HashAlg, PublicKey};
use serde::Serialize;
use crate::models::connection::SshTunnelConfig;
@@ -21,6 +22,12 @@ pub struct SshConfigHostEntry {
pub port: Option<u16>,
pub user: Option<String>,
pub identity_file: Option<String>,
+ /// Every `IdentityFile` for this entry, in config order. `identity_file`
+ /// keeps the last one for the one-key consumers that predate this list.
+ pub identity_files: Vec<String>,
+ /// `IdentitiesOnly yes`: the client may offer only these identities, so
+ /// the agent must not be asked for everything it holds.
+ pub identities_only: bool,
/// The `ProxyJump` alias, if any. Only a single hop is parsed (OpenSSH's
/// comma-separated multi-jump form is not supported); the jump itself
/// may declare its own `ProxyJump`, which `resolve_ssh_tunnel_chain`
@@ -39,6 +46,7 @@ pub fn list_hosts() -> Result<Vec<SshConfigHostEntry>, String> {
let base_dir = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(expand_tilde("~/.ssh")));
let mut loader = SshConfigLoader::new(base_dir);
loader.load_file(&path, 0, true)?;
+ loader.merge_match_entries();
Ok(loader.entries)
}
@@ -152,6 +160,14 @@ fn resolve_chain_from_entries(ssh: &SshTunnelConfig, entries: &[SshConfigHostEnt
/// entirely from `~/.ssh/config` (falling back to the leaf's own settings
/// for anything the config entry doesn't specify).
fn jump_hop_from_entry(leaf: &SshTunnelConfig, entry: SshConfigHostEntry) -> SshTunnelConfig {
+ // A jump host that pins its identities in `~/.ssh/config` uses those; one
+ // that doesn't keeps inheriting the leaf's selection, the way it already
+ // inherits the leaf's agent socket and auth method.
+ let ssh_agent_key_fingerprint = if entry.identities_only {
+ single_agent_fingerprint(&entry.identity_files).unwrap_or_default()
+ } else {
+ leaf.ssh_agent_key_fingerprint.clone()
+ };
SshTunnelConfig {
id: format!("{}::proxyjump::{}", leaf.id, entry.alias),
name: entry.alias.clone(),
@@ -166,6 +182,7 @@ fn jump_hop_from_entry(leaf: &SshTunnelConfig, entry: SshConfigHostEntry) -> Ssh
expose_lan: false,
use_ssh_agent: leaf.use_ssh_agent,
ssh_agent_sock_path: leaf.ssh_agent_sock_path.clone(),
+ ssh_agent_key_fingerprint,
auth_method: leaf.auth_method.clone(),
allow_exec_channel_proxy: leaf.allow_exec_channel_proxy,
proxy_command: entry.proxy_command.unwrap_or_default(),
@@ -194,6 +211,10 @@ fn apply_host_entry(ssh: &SshTunnelConfig, entry: SshConfigHostEntry) -> SshTunn
resolved.port = port;
}
}
+ // Computed before `entry` is consumed below: `IdentitiesOnly yes` pins the
+ // host to the listed identities.
+ let config_agent_fingerprint =
+ if entry.identities_only { single_agent_fingerprint(&entry.identity_files) } else { None };
if resolved.key_path.is_empty() {
if let Some(identity_file) = entry.identity_file {
resolved.key_path = identity_file;
@@ -205,6 +226,17 @@ fn apply_host_entry(ssh: &SshTunnelConfig, entry: SshConfigHostEntry) -> SshTunn
}
}
}
+ // Offering every identity of an agent exhausts a server's per-connection
+ // authentication attempts long before the matching key comes up, so when
+ // the config pins the identities and the layer authenticates through the
+ // agent, select that one key unless the user already picked another.
+ if resolved.ssh_agent_key_fingerprint.trim().is_empty()
+ && (resolved.use_ssh_agent || resolved.auth_method == "agent")
+ {
+ if let Some(fingerprint) = config_agent_fingerprint {
+ resolved.ssh_agent_key_fingerprint = fingerprint;
+ }
+ }
// A ProxyCommand typed into the connection form wins; otherwise inherit
// the one from the matched `~/.ssh/config` block.
if resolved.proxy_command.trim().is_empty() {
@@ -216,6 +248,31 @@ fn apply_host_entry(ssh: &SshTunnelConfig, entry: SshConfigHostEntry) -> SshTunn
resolved
}
+/// The fingerprint of the one key named by `identity_files`, read from the
+/// companion `.pub` files. `None` when no file can be read or the entries name
+/// more than one key: in that case the caller keeps the "offer everything"
+/// default rather than guessing.
+fn single_agent_fingerprint(identity_files: &[String]) -> Option<String> {
+ let mut fingerprints: Vec<String> =
+ identity_files.iter().filter_map(|path| identity_file_fingerprint(path)).collect();
+ fingerprints.sort();
+ fingerprints.dedup();
+ if fingerprints.len() == 1 {
+ fingerprints.pop()
+ } else {
+ None
+ }
+}
+
+fn identity_file_fingerprint(path: &str) -> Option<String> {
+ let expanded = expand_tilde(path);
+ let public_path =
+ if expanded.ends_with(".pub") { PathBuf::from(&expanded) } else { PathBuf::from(format!("{expanded}.pub")) };
+ let content = std::fs::read_to_string(public_path).ok()?;
+ let key = PublicKey::from_openssh(content.trim()).ok()?;
+ Some(key.fingerprint(HashAlg::Sha256).to_string())
+}
+
/// OpenSSH gives up after 16 nested `Include`s; mirror that so a config that
/// includes itself can never recurse without bound.
const MAX_INCLUDE_DEPTH: usize = 16;
@@ -227,6 +284,14 @@ const MAX_INCLUDE_DEPTH: usize = 16;
struct SshConfigLoader {
entries: Vec<SshConfigHostEntry>,
current_aliases: Vec<String>,
+ /// Entries collected from `Match Host` blocks. They are kept apart so a
+ /// `Match` block that precedes the real `Host` block cannot shadow it
+ /// (the loader resolves aliases first-match-wins), then folded in by
+ /// [`SshConfigLoader::merge_match_entries`].
+ match_entries: Vec<SshConfigHostEntry>,
+ /// Whether directives currently land in `match_entries` instead of
+ /// `entries`.
+ current_is_match: bool,
/// Canonical paths already parsed, so include cycles terminate.
visited: HashSet<PathBuf>,
/// Directory that relative `Include` patterns resolve against (`~/.ssh`).
@@ -235,7 +300,14 @@ struct SshConfigLoader {
impl SshConfigLoader {
fn new(base_dir: PathBuf) -> Self {
- Self { entries: Vec::new(), current_aliases: Vec::new(), visited: HashSet::new(), base_dir }
+ Self {
+ entries: Vec::new(),
+ current_aliases: Vec::new(),
+ match_entries: Vec::new(),
+ current_is_match: false,
+ visited: HashSet::new(),
+ base_dir,
+ }
}
/// Reads `path` and folds its directives into this loader's entries.
@@ -259,11 +331,14 @@ impl SshConfigLoader {
}
/// Parses a minimal subset of OpenSSH client config syntax: `Host`,
- /// `HostName`, `Port`, `User`, `IdentityFile`, `ProxyJump`, `Include`.
+ /// `Match Host`, `HostName`, `Port`, `User`, `IdentityFile`,
+ /// `IdentitiesOnly`, `ProxyJump`, `ProxyCommand`, `Include`.
/// Wildcard host patterns (containing `*` or `?`) are skipped since they
- /// aren't usable as a literal alias in the host field. `ProxyJump`'s
- /// comma-separated multi-hop form is read as a single alias (its first
- /// hop). Unknown directives are ignored.
+ /// aren't usable as a literal alias in the host field. `Match` blocks with
+ /// any criterion other than `Host` (`all`, `User`, `exec`, ...) cannot be
+ /// evaluated here and are ignored, as are unknown directives.
+ /// `ProxyJump`'s comma-separated multi-hop form is read as a single alias
+ /// (its first hop).
fn parse_lines(&mut self, content: &str, follow_includes: bool, depth: usize) -> Result<(), String> {
for raw_line in content.lines() {
let line = strip_comment(raw_line).trim();
@@ -291,17 +366,24 @@ impl SshConfigLoader {
.map(str::to_string)
.collect();
for alias in &aliases {
- self.entries.push(SshConfigHostEntry {
- alias: alias.clone(),
- host_name: None,
- port: None,
- user: None,
- identity_file: None,
- proxy_jump: None,
- proxy_command: None,
- });
+ self.entries.push(SshConfigHostEntry::new(alias));
}
self.current_aliases = aliases;
+ self.current_is_match = false;
+ }
+ // `Match Host a b` is the conditional twin of `Host`; its
+ // directives are collected separately and merged afterwards so
+ // an include that precedes the matching `Host` block (1Password
+ // writes `Match Host <alias>` + `IdentitiesOnly yes` +
+ // `IdentityFile` that way) cannot shadow that block.
+ "match" => {
+ self.current_aliases = match_host_aliases(value).unwrap_or_default();
+ for alias in &self.current_aliases {
+ if !self.match_entries.iter().any(|entry| &entry.alias == alias) {
+ self.match_entries.push(SshConfigHostEntry::new(alias));
+ }
+ }
+ self.current_is_match = true;
}
"hostname" => self.set_current_field(|entry| {
entry.host_name = Some(value.to_string());
@@ -318,7 +400,15 @@ impl SshConfigLoader {
}),
"identityfile" => self.set_current_field(|entry| {
entry.identity_file = Some(value.to_string());
+ entry.identity_files.push(value.to_string());
}),
+ "identitiesonly" => {
+ if let Some(identities_only) = parse_yes_no(value) {
+ self.set_current_field(move |entry| {
+ entry.identities_only = identities_only;
+ });
+ }
+ }
"proxycommand" => self.set_current_field(|entry| {
entry.proxy_command = Some(value.to_string());
}),
@@ -365,12 +455,80 @@ impl SshConfigLoader {
fn set_current_field(&mut self, apply: impl Fn(&mut SshConfigHostEntry)) {
let aliases = self.current_aliases.as_slice();
- for entry in self.entries.iter_mut() {
+ let entries = if self.current_is_match { &mut self.match_entries } else { &mut self.entries };
+ for entry in entries.iter_mut() {
if aliases.contains(&entry.alias) {
apply(entry);
}
}
}
+
+ /// Folds `Match Host` blocks into the real entries. Values from the
+ /// conditional block only fill fields the `Host` block left unset, so a
+ /// `Match` that precedes its `Host` (the 1Password layout) enriches it
+ /// instead of replacing its `HostName`/`Port`/`User`.
+ fn merge_match_entries(&mut self) {
+ for condition in std::mem::take(&mut self.match_entries) {
+ match self.entries.iter_mut().find(|entry| entry.alias == condition.alias) {
+ Some(entry) => {
+ entry.host_name = entry.host_name.take().or(condition.host_name);
+ entry.port = entry.port.or(condition.port);
+ entry.user = entry.user.take().or(condition.user);
+ entry.proxy_command = entry.proxy_command.take().or(condition.proxy_command);
+ entry.proxy_jump = entry.proxy_jump.take().or(condition.proxy_jump);
+ entry.identities_only |= condition.identities_only;
+ for identity_file in condition.identity_files {
+ if !entry.identity_files.contains(&identity_file) {
+ entry.identity_files.push(identity_file);
+ }
+ }
+ if entry.identity_file.is_none() {
+ entry.identity_file = condition.identity_file;
+ }
+ }
+ None => self.entries.push(condition),
+ }
+ }
+ }
+}
+
+impl SshConfigHostEntry {
+ fn new(alias: &str) -> Self {
+ Self {
+ alias: alias.to_string(),
+ host_name: None,
+ port: None,
+ user: None,
+ identity_file: None,
+ identity_files: Vec::new(),
+ identities_only: false,
+ proxy_jump: None,
+ proxy_command: None,
+ }
+ }
+}
+
+/// Returns the aliases a `Match` line applies to, or `None` when the block
+/// uses a criterion that cannot be evaluated statically (`all`, `User`,
+/// `exec`, ...) or names only wildcard hosts.
+fn match_host_aliases(value: &str) -> Option<Vec<String>> {
+ let mut tokens = value.split_whitespace();
+ if !tokens.next()?.eq_ignore_ascii_case("host") {
+ return None;
+ }
+ let aliases: Vec<String> =
+ tokens.filter(|alias| !alias.contains('*') && !alias.contains('?')).map(str::to_string).collect();
+ (!aliases.is_empty()).then_some(aliases)
+}
+
+fn parse_yes_no(value: &str) -> Option<bool> {
+ if value.eq_ignore_ascii_case("yes") {
+ Some(true)
+ } else if value.eq_ignore_ascii_case("no") {
+ Some(false)
+ } else {
+ None
+ }
}
/// Parses config text that stands on its own (tests, snippets): `Include` is
@@ -379,6 +537,7 @@ impl SshConfigLoader {
fn parse_ssh_config(content: &str) -> Vec<SshConfigHostEntry> {
let mut loader = SshConfigLoader::new(PathBuf::new());
let _ = loader.parse_lines(content, false, 0);
+ loader.merge_match_entries();
loader.entries
}
@@ -422,6 +581,7 @@ mod tests {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: String::new(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
@@ -523,6 +683,8 @@ mod tests {
port: Some(2222),
user: Some("deploy".to_string()),
identity_file: Some("~/.ssh/id_ed25519".to_string()),
+ identity_files: vec!["~/.ssh/id_ed25519".to_string()],
+ identities_only: false,
proxy_jump: None,
proxy_command: None,
}
@@ -664,6 +826,8 @@ mod tests {
port: None,
user: None,
identity_file: None,
+ identity_files: Vec::new(),
+ identities_only: false,
proxy_jump: proxy_jump.map(str::to_string),
proxy_command: None,
}
@@ -734,6 +898,124 @@ mod tests {
assert!(chain.len() <= entries.len());
assert_eq!(chain.last().unwrap().host, "1.1.1.1");
}
+
+ #[test]
+ fn jump_hop_inherits_the_leaf_agent_key_without_identities_only() {
+ let mut leaf = config("target");
+ leaf.ssh_agent_key_fingerprint = "SHA256:leaf".to_string();
+
+ let hop = jump_hop_from_entry(&leaf, jump_entry("gateway", "1.1.1.1", None));
+
+ assert_eq!(hop.ssh_agent_key_fingerprint, "SHA256:leaf");
+ }
+
+ #[test]
+ fn jump_hop_uses_its_own_identities_only_key() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let public_path = dir.path().join("jump.pub");
+ std::fs::write(
+ &public_path,
+ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIDjAWVPHn2gq7JpSrD5jpUBnnOMn4hB9ieE0UcpM654 fixture-one\n",
+ )
+ .unwrap();
+ let mut leaf = config("target");
+ leaf.ssh_agent_key_fingerprint = "SHA256:leaf".to_string();
+ let mut gateway = jump_entry("gateway", "1.1.1.1", None);
+ gateway.identity_files = vec![public_path.to_string_lossy().into_owned()];
+ gateway.identities_only = true;
+
+ let hop = jump_hop_from_entry(&leaf, gateway);
+
+ assert_eq!(hop.ssh_agent_key_fingerprint, "SHA256:6Dkiwer56XB8PoBi8F2PZ7loWKttQNnE8wBhPB34Bd0");
+ }
+
+ #[test]
+ fn match_host_block_enriches_the_host_block_that_follows_it() {
+ let entries = parse_ssh_config(
+ "Match Host chanel\n IdentitiesOnly yes\n IdentityFile ~/.ssh/1Password/key.pub\n\
+ Host chanel\n HostName 36.133.78.129\n Port 19022\n User root\n",
+ );
+
+ assert_eq!(entries.len(), 1);
+ assert_eq!(entries[0].alias, "chanel");
+ assert_eq!(entries[0].host_name.as_deref(), Some("36.133.78.129"));
+ assert_eq!(entries[0].port, Some(19022));
+ assert_eq!(entries[0].user.as_deref(), Some("root"));
+ assert!(entries[0].identities_only);
+ assert_eq!(entries[0].identity_files, vec!["~/.ssh/1Password/key.pub"]);
+ }
+
+ #[test]
+ fn match_block_criteria_that_cannot_be_evaluated_are_ignored() {
+ let entries = parse_ssh_config(
+ "Match all\n IdentitiesOnly yes\nHost direct\n HostName 10.0.0.1\n\
+ Match User deploy\n IdentityFile ~/.ssh/deploy\n",
+ );
+
+ assert_eq!(entries.len(), 1);
+ assert!(!entries[0].identities_only);
+ assert!(entries[0].identity_files.is_empty());
+ }
+
+ #[test]
+ fn match_host_without_a_host_block_still_resolves() {
+ let entries = parse_ssh_config("Match Host solo\n IdentitiesOnly yes\n IdentityFile ~/.ssh/solo.pub\n");
+
+ assert_eq!(entries.len(), 1);
+ assert!(entries[0].identities_only);
+ assert_eq!(entries[0].identity_files, vec!["~/.ssh/solo.pub"]);
+ }
+
+ #[test]
+ fn identities_only_fills_the_agent_key_from_the_public_file() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let public_path = dir.path().join("agent.pub");
+ std::fs::write(
+ &public_path,
+ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIDjAWVPHn2gq7JpSrD5jpUBnnOMn4hB9ieE0UcpM654 fixture-one\n",
+ )
+ .unwrap();
+
+ let mut ssh = config("chanel");
+ ssh.auth_method = "agent".to_string();
+ ssh.use_ssh_agent = true;
+ let mut host = entry("chanel");
+ host.identity_file = Some(public_path.to_string_lossy().into_owned());
+ host.identity_files = vec![public_path.to_string_lossy().into_owned()];
+ host.identities_only = true;
+
+ let resolved = apply_host_entry(&ssh, host);
+
+ assert_eq!(resolved.ssh_agent_key_fingerprint, "SHA256:6Dkiwer56XB8PoBi8F2PZ7loWKttQNnE8wBhPB34Bd0");
+ }
+
+ #[test]
+ fn identities_only_with_several_keys_or_an_explicit_selection_is_not_guessed() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let first = dir.path().join("first.pub");
+ let second = dir.path().join("second.pub");
+ std::fs::write(
+ &first,
+ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIDjAWVPHn2gq7JpSrD5jpUBnnOMn4hB9ieE0UcpM654 fixture-one\n",
+ )
+ .unwrap();
+ std::fs::write(
+ &second,
+ "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIISjubSpkMgLWOaYIdP6TfTeRoFA6M1ojv6vyqunJpUb fixture-two\n",
+ )
+ .unwrap();
+
+ let mut ssh = config("chanel");
+ ssh.auth_method = "agent".to_string();
+ let mut host = entry("chanel");
+ host.identity_files = vec![first.to_string_lossy().into_owned(), second.to_string_lossy().into_owned()];
+ host.identities_only = true;
+ assert_eq!(apply_host_entry(&ssh, host.clone()).ssh_agent_key_fingerprint, "");
+
+ ssh.ssh_agent_key_fingerprint = "SHA256:explicit".to_string();
+ host.identity_files = vec![first.to_string_lossy().into_owned()];
+ assert_eq!(apply_host_entry(&ssh, host).ssh_agent_key_fingerprint, "SHA256:explicit");
+ }
}
#[cfg(test)]
@@ -756,6 +1038,7 @@ mod include_tests {
fn hosts_from(path: &Path, base_dir: &Path) -> Vec<SshConfigHostEntry> {
let mut loader = SshConfigLoader::new(base_dir.to_path_buf());
loader.load_file(path, 0, true).expect("load config");
+ loader.merge_match_entries();
loader.entries
}
@@ -792,6 +1075,32 @@ mod include_tests {
assert_eq!(abc.proxy_jump, None);
}
+ #[test]
+ fn included_match_host_block_applies_to_a_host_block_declared_after_it() {
+ // The layout 1Password writes: the generated include is pulled in at
+ // the top of ~/.ssh/config, so its `Match Host` block is parsed before
+ // the user's own `Host` block for the same alias.
+ let dir = TempDir::new().unwrap();
+ let main = write_config(
+ dir.path(),
+ "config",
+ "Include 1Password/config\nHost chanel\n HostName 36.133.78.129\n Port 19022\n User root\n",
+ );
+ write_config(
+ dir.path(),
+ "1Password/config",
+ "Match Host chanel\n IdentitiesOnly yes\n IdentityFile ~/.ssh/1Password/SHA256_key.pub\n",
+ );
+
+ let entries = hosts_from(&main, dir.path());
+
+ assert_eq!(aliases(&entries), vec!["chanel"]);
+ assert_eq!(entries[0].host_name.as_deref(), Some("36.133.78.129"));
+ assert_eq!(entries[0].port, Some(19022));
+ assert!(entries[0].identities_only);
+ assert_eq!(entries[0].identity_files, vec!["~/.ssh/1Password/SHA256_key.pub"]);
+ }
+
#[test]
fn include_accepts_absolute_paths_and_multiple_patterns_on_one_line() {
let dir = TempDir::new().unwrap();
diff --git a/crates/dbx-drivers/src/db/sqlite_worker.rs b/crates/dbx-drivers/src/db/sqlite_worker.rs
index 2fdd9ca71c..8da6955e96 100644
--- a/crates/dbx-drivers/src/db/sqlite_worker.rs
+++ b/crates/dbx-drivers/src/db/sqlite_worker.rs
@@ -565,6 +565,7 @@ async fn open_final_hop_session(
&final_ssh.key_passphrase,
final_ssh.use_ssh_agent,
&final_ssh.ssh_agent_sock_path,
+ &final_ssh.ssh_agent_key_fingerprint,
&final_ssh.auth_method,
ssh_tunnel::effective_hop_timeout(final_ssh),
tunnels.known_hosts_path(),
@@ -601,6 +602,7 @@ async fn open_final_hop_session(
&final_ssh.key_passphrase,
final_ssh.use_ssh_agent,
&final_ssh.ssh_agent_sock_path,
+ &final_ssh.ssh_agent_key_fingerprint,
&final_ssh.auth_method,
ssh_tunnel::effective_hop_timeout(final_ssh),
tunnels.known_hosts_path(),
diff --git a/crates/dbx-drivers/src/db/ssh_tunnel.rs b/crates/dbx-drivers/src/db/ssh_tunnel.rs
index ed5b16c971..6ec618606b 100644
--- a/crates/dbx-drivers/src/db/ssh_tunnel.rs
+++ b/crates/dbx-drivers/src/db/ssh_tunnel.rs
@@ -45,6 +45,10 @@ 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);
+/// Minimum budget for ssh-agent authentication. A local agent (1Password,
+/// Secretive, ...) can hold a sign request until the user approves it in a
+/// dialog or with Touch ID, which takes far longer than a TCP handshake.
+const SSH_AGENT_AUTH_TIMEOUT_SECS: u64 = 60;
/// SSH client handler. Holds a host-key verifier so that
/// [`client::Handler::check_server_key`] can reject untrusted/changed server
@@ -408,6 +412,7 @@ pub async fn connect_and_authenticate(
ssh_key_passphrase: &str,
use_ssh_agent: bool,
ssh_agent_sock_path: &str,
+ ssh_agent_key_fingerprint: &str,
auth_method: &str,
connect_timeout_secs: u64,
known_hosts_path: &Path,
@@ -668,7 +673,15 @@ pub async fn connect_and_authenticate(
));
}
} else if try_agent {
- match try_authenticate_with_agent(&mut session, ssh_user, ssh_agent_sock_path, &connect_timeout).await {
+ match try_authenticate_with_agent(
+ &mut session,
+ ssh_user,
+ ssh_agent_sock_path,
+ ssh_agent_key_fingerprint,
+ &connect_timeout,
+ )
+ .await
+ {
Ok(AgentAuthenticationOutcome::Success) => {}
Ok(AgentAuthenticationOutcome::KeyboardInteractiveRequired) => {
authenticate_keyboard_interactive(
@@ -746,6 +759,200 @@ fn resolve_ssh_agent_socket_path(path: &str) -> String {
expand_tilde(path)
}
+#[derive(Debug, Clone, serde::Serialize)]
+pub struct AgentIdentityInfo {
+ pub fingerprint: String,
+ pub algorithm: String,
+ pub comment: String,
+}
+
+impl AgentIdentityInfo {
+ fn from_identity(identity: &AgentIdentity) -> Self {
+ let public_key = identity.public_key();
+ Self {
+ fingerprint: public_key.fingerprint(HashAlg::Sha256).to_string(),
+ algorithm: public_key.algorithm().as_str().to_string(),
+ comment: identity.comment().to_string(),
+ }
+ }
+}
+
+fn agent_identity_fingerprint(identity: &AgentIdentity) -> String {
+ identity.public_key().fingerprint(HashAlg::Sha256).to_string()
+}
+
+/// Normalizes the fingerprint forms users paste: `SHA256:abc...`,
+/// `SHA256_abc...` (1Password's .pub filename form), any letter case,
+/// surrounding whitespace.
+fn normalize_ssh_fingerprint(value: &str) -> String {
+ let trimmed = value.trim();
+ let has_prefix = trimmed
+ .get(..7)
+ .is_some_and(|prefix| prefix.eq_ignore_ascii_case("SHA256:") || prefix.eq_ignore_ascii_case("SHA256_"));
+ if !has_prefix {
+ return trimmed.to_string();
+ }
+ format!("SHA256:{}", trimmed[7..].trim_end_matches('=').to_uppercase())
+}
+
+/// Keeps only the identity whose fingerprint the user selected. An empty
+/// fingerprint keeps every identity, in the order the agent reported them.
+fn select_agent_identities(
+ identities: Vec<AgentIdentity>,
+ ssh_agent_key_fingerprint: &str,
+) -> Result<Vec<AgentIdentity>, String> {
+ if ssh_agent_key_fingerprint.trim().is_empty() {
+ return Ok(identities);
+ }
+
+ let wanted = normalize_ssh_fingerprint(ssh_agent_key_fingerprint);
+ let available: Vec<(String, String)> = identities
+ .iter()
+ .map(|identity| (identity.comment().to_string(), agent_identity_fingerprint(identity)))
+ .collect();
+ let selected: Vec<AgentIdentity> = identities
+ .into_iter()
+ .filter(|identity| normalize_ssh_fingerprint(&agent_identity_fingerprint(identity)) == wanted)
+ .collect();
+ if !selected.is_empty() {
+ return Ok(selected);
+ }
+
+ let available = available
+ .iter()
+ .take(10)
+ .map(
+ |(comment, fingerprint)| {
+ if comment.trim().is_empty() {
+ fingerprint.clone()
+ } else {
+ format!("{comment} ({fingerprint})")
+ }
+ },
+ )
+ .collect::<Vec<_>>()
+ .join(", ");
+ Err(format!(
+ "No ssh-agent identity matches the selected fingerprint {}. The agent reported: {available}. Select the key again in the tunnel profile's SSH settings.",
+ ssh_agent_key_fingerprint.trim()
+ ))
+}
+
+/// Lists the identities an agent exposes without asking it to sign anything,
+/// so no confirmation dialog is triggered.
+pub async fn list_agent_identities(ssh_agent_sock_path: &str) -> Result<Vec<AgentIdentityInfo>, String> {
+ #[cfg(unix)]
+ {
+ let mut agent = connect_unix_agent(ssh_agent_sock_path).await?;
+ list_identities_from_client(&mut agent).await
+ }
+
+ #[cfg(windows)]
+ {
+ let mut failures = Vec::new();
+ for endpoint in windows_ssh_agent_endpoints(ssh_agent_sock_path) {
+ let label = endpoint.label();
+ let identities = match endpoint {
+ WindowsSshAgentEndpoint::NamedPipe(path) => match AgentClient::connect_named_pipe(&path).await {
+ Ok(mut agent) => list_identities_from_client(&mut agent).await,
+ Err(error) => Err(format!("{label} is unavailable: {error}")),
+ },
+ WindowsSshAgentEndpoint::Pageant => match AgentClient::connect_pageant().await {
+ Ok(mut agent) => list_identities_from_client(&mut agent).await,
+ Err(error) => Err(format!("{label} is unavailable: {error}")),
+ },
+ };
+
+ match identities {
+ Ok(identities) => return Ok(identities),
+ Err(error) => failures.push(error),
+ }
+ }
+
+ Err(format!("No configured Windows ssh-agent transport could list identities: {}", failures.join("; ")))
+ }
+}
+
+#[cfg(unix)]
+async fn connect_unix_agent(ssh_agent_sock_path: &str) -> Result<AgentClient<tokio::net::UnixStream>, String> {
+ if ssh_agent_sock_path.is_empty() {
+ AgentClient::connect_env().await.map_err(|e| format!("ssh-agent is unavailable: {e}"))
+ } else {
+ let resolved_path = resolve_ssh_agent_socket_path(ssh_agent_sock_path);
+ AgentClient::connect_uds(&resolved_path)
+ .await
+ .map_err(|e| format!("ssh-agent at '{resolved_path}' is unavailable: {e}"))
+ }
+}
+
+async fn list_identities_from_client<S>(agent: &mut AgentClient<S>) -> Result<Vec<AgentIdentityInfo>, String>
+where
+ S: AgentStream + Send + Unpin,
+{
+ let identities = agent.request_identities().await.map_err(|e| format!("ssh-agent request failed: {e}"))?;
+ Ok(identities.iter().map(AgentIdentityInfo::from_identity).collect())
+}
+
+/// What one public-key probe through an agent identity tells us about what to
+/// do next.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum AgentAttempt {
+ Success,
+ KeyboardInteractiveRequired,
+ Continue,
+ /// The server answered with an empty remaining-methods list: it will accept
+ /// no further attempt on this connection (OpenSSH `MaxAuthTries`).
+ ServerClosedAuthentication,
+ /// The SSH session is gone; retrying the remaining identities cannot work.
+ ConnectionLost,
+}
+
+fn classify_agent_attempt(result: &Result<AuthResult, russh::AgentAuthError>) -> AgentAttempt {
+ match result {
+ Ok(AuthResult::Success) => AgentAttempt::Success,
+ Ok(AuthResult::Failure { remaining_methods, .. }) => {
+ if server_offers_keyboard_interactive(remaining_methods) {
+ AgentAttempt::KeyboardInteractiveRequired
+ } else if remaining_methods.is_empty() {
+ AgentAttempt::ServerClosedAuthentication
+ } else {
+ AgentAttempt::Continue
+ }
+ }
+ Err(russh::AgentAuthError::Send(_)) => AgentAttempt::ConnectionLost,
+ Err(russh::AgentAuthError::Key(_)) => AgentAttempt::Continue,
+ }
+}
+
+fn describe_agent_attempt_failure(result: &Result<AuthResult, russh::AgentAuthError>) -> String {
+ match result {
+ Ok(AuthResult::Failure { remaining_methods, .. }) => {
+ format!("the server rejected the key (remaining methods: {remaining_methods:?})")
+ }
+ Ok(_) => "the server rejected the key".to_string(),
+ Err(error) => error.to_string(),
+ }
+}
+
+fn agent_attempts_stopped_error(
+ attempted: usize,
+ total: usize,
+ ssh_agent_key_fingerprint: &str,
+ server_closed: bool,
+) -> String {
+ let cause = if server_closed { "the server closed authentication" } else { "the SSH session was lost" };
+ if ssh_agent_key_fingerprint.trim().is_empty() {
+ format!(
+ "SSH agent authentication stopped: {cause} after attempting {attempted} of the {total} agent identities. Select the matching agent key so DBX offers only that identity; servers limit authentication attempts per connection."
+ )
+ } else {
+ format!(
+ "SSH agent authentication stopped: {cause} after attempting {attempted} of the {total} agent identities, before the selected key ({}) was accepted. Check the selected fingerprint.",
+ ssh_agent_key_fingerprint.trim()
+ )
+ }
+}
+
/// 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.
@@ -753,31 +960,16 @@ async fn try_authenticate_with_agent(
session: &mut Handle<SshClient>,
ssh_user: &str,
ssh_agent_sock_path: &str,
+ ssh_agent_key_fingerprint: &str,
connect_timeout: &Duration,
) -> Result<AgentAuthenticationOutcome, String> {
#[cfg(unix)]
- let agent = if ssh_agent_sock_path.is_empty() {
- match AgentClient::connect_env().await {
- Ok(a) => a,
- Err(e) => {
- return Err(format!("No SSH password or key provided, and ssh-agent is unavailable: {e}"));
- }
- }
- } else {
- let resolved_path = resolve_ssh_agent_socket_path(ssh_agent_sock_path);
- match AgentClient::connect_uds(&resolved_path).await {
- Ok(a) => a,
- Err(e) => {
- return Err(format!(
- "No SSH password or key provided, and ssh-agent at '{}' is unavailable: {e}",
- resolved_path
- ));
- }
- }
- };
-
- #[cfg(unix)]
- return authenticate_with_agent_client(session, ssh_user, agent, connect_timeout).await;
+ {
+ let agent = connect_unix_agent(ssh_agent_sock_path)
+ .await
+ .map_err(|error| format!("No SSH password or key provided, and {error}"))?;
+ authenticate_with_agent_client(session, ssh_user, agent, ssh_agent_key_fingerprint, connect_timeout).await
+ }
#[cfg(windows)]
{
@@ -792,18 +984,30 @@ async fn try_authenticate_with_agent(
let outcome = match endpoint {
WindowsSshAgentEndpoint::NamedPipe(path) => {
match tokio::time::timeout(*connect_timeout, AgentClient::connect_named_pipe(&path)).await {
- Ok(Ok(agent)) => authenticate_with_agent_client(session, ssh_user, agent, connect_timeout)
- .await
- .map_err(|error| format!("{label}: {error}")),
+ Ok(Ok(agent)) => authenticate_with_agent_client(
+ session,
+ ssh_user,
+ agent,
+ ssh_agent_key_fingerprint,
+ connect_timeout,
+ )
+ .await
+ .map_err(|error| format!("{label}: {error}")),
Ok(Err(error)) => Err(format!("{label} is unavailable: {error}")),
Err(_) => Err(format!("{label} connection timed out")),
}
}
WindowsSshAgentEndpoint::Pageant => {
match tokio::time::timeout(*connect_timeout, AgentClient::connect_pageant()).await {
- Ok(Ok(agent)) => authenticate_with_agent_client(session, ssh_user, agent, connect_timeout)
- .await
- .map_err(|error| format!("{label}: {error}")),
+ Ok(Ok(agent)) => authenticate_with_agent_client(
+ session,
+ ssh_user,
+ agent,
+ ssh_agent_key_fingerprint,
+ connect_timeout,
+ )
+ .await
+ .map_err(|error| format!("{label}: {error}")),
Ok(Err(error)) => Err(format!("{label} is unavailable: {error}")),
Err(_) => Err(format!("{label} connection timed out")),
}
@@ -827,6 +1031,7 @@ async fn authenticate_with_agent_client<S>(
session: &mut Handle<SshClient>,
ssh_user: &str,
mut agent: AgentClient<S>,
+ ssh_agent_key_fingerprint: &str,
connect_timeout: &Duration,
) -> Result<AgentAuthenticationOutcome, String>
where
@@ -841,12 +1046,21 @@ where
return Err(format!("No SSH password or key provided, and ssh-agent request failed: {e}"));
}
};
+ let total_reported = identities.len();
+ let identities = select_agent_identities(identities, ssh_agent_key_fingerprint)?;
let hash_alg = session.best_supported_rsa_hash().await.ok().flatten().flatten();
-
- let auth_result = tokio::time::timeout(*connect_timeout, async {
- for identity in identities {
- let result = match &identity {
+ // An agent may hold the sign request until the user approves it, so the
+ // network-oriented connect budget is only a lower bound here.
+ let agent_auth_timeout = (*connect_timeout).max(Duration::from_secs(SSH_AGENT_AUTH_TIMEOUT_SECS));
+ let total = identities.len();
+ let mut attempted = 0usize;
+
+ let auth_result = tokio::time::timeout(agent_auth_timeout, async {
+ for identity in &identities {
+ let comment = identity.comment();
+ let fingerprint = agent_identity_fingerprint(identity);
+ let result = match identity {
AgentIdentity::PublicKey { key, .. } => {
session.authenticate_publickey_with(ssh_user, key.clone(), hash_alg, &mut agent).await
}
@@ -854,27 +1068,54 @@ where
session.authenticate_certificate_with(ssh_user, certificate.clone(), hash_alg, &mut agent).await
}
};
+ attempted += 1;
- match result {
- Ok(auth_res) if auth_res.success() => return Ok(AgentAuthenticationOutcome::Success),
- Ok(auth_res) if auth_result_offers_keyboard_interactive(&auth_res) => {
+ match classify_agent_attempt(&result) {
+ AgentAttempt::Success => return Ok(AgentAuthenticationOutcome::Success),
+ AgentAttempt::KeyboardInteractiveRequired => {
return Ok(AgentAuthenticationOutcome::KeyboardInteractiveRequired)
}
- Ok(_) => continue,
- Err(e) => {
- log::debug!("SSH agent identity ({}) auth failed: {e}", identity.comment());
- continue;
+ AgentAttempt::Continue => {
+ // Debug, not warn: offering every identity of an agent is
+ // the normal path, so a rejection here is expected traffic
+ // for a working setup and would spam the log on every
+ // connect.
+ log::debug!(
+ "SSH agent identity ({comment}, {fingerprint}) auth failed: {}",
+ describe_agent_attempt_failure(&result)
+ );
+ }
+ AgentAttempt::ServerClosedAuthentication => {
+ return Err(agent_attempts_stopped_error(
+ attempted,
+ total_reported,
+ ssh_agent_key_fingerprint,
+ true,
+ ))
+ }
+ AgentAttempt::ConnectionLost => {
+ return Err(agent_attempts_stopped_error(
+ attempted,
+ total_reported,
+ ssh_agent_key_fingerprint,
+ false,
+ ))
}
}
}
- Err("No SSH password or key provided, and no ssh-agent identity was accepted".to_string())
+ Err(format!(
+ "No SSH password or key provided, and no ssh-agent identity was accepted ({attempted} of {total} identities tried)"
+ ))
})
.await;
match auth_result {
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()),
+ Err(_) => Err(format!(
+ "SSH agent authentication timed out after {}s; approve the agent prompt and retry",
+ agent_auth_timeout.as_secs()
+ )),
}
}
@@ -1262,6 +1503,7 @@ async fn tunnel_reconnect_loop(
ssh_key_passphrase: String,
use_ssh_agent: bool,
ssh_agent_sock_path: String,
+ ssh_agent_key_fingerprint: String,
auth_method: String,
connect_timeout_secs: u64,
known_hosts_path: PathBuf,
@@ -1307,6 +1549,7 @@ async fn tunnel_reconnect_loop(
&ssh_key_passphrase,
use_ssh_agent,
&ssh_agent_sock_path,
+ &ssh_agent_key_fingerprint,
&auth_method,
connect_timeout_secs,
&known_hosts_path,
@@ -1487,6 +1730,7 @@ impl TunnelManager {
ssh_key_passphrase: &str,
use_ssh_agent: bool,
ssh_agent_sock_path: &str,
+ ssh_agent_key_fingerprint: &str,
auth_method: &str,
connect_timeout_secs: u64,
remote_host: &str,
@@ -1507,6 +1751,7 @@ impl TunnelManager {
ssh_key_passphrase,
use_ssh_agent,
ssh_agent_sock_path,
+ ssh_agent_key_fingerprint,
auth_method,
connect_timeout_secs,
remote_host,
@@ -1533,6 +1778,7 @@ impl TunnelManager {
ssh_key_passphrase: &str,
use_ssh_agent: bool,
ssh_agent_sock_path: &str,
+ ssh_agent_key_fingerprint: &str,
auth_method: &str,
connect_timeout_secs: u64,
remote_host: &str,
@@ -1579,6 +1825,7 @@ impl TunnelManager {
ssh_key_passphrase,
use_ssh_agent,
ssh_agent_sock_path,
+ ssh_agent_key_fingerprint,
auth_method,
connect_timeout_secs,
&self.known_hosts_path,
@@ -1612,6 +1859,7 @@ impl TunnelManager {
ssh_key_passphrase: &str,
use_ssh_agent: bool,
ssh_agent_sock_path: &str,
+ ssh_agent_key_fingerprint: &str,
auth_method: &str,
connect_timeout_secs: u64,
allow_exec_channel_proxy: bool,
@@ -1649,6 +1897,7 @@ impl TunnelManager {
ssh_key_passphrase,
use_ssh_agent,
ssh_agent_sock_path,
+ ssh_agent_key_fingerprint,
auth_method,
connect_timeout_secs,
&self.known_hosts_path,
@@ -1759,6 +2008,7 @@ impl TunnelManager {
&hop.key_passphrase,
hop.use_ssh_agent,
&hop.ssh_agent_sock_path,
+ &hop.ssh_agent_key_fingerprint,
&hop.auth_method,
effective_hop_timeout(hop),
&self.known_hosts_path,
@@ -1858,6 +2108,7 @@ async fn spawn_tunnel(
ssh_key_passphrase: &str,
use_ssh_agent: bool,
ssh_agent_sock_path: &str,
+ ssh_agent_key_fingerprint: &str,
auth_method: &str,
connect_timeout_secs: u64,
known_hosts_path: &Path,
@@ -1879,6 +2130,7 @@ async fn spawn_tunnel(
ssh_key_passphrase,
use_ssh_agent,
ssh_agent_sock_path,
+ ssh_agent_key_fingerprint,
auth_method,
connect_timeout_secs,
known_hosts_path,
@@ -1903,6 +2155,7 @@ async fn spawn_socks5_proxy(
ssh_key_passphrase: &str,
use_ssh_agent: bool,
ssh_agent_sock_path: &str,
+ ssh_agent_key_fingerprint: &str,
auth_method: &str,
connect_timeout_secs: u64,
known_hosts_path: &Path,
@@ -1920,6 +2173,7 @@ async fn spawn_socks5_proxy(
ssh_key_passphrase,
use_ssh_agent,
ssh_agent_sock_path,
+ ssh_agent_key_fingerprint,
auth_method,
connect_timeout_secs,
known_hosts_path,
@@ -1944,6 +2198,7 @@ async fn spawn_tunnel_target(
ssh_key_passphrase: &str,
use_ssh_agent: bool,
ssh_agent_sock_path: &str,
+ ssh_agent_key_fingerprint: &str,
auth_method: &str,
connect_timeout_secs: u64,
known_hosts_path: &Path,
@@ -1967,6 +2222,7 @@ async fn spawn_tunnel_target(
ssh_key_passphrase,
use_ssh_agent,
ssh_agent_sock_path,
+ ssh_agent_key_fingerprint,
auth_method,
connect_timeout_secs,
known_hosts_path,
@@ -1987,6 +2243,7 @@ async fn spawn_tunnel_target(
ssh_key_passphrase.to_string(),
use_ssh_agent,
ssh_agent_sock_path.to_string(),
+ ssh_agent_key_fingerprint.to_string(),
auth_method.to_string(),
connect_timeout_secs,
known_hosts_path.to_path_buf(),
@@ -2076,17 +2333,18 @@ mod tests {
use super::resolve_ssh_agent_socket_path;
use super::SshClient;
use super::{
- bind_tunnel_listener, connect_and_authenticate, describe_terminal_auth_failure, 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, tofu_prompt_deadline, HostKeyState, HostKeyVerifier, PlannedTunnel, TunnelEntry, TunnelKind,
- TunnelManager, TunnelStatus, TOFU_PROMPT_TIMEOUT,
+ agent_attempts_stopped_error, bind_tunnel_listener, classify_agent_attempt, connect_and_authenticate,
+ describe_terminal_auth_failure, effective_hop_timeout, netcat_proxy_command, normalize_ssh_fingerprint,
+ openssh_padding_len, plan_chain, read_ssh_string, sanitize_unencrypted_openssh_comment_bytes,
+ server_offers_keyboard_interactive, server_offers_password, ssh_client_config, tofu_prompt_deadline,
+ AgentAttempt, HostKeyState, HostKeyVerifier, PlannedTunnel, TunnelEntry, TunnelKind, TunnelManager,
+ TunnelStatus, TOFU_PROMPT_TIMEOUT,
};
use super::{windows_ssh_agent_endpoints, WindowsSshAgentEndpoint, WINDOWS_OPENSSH_AGENT_PIPE};
use crate::db::ssh_prompt;
use crate::models::connection::{default_ssh_connect_timeout_secs, SshTunnelConfig};
use russh::client;
- use russh::client::Handler;
+ use russh::client::{AuthResult, Handler};
use russh::keys::decode_secret_key;
use russh::keys::ssh_key::PublicKey;
use russh::server::{self, Auth, Response, Server};
@@ -2149,6 +2407,53 @@ mod tests {
);
}
+ #[test]
+ fn normalizes_ssh_fingerprint_forms() {
+ let expected = "SHA256:ABC+/DEF";
+ assert_eq!(normalize_ssh_fingerprint("SHA256:abc+/def="), expected);
+ assert_eq!(normalize_ssh_fingerprint(" sha256:abc+/def "), expected);
+ assert_eq!(normalize_ssh_fingerprint("SHA256_abc+/def"), expected);
+ assert_eq!(normalize_ssh_fingerprint("SHA256_ABC+/DEF"), expected);
+ assert_eq!(normalize_ssh_fingerprint(" MD5:aa:bb "), "MD5:aa:bb");
+ assert_eq!(normalize_ssh_fingerprint(""), "");
+ }
+
+ #[test]
+ fn classifies_every_agent_attempt_outcome() {
+ assert_eq!(classify_agent_attempt(&Ok(AuthResult::Success)), AgentAttempt::Success);
+
+ let keyboard_interactive = AuthResult::Failure {
+ remaining_methods: MethodSet::from(&[MethodKind::KeyboardInteractive][..]),
+ partial_success: false,
+ };
+ assert_eq!(classify_agent_attempt(&Ok(keyboard_interactive)), AgentAttempt::KeyboardInteractiveRequired);
+
+ let password_still_offered = AuthResult::Failure {
+ remaining_methods: MethodSet::from(&[MethodKind::Password][..]),
+ partial_success: false,
+ };
+ assert_eq!(classify_agent_attempt(&Ok(password_still_offered)), AgentAttempt::Continue);
+
+ let exhausted = AuthResult::Failure { remaining_methods: MethodSet::empty(), partial_success: false };
+ assert_eq!(classify_agent_attempt(&Ok(exhausted)), AgentAttempt::ServerClosedAuthentication);
+
+ assert_eq!(
+ classify_agent_attempt(&Err(russh::AgentAuthError::Send(russh::SendError {}))),
+ AgentAttempt::ConnectionLost
+ );
+ }
+
+ #[test]
+ fn stopped_agent_error_reports_attempted_and_total_counts() {
+ let without_filter = agent_attempts_stopped_error(6, 17, "", true);
+ assert!(without_filter.contains("6 of the 17"), "{without_filter}");
+ assert!(without_filter.contains("Select the matching agent key"), "{without_filter}");
+
+ let with_filter = agent_attempts_stopped_error(1, 17, "SHA256:abc", false);
+ assert!(with_filter.contains("1 of the 17"), "{with_filter}");
+ assert!(with_filter.contains("SHA256:abc"), "{with_filter}");
+ }
+
#[test]
fn tofu_prompt_deadline_uses_the_actual_prompt_start() {
let now = Instant::now();
@@ -2240,6 +2545,7 @@ mod tests {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: "password".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
@@ -3001,6 +3307,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"password",
5,
&known_hosts_path,
@@ -3048,6 +3355,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"key",
5,
&known_hosts_path,
@@ -3171,6 +3479,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"none",
5,
false,
@@ -3191,6 +3500,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"none",
5,
false,
@@ -3324,6 +3634,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"none",
5,
"db.internal",
@@ -3380,6 +3691,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"none",
5,
"db.internal",
@@ -3427,6 +3739,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"none",
5,
&known_hosts_path,
@@ -3477,6 +3790,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"none",
1,
&known_hosts_path,
@@ -3524,6 +3838,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"none",
5,
"db.internal",
@@ -3544,6 +3859,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"none",
5,
"db.internal",
@@ -3755,6 +4071,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"key",
5,
"db.internal",
@@ -3800,6 +4117,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"key",
5,
"db.internal",
@@ -3850,6 +4168,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"",
false,
"",
+ "",
"key",
5,
&known_hosts_path,
diff --git a/crates/dbx-drivers/src/db/transport_layer_tunnel.rs b/crates/dbx-drivers/src/db/transport_layer_tunnel.rs
index 7c93d0f453..521421075d 100644
--- a/crates/dbx-drivers/src/db/transport_layer_tunnel.rs
+++ b/crates/dbx-drivers/src/db/transport_layer_tunnel.rs
@@ -197,6 +197,7 @@ async fn start_transport_layers_internal(
&resolved.key_passphrase,
resolved.use_ssh_agent,
&resolved.ssh_agent_sock_path,
+ &resolved.ssh_agent_key_fingerprint,
&resolved.auth_method,
effective_ssh_connect_timeout_secs(resolved.connect_timeout_secs),
resolved.allow_exec_channel_proxy,
@@ -220,6 +221,7 @@ async fn start_transport_layers_internal(
&resolved.key_passphrase,
resolved.use_ssh_agent,
&resolved.ssh_agent_sock_path,
+ &resolved.ssh_agent_key_fingerprint,
&resolved.auth_method,
effective_ssh_connect_timeout_secs(resolved.connect_timeout_secs),
&target_endpoint.host,
@@ -411,6 +413,7 @@ mod tests {
expose_lan: false,
use_ssh_agent: false,
ssh_agent_sock_path: String::new(),
+ ssh_agent_key_fingerprint: String::new(),
auth_method: "password".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
diff --git a/crates/dbx-types/src/models/connection.rs b/crates/dbx-types/src/models/connection.rs
index 01bb8bd200..64b9e28331 100644
--- a/crates/dbx-types/src/models/connection.rs
+++ b/crates/dbx-types/src/models/connection.rs
@@ -500,6 +500,10 @@ pub struct SshTunnelConfig {
/// the `SSH_AUTH_SOCK` environment variable.
#[serde(default)]
pub ssh_agent_sock_path: String,
+ /// SHA-256 fingerprint (`SHA256:...`) of the one agent identity to use.
+ /// Empty means every identity the agent reports is tried, in order.
+ #[serde(default)]
+ pub ssh_agent_key_fingerprint: String,
/// 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
diff --git a/src-tauri/src/commands/tunnel_profiles.rs b/src-tauri/src/commands/tunnel_profiles.rs
index 20bbe84f4e..77a9be5690 100644
--- a/src-tauri/src/commands/tunnel_profiles.rs
+++ b/src-tauri/src/commands/tunnel_profiles.rs
@@ -25,3 +25,10 @@ pub async fn test_tunnel_profile(
) -> Result<String, String> {
state.test_tunnel_profile(&profile).await
}
+
+#[tauri::command]
+pub async fn list_ssh_agent_identities(
+ ssh_agent_sock_path: String,
+) -> Result<Vec<dbx_core::db::ssh_tunnel::AgentIdentityInfo>, String> {
+ dbx_core::db::ssh_tunnel::list_agent_identities(&ssh_agent_sock_path).await
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 1e303570e7..404a5f1d07 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -3068,6 +3068,7 @@ pub fn run() {
commands::tunnel_profiles::load_tunnel_profiles,
commands::tunnel_profiles::save_tunnel_profiles,
commands::tunnel_profiles::test_tunnel_profile,
+ commands::tunnel_profiles::list_ssh_agent_identities,
])))
.build(tauri::generate_context!())
.inspect(|app| {