diff --git a/docs/mcp-single-channel-sftp.md b/docs/mcp-single-channel-sftp.md new file mode 100644 index 000000000..ed4b06eb6 --- /dev/null +++ b/docs/mcp-single-channel-sftp.md @@ -0,0 +1,57 @@ +# MCP file operations on single-channel SSH servers + +Servers identified as single-channel (for example, `TERM-SSHD`) must not +receive an SFTP subsystem request on the interactive terminal transport. +Session-backed MCP file operations instead open a dedicated file connection +using the original terminal dial profile, with transport reuse disabled. + +The profile stays in a non-enumerable session closure. It is not returned by +host discovery or written to the vault. The dedicated connection uses the +same hostname, username, proxy/jump route, credentials and host-key policy. +Normal authentication prompts may be shown again for the new connection. +Host-key verification pins the keys actually accepted for the live terminal +and its jump hosts, including a first-time or updated key accepted during +login. A different key on the dedicated connection fails closed immediately; +reconnect the terminal to verify it before retrying the file operation. +The host's Auto/SFTP/SCP preference is preserved. + +Closing the source terminal or cancelling an open aborts pending login and +authentication prompts. Late connections are closed before registration. +The normal MCP operation cleanup closes the dedicated file connection after +the operation. Sessions created before this support was loaded retain the +protective error and must be reconnected. + +The GUI's explicit-session and vault reconnect paths validate the endpoint +before selecting this dial. Endpoint identity matching must not treat the +single-channel restriction as a route mismatch: that restriction prohibits +borrowing a channel, not opening an independent connection from a matching +profile. Only sessions that own a dedicated dial capability use this identity +lookup; host/profile, authentication, jump/proxy route and forwarding checks +remain enforced. Vault reconnects without a live pane id can select this +capability too. Actual transport reuse rules remain unchanged. + +## TERM-SSHD file semantics + +The tested TERM-SSHD gateway acknowledges pipelined writes but produces a +same-sized corrupt file. Repositioning a READ on a consumed handle returns +EOF; opening another handle before closing the first returns General failure. +These observations are consistent with a sequential, cursor-based backend +that does not implement SFTP positioned I/O correctly. + +For exactly the TERM-SSHD software identification, range transfers use one +in-flight request and restart checkpoints at zero. Downloads close the body +handle, reopen the file at zero, and compare every byte sequentially with the +local output. Uploads hash the local file and sequentially reread the complete +remote stage before promotion. A size-only acknowledgement is insufficient. +Other SSH software retains its existing concurrency and chunk sizes. + +This compatibility policy trades throughput and resume efficiency for correct +contents. Allow sufficient MCP command time for both the transfer and the +second full read. It is not a general promise that every TERM-SSHD version has +the same defect. An explicit SFTP host preference may be necessary when a +gateway advertises but cannot execute SCP. The saved preference is never +silently changed by this patch. + +For live acceptance, compare source, remote and downloaded sizes and SHA-256 +digests, and confirm the interactive terminal remains usable. A successful +tool response alone is not a substitute for this three-way check. diff --git a/electron/bridges/sftpBridge.authRetry.test.cjs b/electron/bridges/sftpBridge.authRetry.test.cjs index 464b9ce52..642a7bb14 100644 --- a/electron/bridges/sftpBridge.authRetry.test.cjs +++ b/electron/bridges/sftpBridge.authRetry.test.cjs @@ -81,6 +81,10 @@ function loadSftpBridgeWithAuthRetryMocks(t, options = {}) { setImmediate(() => { this.client.emit("connect"); this.client.emit("handshake"); + if (options.onConnect) { + options.onConnect(this.client); + return; + } if (options.alwaysSucceed) { this.client.emit("ready"); return; @@ -483,3 +487,88 @@ test("single-channel SFTP does not join an in-flight terminal dial", async (t) = assert.notEqual(MockSftpClient.instances[0].client.ended, true); assert.equal(sftpClients.has("sftp-during-terminal"), true); }); + +test("cancelling a dedicated SFTP login closes its client and rejects before authentication", async (t) => { + const controller = new AbortController(); + const { bridge, MockSftpClient } = loadSftpBridgeWithAuthRetryMocks(t, { + onConnect(client) { + controller.abort(); + // A racing ready notification must not publish a closed SFTP client. + client.emit("ready"); + }, + }); + const clients = new Map(); + bridge.init({ sftpClients: clients, sessions: new Map(), electronModule: {} }); + await assert.rejects(bridge.openSftp({ sender: makeSender() }, { + sessionId: "cancelled-login", hostname: "bastion.example", username: "root", + authMethod: "password", password: "saved-login-password", useSshAgent: false, + verifyHostKeys: false, fileProtocol: "sftp", singleChannelSsh: true, + reuseTransport: false, abortSignal: controller.signal, + }), { name: "AbortError" }); + assert.equal(MockSftpClient.instances[0].client.ended, true); + assert.equal(MockSftpClient.instances[0].client.destroyed, true); + assert.equal(clients.size, 0); +}); + +for (const initialTrust of ["unknown", "changed"]) { + test(`dedicated SFTP pins the terminal's accepted ${initialTrust} host key without reconnect`, async (t) => { + const verifier = require("./hostKeyVerifier.cjs"); + const { attachSessionSftpDial } = require("./sshBridge/sessionSftpDial.cjs"); + const makeKey = (byte) => { + const type = Buffer.from("ssh-ed25519"); + const blob = Buffer.alloc(4 + type.length + 4 + 32); + blob.writeUInt32BE(type.length); type.copy(blob, 4); + blob.writeUInt32BE(32, 4 + type.length); blob.fill(byte, 8 + type.length); + return blob; + }; + const acceptedRaw = makeKey(1); + const oldRaw = makeKey(2); + let remoteKey = acceptedRaw; + const sender = makeSender(); + const acceptedHostKeys = []; + const oldInfo = verifier.describeHostKey(oldRaw); + const options = { + hostname: "gateway.example", port: 22, username: "root", + authMethod: "password", password: "test-only", useSshAgent: false, + verifyHostKeys: true, fileProtocol: "sftp", + knownHosts: initialTrust === "changed" ? [{ hostname: "gateway.example", port: 22, ...oldInfo }] : [], + }; + const terminalVerifier = verifier.createHostVerifier({ + ...options, sender, sessionId: "terminal-trust", + onAccepted: info => acceptedHostKeys.push(info), + }); + const terminalAccepted = new Promise(resolve => terminalVerifier(acceptedRaw, resolve)); + const request = sender.sent.find(message => message.channel === "netcatty:host-key:verify").payload; + assert.equal(request.status, initialTrust); + verifier.handleResponse({ sender }, { requestId: request.requestId, accept: true, addToKnownHosts: true }); + assert.equal(await terminalAccepted, true); + const { bridge } = loadSftpBridgeWithAuthRetryMocks(t, { onConnect(client) { + client.connectOpts.hostVerifier(remoteKey, accept => { + if (accept) client.emit("ready"); + else client.emit("error", new Error("Host denied (verification failed)")); + }); + } }); + const session = { singleChannelSsh: true, conn: Object.assign(new EventEmitter(), { sftp() { throw new Error("must not borrow terminal"); } }), stream: new EventEmitter(), sftpFileProtocol: "sftp" }; + const sessions = new Map([["terminal-trust", session]]); + const clients = new Map(); + bridge.init({ sessions, sftpClients: clients, electronModule: {} }); + attachSessionSftpDial(session, options, { + sessions, sessionId: "terminal-trust", sender, acceptedHostKeys, + openSftp: bridge.openSftp, closeSftp: bridge.closeSftp, + }); + // The captured route must not alias mutable caller/collector arrays. + acceptedHostKeys.length = 0; + const opened = await bridge.openSftpForSession(null, { sessionId: "terminal-trust" }); + assert.equal(clients.has(opened.sftpId), true); + await bridge.closeSftp(null, opened); + for (const unexpectedKey of [oldRaw, makeKey(3)]) { + remoteKey = unexpectedKey; + await assert.rejects(bridge.openSftpForSession(null, { sessionId: "terminal-trust" }), { + code: "ERR_HOST_KEY_UNVERIFIED", message: /Reconnect the terminal/, + }); + } + assert.equal(sender.sent.filter(message => message.channel === "netcatty:host-key:verify").length, 1); + assert.equal(verifier.getRequests().size, 0); + assert.equal(clients.size, 0); + }); +} diff --git a/electron/bridges/sftpBridge.cjs b/electron/bridges/sftpBridge.cjs index be3df90f5..774e04635 100644 --- a/electron/bridges/sftpBridge.cjs +++ b/electron/bridges/sftpBridge.cjs @@ -765,15 +765,27 @@ function findRemoteSftpSourceByEndpoint(sourceSessionId, expectedEndpoint, requi const requested = sessions?.get(sourceSessionId); const matchesExpectedEndpoint = (session) => { const actualEndpoint = session?._reuseEndpoint || session?.connRef?.endpoint; + // Selecting the original dial profile is not borrowing a channel. A + // single-channel peer may match the route while requiring a new transport. + // Keep the normal reuse guard for sessions that cannot dial independently. + const dedicatedDial = typeof session?._openDedicatedSftp === "function"; + if (dedicatedDial && typeof session._matchesDedicatedSftpEndpoint === "function") { + return session._matchesDedicatedSftpEndpoint(expectedEndpoint); + } + const matchesIdentity = (requested, existing) => endpointAllowsReuse( + dedicatedDial ? { ...requested, singleChannelSsh: false } : requested, + dedicatedDial ? { ...existing, singleChannelSsh: false } : existing, + "channel", + ); return Boolean( actualEndpoint - && (endpointAllowsReuse(expectedEndpoint, actualEndpoint, "channel") + && (matchesIdentity(expectedEndpoint, actualEndpoint) || (session._sftpReuseEndpoint - && endpointAllowsReuse({ + && matchesIdentity({ ...session._sftpReuseEndpoint, authFingerprint: actualEndpoint.authFingerprint, - }, actualEndpoint, "channel") - && endpointAllowsReuse(expectedEndpoint, session._sftpReuseEndpoint, "channel"))), + }, actualEndpoint) + && matchesIdentity(expectedEndpoint, session._sftpReuseEndpoint))), ); }; const hasLiveSftpConnection = (session) => { @@ -1979,6 +1991,13 @@ async function openSftpForSession(_event, payload) { session.singleChannelSsh || remoteSoftwareRequiresSingleChannel(session.remoteSshVersion || sshClient?._remoteVer) ) { + if (typeof session._openDedicatedSftp === "function") { + const opened = await session._openDedicatedSftp(payload); + const client = sftpClients?.get(opened.sftpId); + if (client) client.__netcattySourceSessionId = sourceSessionId; + copySftpEncodingState(payload?.encodingStateKey, opened.sftpId); + return opened; + } const err = new Error( "This host is configured for single-channel SSH. Opening SFTP on the terminal connection would disconnect it.", ); @@ -2440,7 +2459,9 @@ async function openSftp(event, options) { if (options.reuseTransport !== false) { const endpoint = buildConnectionReuseEndpoint(options); const source = findRemoteSftpSourceByEndpoint(options.sourceSessionId, endpoint); - if (source?.session._sftpReuseEndpoint) { + const dedicatedDial = typeof source?.session._openDedicatedSftp === "function"; + if (source && (source.session._sftpReuseEndpoint + || dedicatedDial)) { try { return await openSftpForSession(event, { ...options, @@ -2448,8 +2469,11 @@ async function openSftp(event, options) { expectedEndpoint: options, requireExactSourceSession: true, }); - } catch { - // Preserve the normal fresh-connection fallback if the channel fails. + } catch (error) { + // A dedicated dial owns its trust/lifecycle boundary. Never turn its + // rejection into a new login with different trust or cancellation state. + if (dedicatedDial) throw error; + // Preserve the normal fresh-connection fallback for reusable channels. } } } diff --git a/electron/bridges/sftpBridge.singleChannelDial.test.cjs b/electron/bridges/sftpBridge.singleChannelDial.test.cjs new file mode 100644 index 000000000..d37501d97 --- /dev/null +++ b/electron/bridges/sftpBridge.singleChannelDial.test.cjs @@ -0,0 +1,218 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const bridge = require("./sftpBridge.cjs"); +const { buildConnectionReuseEndpoint, normalizeEndpoint } = require("./sshConnectionPool.cjs"); + +test("GUI vault reconnect finds the dedicated terminal dial without a source-session hint", async (t) => { + t.mock.method(require("node:net").Socket.prototype, "connect", () => { + throw new Error("Unexpected fresh vault dial instead of the terminal profile"); + }); + const options = { + hostId: "vault-gateway", hostname: "gateway.example", username: "gateway/target/root", + password: "test-only-password", authMethod: "password", port: 22, fileProtocol: "sftp", + }; + let opened = 0; + const clients = new Map([["gui-dedicated", {}]]); + bridge.init({ sessions: new Map([["live-terminal", { + singleChannelSsh: true, remoteSshVersion: "TERM-SSHD", + _reuseEndpoint: normalizeEndpoint({ ...buildConnectionReuseEndpoint(options), singleChannelSsh: true }), + _sftpReuseEndpoint: null, + conn: { sftp() { throw new Error("terminal channel must not be borrowed"); } }, + async _openDedicatedSftp(payload) { + opened++; + assert.equal(payload.sessionId, "live-terminal"); + return { sftpId: "gui-dedicated", sourceSessionId: "live-terminal", fileProtocol: "sftp" }; + }, + }]]), sftpClients: clients, electronModule: {} }); + assert.equal((await bridge.openSftp({ sender: { isDestroyed: () => false } }, options)).sftpId, "gui-dedicated"); + assert.equal(opened, 1); +}); + +for (const code of ["ERR_HOST_KEY_UNVERIFIED", "ERR_SFTP_SOURCE_SESSION_CLOSED", "ABORT_ERR"]) { + test(`GUI dedicated dial propagates ${code} without fresh-login fallback`, async (t) => { + let freshDials = 0; + t.mock.method(require("node:net").Socket.prototype, "connect", () => { + freshDials++; + throw new Error("Unexpected fresh connection after dedicated-dial rejection"); + }); + const options = { hostname: "gateway.example", username: "root", password: "test-only", authMethod: "password", fileProtocol: "sftp" }; + const failure = Object.assign(new Error("dedicated trust or lifecycle rejection"), { code }); + const session = { + singleChannelSsh: true, + _reuseEndpoint: normalizeEndpoint({ ...buildConnectionReuseEndpoint(options), singleChannelSsh: true }), + conn: { sftp() { throw new Error("must not borrow terminal"); } }, + async _openDedicatedSftp() { + // Lifecycle cleanup may remove the capability while an open is pending. + delete session._openDedicatedSftp; + throw failure; + }, + }; + bridge.init({ sessions: new Map([["terminal", session]]), sftpClients: new Map(), electronModule: {} }); + await assert.rejects(bridge.openSftp({ sender: { isDestroyed: () => false } }, options), error => error === failure); + assert.equal(freshDials, 0); + }); +} + +test("ordinary reusable-channel failures retain fresh-login fallback", async (t) => { + let freshDials = 0; + let borrowedChannels = 0; + t.mock.method(require("node:net").Socket.prototype, "connect", () => { + freshDials++; + throw new Error("fresh-login fallback reached"); + }); + const options = { hostname: "ordinary.example", username: "root", password: "test-only", authMethod: "password", fileProtocol: "sftp", useSshAgent: false }; + const endpoint = normalizeEndpoint(buildConnectionReuseEndpoint(options)); + const conn = Object.assign(new (require("node:events").EventEmitter)(), { + sftp(callback) { borrowedChannels++; callback(new Error("channel failed")); }, + }); + bridge.init({ sessions: new Map([["ordinary", { + _reuseEndpoint: endpoint, _sftpReuseEndpoint: endpoint, conn, + }]]), sftpClients: new Map(), electronModule: {} }); + await assert.rejects(bridge.openSftp({ sender: { isDestroyed: () => false } }, options), /fresh-login fallback reached/); + assert.ok(borrowedChannels > 0); + assert.equal(freshDials, 1); +}); + +for (const mismatch of [null, "hostId", "hostname", "username", "password", "jumpHosts", "proxy", "agentForwarding"]) { + test(`single-channel endpoint validation selects a dedicated dial only for matching identity (${mismatch})`, async () => { + const options = { + hostId: "gateway-target", hostname: "gateway.example", username: "gateway/target/root", + password: "test-only-password", authMethod: "password", port: 22, + jumpHosts: [{ hostname: "jump.example", username: "jump-user", password: "jump-test" }], + }; + const requested = { ...options }; + if (mismatch === "hostId") requested.hostId = "other-profile"; + if (mismatch === "hostname") requested.hostname = "other.example"; + if (mismatch === "username") requested.username = "another-user"; + if (mismatch === "password") requested.password = "different-test-password"; + if (mismatch === "jumpHosts") requested.jumpHosts = [{ ...options.jumpHosts[0], hostname: "other-jump.example" }]; + if (mismatch === "proxy") requested.proxy = { type: "http", host: "proxy.example", port: 8080 }; + if (mismatch === "agentForwarding") requested.agentForwarding = true; + let dedicatedDials = 0; + const clients = new Map([["dedicated", {}]]); + bridge.init({ sessions: new Map([["terminal", { + singleChannelSsh: true, remoteSshVersion: "TERM-SSHD", + _reuseEndpoint: normalizeEndpoint({ ...buildConnectionReuseEndpoint(options), singleChannelSsh: true }), + conn: { sftp() { throw new Error("must not borrow a terminal channel"); } }, + async _openDedicatedSftp() { dedicatedDials++; return { sftpId: "dedicated", sourceSessionId: "terminal" }; }, + }]]), sftpClients: clients, electronModule: {} }); + const result = bridge.openSftpForSession(null, { + sessionId: "terminal", expectedEndpoint: requested, requireExactSourceSession: true, + }); + if (mismatch) { + await assert.rejects(result, { code: "ERR_SFTP_SOURCE_ROUTE_MISMATCH" }); + assert.equal(dedicatedDials, 0); + } else { + assert.equal((await result).sftpId, "dedicated"); + assert.equal(dedicatedDials, 1); + } + }); +} + +for (const flag of [true, false]) { + test(`single-channel session opens a dedicated SFTP connection (runtime flag=${flag})`, async () => { + let terminalChannels = 0; + const clients = new Map([["dedicated", {}]]); + const controller = new AbortController(); + const payload = { sessionId: "terminal", abortSignal: controller.signal, fileProtocol: "sftp" }; + const session = { + singleChannelSsh: flag, remoteSshVersion: "TERM-SSHD", + conn: { sftp() { terminalChannels++; throw new Error("terminal must remain untouched"); } }, + async _openDedicatedSftp(received) { + assert.equal(received, payload); + return { sftpId: "dedicated", sourceSessionId: "terminal", fileProtocol: "sftp" }; + }, + }; + bridge.init({ sessions: new Map([["terminal", session]]), sftpClients: clients, electronModule: {} }); + assert.deepEqual(await bridge.openSftpForSession(null, payload), { + sftpId: "dedicated", sourceSessionId: "terminal", fileProtocol: "sftp", + }); + assert.equal(terminalChannels, 0); + assert.equal(clients.get("dedicated").__netcattySourceSessionId, "terminal"); + }); +} + +test("legacy single-channel sessions retain the protection when no dial profile exists", async () => { + bridge.init({ sessions: new Map([["terminal", { + singleChannelSsh: true, conn: { sftp() { throw new Error("must not open"); } }, + }]]), sftpClients: new Map(), electronModule: {} }); + await assert.rejects(bridge.openSftpForSession(null, { sessionId: "terminal" }), { + code: "ERR_SFTP_SINGLE_CHANNEL_BASTION", + }); +}); + +test("dedicated opens restore auto-detected filename encoding across MCP operations", async () => { + const iconv = require("iconv-lite"); + const name = "\u4e2d\u6587.txt"; + const path = `/${name}`; + const clients = new Map(); + const paths = []; + let opened = 0; + const session = { + singleChannelSsh: true, + conn: { sftp() { throw new Error("must not borrow terminal"); } }, + async _openDedicatedSftp() { + const sftpId = `encoding-dedicated-${++opened}`; + clients.set(sftpId, { end: async () => {}, sftp: { + mkdir() {}, unlink() {}, + readdir(_path, callback) { callback(null, [{ filename: name, filenameRaw: iconv.encode(name, "gb18030"), attrs: { mode: 0o100644, size: 7, mtime: 1 } }]); }, + stat(encodedPath, callback) { paths.push(encodedPath); callback(null, { mode: 0o100644, size: 7, mtime: 1 }); }, + } }); + return { sftpId }; + }, + }; + bridge.init({ sessions: new Map([["encoding-terminal", session]]), sftpClients: clients, electronModule: {} }); + const key = "dedicated-encoding-regression"; + try { + const first = await bridge.openSftpForSession(null, { sessionId: "encoding-terminal", encodingStateKey: key }); + const list = await bridge.listSftp(null, { sftpId: first.sftpId, path: "/", encoding: "auto" }); + assert.equal(list[0].name, name); + assert.equal(bridge.getResolvedFilenameEncoding(first.sftpId), "gb18030"); + await bridge.closeSftp(null, { sftpId: first.sftpId, encodingStateKey: key }); + const second = await bridge.openSftpForSession(null, { sessionId: "encoding-terminal", encodingStateKey: key }); + await bridge.statSftp(null, { sftpId: second.sftpId, path, encoding: "auto" }); + assert.deepEqual(paths, [iconv.encode(path, "gb18030")]); + await bridge.closeSftp(null, { sftpId: second.sftpId }); + } finally { + bridge.clearSftpEncodingState(key); + } +}); + +for (const keepaliveInterval of [0, 60]) for (const initialTrust of [[], [{ hostname: "gateway.example", port: 22, keyType: "ssh-rsa", fingerprint: "SHA256:old" }]]) { + test(`GUI dedicated dial follows newly saved accepted key (previous records=${initialTrust.length}, keepalive=${keepaliveInterval})`, async (t) => { + t.mock.method(require("node:net").Socket.prototype, "connect", () => { throw new Error("unexpected fresh login"); }); + const accepted = { hostname: "gateway.example", port: 22, keyType: "ssh-rsa", fingerprint: "SHA256:accepted" }; + const options = { hostname: accepted.hostname, username: "root", password: "captured", authMethod: "password", knownHosts: initialTrust, keepaliveInterval }; + const session = { singleChannelSsh: true, conn: { sftp() { throw new Error("must not borrow"); } }, _reuseEndpoint: normalizeEndpoint(buildConnectionReuseEndpoint(options)) }; + const sessions = new Map([["terminal", session]]); + let dials = 0; + require("./sshBridge/sessionSftpDial.cjs").attachSessionSftpDial(session, options, { + sessions, sessionId: "terminal", sender: { isDestroyed: () => false }, acceptedHostKeys: [accepted], + openSftp: async () => { dials++; return { sftpId: "saved-trust" }; }, + }); + bridge.init({ sessions, sftpClients: new Map(), electronModule: {} }); + assert.equal((await bridge.openSftp(null, { ...options, knownHosts: [accepted] })).sftpId, "saved-trust"); + assert.equal(dials, 1); + for (const knownHosts of [[], [{ ...accepted, fingerprint: "SHA256:other" }], [{ ...accepted, port: 2222 }]]) { + await assert.rejects(bridge.openSftp(null, { ...options, knownHosts }), { code: "ERR_HOST_KEY_UNVERIFIED" }); + } + assert.equal(dials, 1); + }); +} + +test("dedicated GUI trust checks verified jump even when target verification is disabled", async () => { + const accepted = { hostname: "jump.example", port: 22, keyType: "ssh-rsa", fingerprint: "SHA256:jump" }; + const options = { hostname: "target.example", verifyHostKeys: false, jumpHosts: [{ hostname: "jump.example", verifyHostKeys: true }] }; + const session = {}; + let dials = 0; + require("./sshBridge/sessionSftpDial.cjs").attachSessionSftpDial(session, options, { + sessions: new Map([["terminal", session]]), sessionId: "terminal", acceptedHostKeys: [accepted], + openSftp: async () => { dials++; return { sftpId: "jump-trust" }; }, + }); + assert.equal(session._matchesDedicatedSftpEndpoint({ ...options, knownHosts: [accepted] }), true); + await session._openDedicatedSftp({ expectedEndpoint: { ...options, knownHosts: [accepted] } }); + await assert.rejects(session._openDedicatedSftp({ expectedEndpoint: { ...options, knownHosts: [] } }), { code: "ERR_HOST_KEY_UNVERIFIED" }); + assert.equal(dials, 1); +}); diff --git a/electron/bridges/sftpBridge/openConnection.cjs b/electron/bridges/sftpBridge/openConnection.cjs index 2577377c7..5e9354033 100644 --- a/electron/bridges/sftpBridge/openConnection.cjs +++ b/electron/bridges/sftpBridge/openConnection.cjs @@ -172,17 +172,36 @@ function createOpenConnectionApi(ctx) { const connections = []; let currentSocket = null; let activeConn = null; - const defaultAgentSocket = await getAvailableAgentSocket(); + const signal = options.abortSignal; + let rejectPending = null; const cleanupSocket = (socket) => { if (!socket) return; try { socket.end?.(); } catch { /* ignore */ } try { socket.destroy?.(); } catch { /* ignore */ } }; + const onAbort = () => { + cleanupSocket(currentSocket); + for (const conn of new Set([...connections, activeConn])) { + if (!conn) continue; + try { conn.end?.(); } catch { /* ignore */ } + try { conn.destroy?.(); } catch { /* ignore */ } + } + rejectPending?.(new DOMException("SFTP jump connection cancelled", "AbortError")); + }; + const checkCancelled = () => { + if (!signal?.aborted) return; + onAbort(); + throw new DOMException("SFTP jump connection cancelled", "AbortError"); + }; + signal?.addEventListener("abort", onAbort, { once: true }); try { + checkCancelled(); + const defaultAgentSocket = await getAvailableAgentSocket(); // Connect through each jump host for (let i = 0; i < jumpHosts.length; i++) { + checkCancelled(); const jump = jumpHosts[i]; const isFirst = i === 0; const isLast = i === jumpHosts.length - 1; @@ -279,6 +298,7 @@ function createOpenConnectionApi(ctx) { identityFilePaths: jump.identityFilePaths, hostname: hopLabel, initialPassphrase: jump.passphrase, + sessionId: connId, passphraseSignal: options.abortSignal, logPrefix: `[SFTP Chain] Hop ${i + 1}:`, onLoaded: (loaded) => { console.log(`[SFTP Chain] Hop ${i + 1}: loaded identity file ${loaded.keyPath}`); @@ -298,6 +318,7 @@ function createOpenConnectionApi(ctx) { keyName: jump.keyId || jump.label || jump.username, hostname: hopLabel, initialPassphrase: jump.passphrase, + sessionId: connId, passphraseSignal: options.abortSignal, logPrefix: `[SFTP Chain] Hop ${i + 1}:`, }) : null; @@ -333,7 +354,8 @@ function createOpenConnectionApi(ctx) { sender, `SSH key for ${keyLabel}`, keyLabel, - hopLabel + hopLabel, + false, { sessionId: connId, signal: options.abortSignal } ); if (result?.passphrase) { connOpts.passphrase = result.passphrase; @@ -383,6 +405,7 @@ function createOpenConnectionApi(ctx) { if (effectiveHopProxy) { currentSocket = await createProxySocket(effectiveHopProxy, jump.hostname, jump.port || 22, { timeoutMs: hopConnectionTimeouts.tcpConnectTimeoutMs, + onSocket: (socket) => { currentSocket = socket; if (signal?.aborted) cleanupSocket(socket); }, }); connOpts.sock = currentSocket; delete connOpts.host; @@ -395,7 +418,9 @@ function createOpenConnectionApi(ctx) { } // Connect this hop + checkCancelled(); await new Promise((resolve, reject) => { + rejectPending = reject; let settled = false; let authReadyTimer = null; const clearAuthReadyTimer = () => { @@ -505,7 +530,9 @@ function createOpenConnectionApi(ctx) { // Create forward stream to next hop console.log(`[SFTP Chain] Hop ${i + 1}/${jumpHosts.length}: Forwarding to ${nextHost}:${nextPort}...`); + checkCancelled(); currentSocket = await new Promise((resolve, reject) => { + rejectPending = reject; let settled = false; const timeout = setTimeout(() => { if (settled) return; @@ -514,7 +541,8 @@ function createOpenConnectionApi(ctx) { }, nextConnectionTimeouts.tcpConnectTimeoutMs); timeout.unref?.(); openBoundedForwardOutCallback(conn, '127.0.0.1', 0, nextHost, nextPort, (err, stream) => { - if (settled) { + if (settled || signal?.aborted) { + clearTimeout(timeout); try { stream?.end?.(); } catch { /* ignore */ } return; } @@ -531,6 +559,7 @@ function createOpenConnectionApi(ctx) { }); } + checkCancelled(); // Return the final forwarded stream and all connections for cleanup return { socket: currentSocket, @@ -546,6 +575,8 @@ function createOpenConnectionApi(ctx) { try { conn.end(); } catch (cleanupErr) { console.warn('[SFTP Chain] Cleanup error:', cleanupErr.message); } } throw err; + } finally { + signal?.removeEventListener("abort", onAbort); } } @@ -1085,11 +1116,26 @@ function createOpenConnectionApi(ctx) { } } + const signal = options.abortSignal; + let cancelFresh = () => {}; + let rejectCancelled; + const cancelled = new Promise((_resolve, reject) => { rejectCancelled = reject; }); + const throwIfCancelled = () => { + if (signal?.aborted) throw new DOMException("SFTP open cancelled", "AbortError"); + }; + const onAbort = () => { + cancelFresh(); + rejectCancelled(new DOMException("SFTP open cancelled", "AbortError")); + }; + signal?.addEventListener("abort", onAbort, { once: true }); try { - return await openFreshSftp(); + throwIfCancelled(); + return await Promise.race([openFreshSftp(), cancelled]); } catch (err) { if (pendingDialCoordination) failTransportDial(pendingDialCoordination, err); throw err; + } finally { + signal?.removeEventListener("abort", onAbort); } async function openFreshSftp() { @@ -1111,9 +1157,6 @@ function createOpenConnectionApi(ctx) { try { client.client?.destroy?.(); } catch { /* ignore */ } }; - // Get default keys early to use for both chain and target - const defaultKeys = await findAllDefaultPrivateKeysFromHelper(); - // Check if we need to connect through jump hosts const jumpHosts = options.jumpHosts || []; const hasJumpHosts = jumpHosts.length > 0; @@ -1131,10 +1174,27 @@ function createOpenConnectionApi(ctx) { try { connectionSocket.destroy?.(); } catch { /* ignore */ } } }; + cancelFresh = () => { + cleanupPendingConnection(); + closeFreshClient(); + require("../keyboardInteractiveHandler.cjs").cancelRequestsForSession(connId); + require("../passphraseHandler.cjs").cancelPassphraseRequestsForSession(connId); + require("../hostKeyVerifier.cjs").cancelRequestsForSession(connId); + }; + // Abort can race an awaited proxy, jump chain or authentication prompt. + // A late socket must be disposed before it can start another login. + const checkCancelled = () => { + if (!signal?.aborted) return; + cancelFresh(); + throwIfCancelled(); + }; + const defaultKeys = await findAllDefaultPrivateKeysFromHelper(); + checkCancelled(); // Pre-fetch agent socket (async check for Windows SSH Agent service) // This is used by both jump host chain auth and final host auth const agentSocket = await getAvailableAgentSocket(options.identityAgent); + checkCancelled(); // Handle chain/proxy connections if (hasJumpHosts) { @@ -1159,10 +1219,16 @@ function createOpenConnectionApi(ctx) { options.proxy, options.hostname, options.port || 22, - { timeoutMs: targetConnectionTimeouts.tcpConnectTimeoutMs }, + { + timeoutMs: targetConnectionTimeouts.tcpConnectTimeoutMs, + onSocket: (socket) => { + connectionSocket = socket; + if (signal?.aborted) cleanupPendingConnection(); + }, + }, ); } - + checkCancelled(); const keepalivePolicy = resolveConnectionKeepalivePolicy(options); const connectOpts = { host: options.hostname, @@ -1233,6 +1299,7 @@ function createOpenConnectionApi(ctx) { identityFilePaths: options.identityFilePaths, hostname: options.hostname, initialPassphrase: options.passphrase, + sessionId: connId, passphraseSignal: options.abortSignal, logPrefix: "[SFTP]", onLoaded: (loaded) => { console.log(`[SFTP] Loaded identity file ${loaded.keyPath}`); @@ -1252,6 +1319,7 @@ function createOpenConnectionApi(ctx) { keyName: options.keyId || options.username, hostname: options.hostname, initialPassphrase: options.passphrase, + sessionId: connId, passphraseSignal: options.abortSignal, logPrefix: "[SFTP]", }) : null; @@ -1289,7 +1357,8 @@ function createOpenConnectionApi(ctx) { event.sender, `SSH key for ${options.hostname}`, options.hostname, - options.hostname + options.hostname, + false, { sessionId: connId, signal: options.abortSignal } ); if (result?.passphrase) { connectOpts.passphrase = result.passphrase; @@ -1459,6 +1528,11 @@ function createOpenConnectionApi(ctx) { cleanup(); // See jump-hop note above: SFTP is RPC-bound, so disable Nagle. enableSshNoDelay(sshClient); + if (signal?.aborted) { + cancelFresh(); + reject(new DOMException("SFTP open cancelled", "AbortError")); + return; + } if (remoteSoftwareRequiresSingleChannel(sshClient._remoteVer)) { peerSingleChannelSsh = true; } @@ -1543,11 +1617,13 @@ function createOpenConnectionApi(ctx) { sendSftpProgress(event.sender, connId, options.hostname, 'connecting'); try { + checkCancelled(); sshClient.connect(connectOpts); } catch (e) { settle(reject, e); } }); + checkCancelled(); // Increase max listeners AFTER connect, when the internal ssh2 Client exists // This prevents Node.js MaxListenersExceededWarning when performing many operations // ssh2-sftp-client adds temporary listeners for each operation, so we need a high limit diff --git a/electron/bridges/sshBridge.cjs b/electron/bridges/sshBridge.cjs index 2650a8447..929decc77 100644 --- a/electron/bridges/sshBridge.cjs +++ b/electron/bridges/sshBridge.cjs @@ -522,7 +522,7 @@ function closeTerminalOutputSession(sessionId) { /** * Connect through a chain of jump hosts */ -async function connectThroughChain(event, options, jumpHosts, targetHost, targetPort, sessionId) { +async function connectThroughChain(event, options, jumpHosts, targetHost, targetPort, sessionId, onHostKeyAccepted) { const targetConnectionTimeouts = resolveSshConnectionTimeouts(options); const sender = event.sender; const connections = options?._connectionsRef || []; @@ -610,6 +610,7 @@ async function connectThroughChain(event, options, jumpHosts, targetHost, target knownHosts: options.knownHosts, verifyHostKeys: jump.verifyHostKeys ?? options.verifyHostKeys, bootEpoch: options.bootEpoch, + onAccepted: onHostKeyAccepted, }); attachSshDebugLogger(connOpts, sshDiagnosticLogger); logSshAlgorithms("Jump host", connOpts.algorithms, { diff --git a/electron/bridges/sshBridge/sessionSftpDial.cjs b/electron/bridges/sshBridge/sessionSftpDial.cjs new file mode 100644 index 000000000..7533ea7a0 --- /dev/null +++ b/electron/bridges/sshBridge/sessionSftpDial.cjs @@ -0,0 +1,115 @@ +"use strict"; + +const { randomUUID } = require("node:crypto"); +const { buildConnectionReuseEndpoint, normalizeEndpoint, endpointAllowsReuse } = require("../sshConnectionPool.cjs"); +const { classifyHostKey } = require("../hostKeyVerifier.cjs"); + +// Keep the authenticated dial profile in a closure, never in discovery metadata +// or persisted host data. The terminal still owns this profile's lifetime. +function attachSessionSftpDial(session, options, { sessions, sessionId, sender, openSftp, closeSftp, acceptedHostKeys = [] }) { + // Pin this redial to the keys actually accepted for the live route, not the + // renderer snapshot from before a first-trust / changed-key confirmation. + // Do not retain an older trusted key alongside its accepted replacement. + const dialOptions = { + ...options, + knownHosts: acceptedHostKeys.map((key) => ({ ...key })), + hostKeyUnattended: true, + }; + const routeEndpoint = (profile) => normalizeEndpoint({ + ...buildConnectionReuseEndpoint(profile), + ...(profile.keepaliveIntervalMs != null ? { + keepaliveIntervalMs: profile.keepaliveIntervalMs, + keepaliveCountMax: profile.keepaliveCountMax, + } : {}), + ignoreKnownHostTrustForReuse: true, + singleChannelSsh: false, + }); + const originalRoute = routeEndpoint({ + ...options, + agentForwarding: session._reuseEndpoint?.agentForwarding ?? options.agentForwarding, + }); + const passwordlessRoute = options.sftpReuseOptions && !options.sftpReuseOptions.password + ? routeEndpoint(options.sftpReuseOptions) + : null; + Object.defineProperty(session, "_matchesDedicatedSftpEndpoint", { + value: (request) => { + const requested = routeEndpoint(request); + return endpointAllowsReuse(requested, originalRoute, "channel") + || Boolean(passwordlessRoute + && endpointAllowsReuse({ ...passwordlessRoute, authFingerprint: originalRoute?.authFingerprint }, originalRoute, "channel") + && endpointAllowsReuse(requested, passwordlessRoute, "channel")); + }, + }); + const assertCurrentTrust = (request) => { + if (!request) return; // Explicit session operations use its accepted lifetime pin. + const hops = [request, ...(Array.isArray(request.jumpHosts) ? request.jumpHosts : [])]; + const trusted = hops.every((hop) => { + if ((hop.verifyHostKeys ?? request.verifyHostKeys) === false) return true; + return dialOptions.knownHosts.some((key) => + String(key.hostname || "").trim().toLowerCase() === String(hop.hostname || "").trim().toLowerCase() + && (Number(key.port) || 22) === (Number(hop.port) || 22) + && classifyHostKey({ + knownHosts: Array.isArray(request.knownHosts) ? request.knownHosts : [], + hostname: key.hostname, port: key.port || 22, + keyType: key.keyType, fingerprint: key.fingerprint, + }).status === "trusted"); + }); + if (!trusted) { + const error = new Error("The terminal host key is no longer trusted. Reconnect the terminal to verify the host key before transferring files."); + error.code = "ERR_HOST_KEY_UNVERIFIED"; + throw error; + } + }; + for (const key of ["sessionId", "sourceSessionId", "bootEpoch", "_connRef", "_sourceReuseState", "sftpReuseOptions", "sock"]) { + delete dialOptions[key]; + } + const assertActive = (signal) => { + if (signal?.aborted) throw new DOMException("SFTP open cancelled", "AbortError"); + if (sessions.get(sessionId) !== session || sender?.isDestroyed?.()) { + throw new Error("Source SSH session is no longer active"); + } + }; + Object.defineProperty(session, "_openDedicatedSftp", { + value: async (payload = {}) => { + assertActive(payload.abortSignal); + assertCurrentTrust(payload.expectedEndpoint); + const controller = new AbortController(); + const abort = () => controller.abort(); + payload.abortSignal?.addEventListener("abort", abort, { once: true }); + session.stream?.once?.("close", abort); + session.conn?.once?.("close", abort); + try { + const opened = await openSftp({ sender }, { + ...dialOptions, + sessionId: randomUUID(), + sourceSessionId: sessionId, + reuseTransport: false, + singleChannelSsh: true, + fileProtocol: payload.fileProtocol ?? session.sftpFileProtocol ?? "auto", + sudo: Boolean(payload.sudo), + abortSignal: controller.signal, + }); + try { + assertActive(controller.signal); + } catch (err) { + try { await closeSftp(null, { sftpId: opened.sftpId }); } catch { /* Preserve cancellation. */ } + throw err; + } + return { ...opened, sourceSessionId: sessionId }; + } catch (err) { + if (err?.code === "ERR_HOST_KEY_UNVERIFIED" + || /Host denied \(verification failed\)|Host key rejected/i.test(String(err?.message || ""))) { + err.code = "ERR_HOST_KEY_UNVERIFIED"; + err.message += ". Reconnect the terminal to verify the host key before transferring files."; + } + throw err; + } finally { + payload.abortSignal?.removeEventListener("abort", abort); + session.stream?.removeListener?.("close", abort); + session.conn?.removeListener?.("close", abort); + } + }, + }); +} + +module.exports = { attachSessionSftpDial }; diff --git a/electron/bridges/sshBridge/sessionSftpDial.test.cjs b/electron/bridges/sshBridge/sessionSftpDial.test.cjs new file mode 100644 index 000000000..724ad9987 --- /dev/null +++ b/electron/bridges/sshBridge/sessionSftpDial.test.cjs @@ -0,0 +1,157 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { attachSessionSftpDial } = require("./sessionSftpDial.cjs"); + +test("dedicated session SFTP preserves the authenticated route and isolates its transport", async () => { + const session = { sftpFileProtocol: "sftp" }; + const sessions = new Map([["terminal", session]]); + const sender = { isDestroyed: () => false }; + const options = { + hostname: "gateway.example", username: "user/target/root", password: "ephemeral", + proxy: { host: "proxy.example" }, jumpHosts: [{ hostname: "jump.example" }], + verifyHostKeys: true, knownHosts: [{ hostname: "gateway.example" }], + sessionId: "terminal", _connRef: { neverReuse: true }, + }; + const calls = []; + attachSessionSftpDial(session, options, { + sessions, sessionId: "terminal", sender, acceptedHostKeys: options.knownHosts, + openSftp: async (event, dial) => { calls.push({ event, dial }); return { sftpId: dial.sessionId }; }, + }); + const controller = new AbortController(); + const first = await session._openDedicatedSftp({ abortSignal: controller.signal, hostname: "untrusted.example" }); + const second = await session._openDedicatedSftp({}); + const { dial, event } = calls[0]; + assert.equal(dial.hostname, options.hostname); + assert.equal(dial.password, options.password); + assert.deepEqual(dial.proxy, options.proxy); + assert.deepEqual(dial.jumpHosts, options.jumpHosts); + assert.deepEqual(dial.knownHosts, options.knownHosts); + assert.equal(dial.verifyHostKeys, true); + assert.equal(dial.hostKeyUnattended, true); + assert.equal(dial.reuseTransport, false); + assert.equal(dial.singleChannelSsh, true); + assert.equal(dial.fileProtocol, "sftp"); + assert.equal(dial.sourceSessionId, "terminal"); + assert.equal(dial.abortSignal.aborted, false); + assert.equal(dial._connRef, undefined); + assert.notEqual(first.sftpId, "terminal"); + assert.notEqual(first.sftpId, second.sftpId); + assert.equal(event.sender, sender); + assert.equal(options.reuseTransport, undefined); + assert.equal(JSON.stringify(session).includes("ephemeral"), false); + assert.equal(Object.keys(session).includes("_openDedicatedSftp"), false); +}); + +test("closing the terminal aborts a pending dedicated authentication", async () => { + const { EventEmitter } = require("node:events"); + const session = { stream: new EventEmitter(), conn: new EventEmitter() }; + const sessions = new Map([["terminal", session]]); + attachSessionSftpDial(session, {}, { + sessions, sessionId: "terminal", sender: { isDestroyed: () => false }, + openSftp: async (_event, dial) => new Promise((_resolve, reject) => { + dial.abortSignal.addEventListener("abort", () => reject(new DOMException("cancelled", "AbortError")), { once: true }); + }), + }); + const opening = session._openDedicatedSftp({}); + session.stream.emit("close"); + await assert.rejects(opening, { name: "AbortError" }); + assert.equal(session.stream.listenerCount("close"), 0); + assert.equal(session.conn.listenerCount("close"), 0); +}); + +test("dedicated SFTP cannot redial a closed or replaced terminal", async () => { + const session = {}; + const sessions = new Map([["terminal", session]]); + let dials = 0; + attachSessionSftpDial(session, {}, { + sessions, sessionId: "terminal", sender: { isDestroyed: () => false }, + openSftp: async () => { dials++; }, + }); + sessions.set("terminal", {}); + await assert.rejects(session._openDedicatedSftp({}), /no longer active/i); + assert.equal(dials, 0); +}); + +test("dedicated SFTP rejects an already cancelled open and a destroyed owner", async () => { + const session = {}; + const sessions = new Map([["terminal", session]]); + let destroyed = false; + attachSessionSftpDial(session, {}, { + sessions, sessionId: "terminal", sender: { isDestroyed: () => destroyed }, + openSftp: async () => { throw new Error("must not dial"); }, + }); + const controller = new AbortController(); + controller.abort(); + await assert.rejects(session._openDedicatedSftp({ abortSignal: controller.signal }), { name: "AbortError" }); + destroyed = true; + await assert.rejects(session._openDedicatedSftp({}), /no longer active/i); +}); + +test("a dedicated connection completing after cancellation is closed without touching the terminal", async () => { + const session = {}; + const sessions = new Map([["terminal", session]]); + const controller = new AbortController(); + const closed = []; + attachSessionSftpDial(session, {}, { + sessions, sessionId: "terminal", sender: { isDestroyed: () => false }, + openSftp: async () => { controller.abort(); return { sftpId: "late" }; }, + closeSftp: async (_event, payload) => { closed.push(payload.sftpId); }, + }); + await assert.rejects(session._openDedicatedSftp({ abortSignal: controller.signal }), { name: "AbortError" }); + assert.deepEqual(closed, ["late"]); +}); + +test("dedicated trust is scoped to accepted host and port, with no stale fallback", async () => { + const verifier = require("../hostKeyVerifier.cjs"); + const raw = Buffer.from("accepted-route-key"); + const info = verifier.describeHostKey(raw); + for (const accepted of [[], [{ hostname: "other.example", port: 22, ...info }], [{ hostname: "target.example", port: 2222, ...info }]]) { + const session = {}; + const sender = { isDestroyed: () => false, send() { throw new Error("no orphan host-key prompt"); } }; + attachSessionSftpDial(session, { + hostname: "target.example", port: 22, verifyHostKeys: true, + knownHosts: [{ hostname: "target.example", port: 22, ...info }], + _acceptedHostKeys: [{ hostname: "target.example", port: 22, ...info }], + }, { + sessions: new Map([["terminal", session]]), sessionId: "terminal", sender, + acceptedHostKeys: accepted, + openSftp: async (_event, dial) => { + assert.equal(dial.verifyHostKeys, true); + const accepted = await new Promise(resolve => verifier.createHostVerifier({ + ...dial, sender, unattended: dial.hostKeyUnattended, + })(raw, resolve)); + assert.equal(accepted, false); + throw Object.assign(new Error("Host key rejected"), { code: "ERR_HOST_KEY_UNVERIFIED" }); + }, + }); + await assert.rejects(session._openDedicatedSftp(), { code: "ERR_HOST_KEY_UNVERIFIED" }); + } +}); + +test("jump-host verification rejection fails closed with a reconnect instruction", async () => { + const session = {}; + attachSessionSftpDial(session, { verifyHostKeys: true }, { + sessions: new Map([["terminal", session]]), sessionId: "terminal", sender: { isDestroyed: () => false }, + openSftp: async () => { throw new Error("Host denied (verification failed)"); }, + }); + await assert.rejects(session._openDedicatedSftp(), { code: "ERR_HOST_KEY_UNVERIFIED", message: /Reconnect the terminal/ }); +}); + +test("dedicated route matching keeps credential and route boundaries plus constrained OTP alias", () => { + const saved = { hostId: "vault", hostname: "gateway.example", username: "root", authMethod: "password", password: "", jumpHosts: [{ hostname: "jump.example", password: "jump" }] }; + const options = { ...saved, password: "captured-otp", sftpReuseOptions: saved }; + const session = {}; + attachSessionSftpDial(session, options, { sessions: new Map(), sessionId: "terminal" }); + assert.equal(session._matchesDedicatedSftpEndpoint(saved), true); + assert.equal(session._matchesDedicatedSftpEndpoint(options), true); + for (const mismatch of [ + { password: "changed" }, { hostname: "other.example" }, { hostId: "other" }, + { verifyHostKeys: false }, { proxy: { type: "http", host: "proxy.example", port: 8080 } }, + { jumpHosts: [{ ...saved.jumpHosts[0], password: "changed" }] }, { agentForwarding: true }, + ]) assert.equal(session._matchesDedicatedSftpEndpoint({ ...saved, ...mismatch }), false); + const unsafeAlias = {}; + attachSessionSftpDial(unsafeAlias, { ...options, sftpReuseOptions: { ...saved, hostname: "other.example" } }, { sessions: new Map(), sessionId: "terminal" }); + assert.equal(unsafeAlias._matchesDedicatedSftpEndpoint({ ...saved, hostname: "other.example" }), false); +}); diff --git a/electron/bridges/sshBridge/startSession.cjs b/electron/bridges/sshBridge/startSession.cjs index b9bcf3fc4..aa2b08384 100644 --- a/electron/bridges/sshBridge/startSession.cjs +++ b/electron/bridges/sshBridge/startSession.cjs @@ -382,6 +382,7 @@ function createStartSessionApi(ctx) { detachX11Forwarding, chainConnections, isReused, + acceptedHostKeys = [], }) { const sessionOptions = optionsForPeerSingleChannel(options, conn); const session = { @@ -439,6 +440,13 @@ function createStartSessionApi(ctx) { try { if (!isReused) conn?.end?.(); } catch { /* ignore */ } throw supersededError; } + if (session.singleChannelSsh) { + require("./sessionSftpDial.cjs").attachSessionSftpDial(session, options, { + sessions, sessionId, sender: event.sender, acceptedHostKeys, + openSftp: (...args) => require("../sftpBridge.cjs").openSftp(...args), + closeSftp: (...args) => require("../sftpBridge.cjs").closeSftp(...args), + }); + } openTerminalOutputSession?.(sessionId, event.sender); // Attach the shared connection descriptor to this session. The caller owns @@ -1312,6 +1320,10 @@ function createStartSessionApi(ctx) { async function startSSHSession(event, options) { const sessionId = options.sessionId || randomUUID(); + // Per-attempt, main-process-only trust. Never accept a caller-provided + // list of supposedly verified keys for a dedicated transport. + const acceptedHostKeys = []; + const recordAcceptedHostKey = (info) => acceptedHostKeys.push({ ...info }); const monitorMode = options._monitorMode === true; const testMode = options.testMode === true || monitorMode; const sender = event.sender; @@ -1587,6 +1599,7 @@ function createStartSessionApi(ctx) { knownHosts: options.knownHosts, verifyHostKeys: options.verifyHostKeys, bootEpoch: options.bootEpoch, + onAccepted: recordAcceptedHostKey, }); // Authentication for final target @@ -2290,7 +2303,8 @@ function createStartSessionApi(ctx) { jumpHosts, options.hostname, options.port || 22, - sessionId + sessionId, + recordAcceptedHostKey ); connectionSocket = chainResult.socket; chainConnections = chainResult.connections; @@ -2536,6 +2550,7 @@ function createStartSessionApi(ctx) { detachX11Forwarding, chainConnections, isReused: false, + acceptedHostKeys, }); } catch (setupErr) { // Callback runs from openBoundedSshShellCallback's Promise diff --git a/electron/bridges/transferBridge.cjs b/electron/bridges/transferBridge.cjs index c476599cc..0964cc6a6 100644 --- a/electron/bridges/transferBridge.cjs +++ b/electron/bridges/transferBridge.cjs @@ -33,6 +33,7 @@ const { SFTP_REQUEST_TIMEOUT_MS, TRANSFER_CHUNK_SIZE, UPLOAD_TRANSFER_CONCURRENCY, + getSftpTransferConcurrency, } = require("./transferLimits.cjs"); /** @@ -2714,6 +2715,19 @@ async function uploadFile( }); } await assertRemoteUploadSize(client, remotePath, fileSize); + if (fileSize > 0 && getSftpTransferConcurrency(sftp, UPLOAD_TRANSFER_CONCURRENCY) === 1) { + // A successful WRITE acknowledgement and matching size are insufficient + // on TERM-SSHD. Prove the staged bytes before any destination promotion. + const [localHash, remoteHash] = await Promise.all([ + hashLocalPrefix(originalLocalPath, fileSize, { signal: transfer.signal }), + hashRemotePrefixWithSftpRanges(client, remotePath, fileSize, { signal: transfer.signal }), + ]); + if (!localHash || !remoteHash || localHash !== remoteHash) { + const error = new Error("SFTP upload content verification failed"); + error.noTransferFallback = true; + throw error; + } + } // In-place replace writes the final path (fastPut / pipelined WRITE). Restore // captured mode here; staged `.part` uploads restore after rename instead. if (!generatedStagePath && Number.isFinite(existingRemoteMode)) { @@ -3869,7 +3883,7 @@ async function hashRemotePrefixWithSftpRanges(client, remotePath, bytes, options const chunkSize = TRANSFER_CHUNK_SIZE; const rangeCount = Math.ceil(bytes / chunkSize); - const concurrency = Math.min(DOWNLOAD_TRANSFER_CONCURRENCY, rangeCount); + const concurrency = Math.min(getSftpTransferConcurrency(sftp, DOWNLOAD_TRANSFER_CONCURRENCY), rangeCount); let completedBytes = 0; const openTimeoutMs = Number(options.sftpOpenTimeoutMs) > 0 ? Number(options.sftpOpenTimeoutMs) @@ -4156,10 +4170,14 @@ function writeSftpRange(sftp, handle, buffer, position, length) { }); } -async function verifyFastDownloadSamples(sftp, remoteHandle, localHandle, fileSize, transfer) { +async function verifyFastDownloadSamples(sftp, remoteHandle, localHandle, fileSize, transfer, remotePath) { if (fileSize <= 0) return; const sampleSize = Math.min(TRANSFER_CHUNK_SIZE, fileSize); - const offsets = [...new Set([ + const sequentialPeer = getSftpTransferConcurrency(sftp, DOWNLOAD_TRANSFER_CONCURRENCY) === 1; + let verificationHandle = null; + const offsets = sequentialPeer ? (function* () { + for (let position = 0; position < fileSize; position += sampleSize) yield position; + })() : [...new Set([ 0, Math.max(0, Math.floor((fileSize - sampleSize) / 2)), Math.max(0, fileSize - sampleSize), @@ -4197,6 +4215,12 @@ async function verifyFastDownloadSamples(sftp, remoteHandle, localHandle, fileSi try { if (transfer.cancelled) throw cancelError(); if (channelError) throw channelError; + // TERM-SSHD ignores repositioned READs on a consumed handle. Reopen at + // offset zero and compare every byte sequentially instead of weakening + // verification or seeking back through the completed body handle. + if (sequentialPeer) { + verificationHandle = await openSftpReadHandle(sftp, remotePath, transfer.signal, SFTP_OPEN_TIMEOUT_MS); + } for (const position of offsets) { if (transfer.cancelled) throw cancelError(); if (channelError) throw channelError; @@ -4205,7 +4229,7 @@ async function verifyFastDownloadSamples(sftp, remoteHandle, localHandle, fileSi const localBuffer = Buffer.allocUnsafe(length); await Promise.race([ (async () => { - await readSftpRange(sftp, remoteHandle, remoteBuffer, position, length); + await readSftpRange(sftp, verificationHandle || remoteHandle, remoteBuffer, position, length); await readLocalRange(localHandle, localBuffer, position, length); if (!remoteBuffer.equals(localBuffer)) { const error = new Error("Transfer source content changed during transfer"); @@ -4240,6 +4264,15 @@ async function verifyFastDownloadSamples(sftp, remoteHandle, localHandle, fileSi transfer.abort = previousAbort; } try { sftp.removeListener?.("error", onVerifyChannelError); } catch { /* ignore */ } + if (verificationHandle) { + const closeResult = await closeSftpHandleBestEffort(sftp, verificationHandle); + if (closeResult.unclean) { + const error = new Error("SFTP verification handle could not be closed"); + error.noTransferFallback = true; + error.uncleanSftpChannel = true; + throw error; + } + } } } @@ -4798,6 +4831,7 @@ async function runPausableConcurrentRanges({ sftp = null, forceSettleOnError = false, }) { + concurrency = getSftpTransferConcurrency(sftp, concurrency); let nextOffset = checkpoint; // Progress may complete out of order, but the resume checkpoint must never // advance past a range that has not durably finished yet. @@ -5043,6 +5077,10 @@ async function uploadFileConcurrent( // Mutable: may shrink after path-gate wait if a stale truncating OPEN wiped // the stage while we were waiting (Codex P2 on 294b7a4b). let checkpoint = Math.max(0, Math.min(transfer.checkpointBytes || 0, fileSize)); + if (getSftpTransferConcurrency(sftp, UPLOAD_TRANSFER_CONCURRENCY) === 1) { + checkpoint = 0; + transfer.checkpointBytes = 0; + } // A fallback strategy may have moved the resume offset. The prefix digest // only matches its own offset; anything else restarts at 0 before OPEN // chooses r+ vs w. Fingerprinted resumes do not consult this digest. @@ -5298,7 +5336,9 @@ async function downloadFileResumableFast( options = {}, ) { const disposeChannel = options.disposeChannel !== false; - const checkpoint = Math.max(0, Math.min(transfer.checkpointBytes || 0, fileSize)); + const sequentialPeer = getSftpTransferConcurrency(sftp, DOWNLOAD_TRANSFER_CONCURRENCY) === 1; + const checkpoint = sequentialPeer ? 0 : Math.max(0, Math.min(transfer.checkpointBytes || 0, fileSize)); + if (sequentialPeer) transfer.checkpointBytes = 0; let channelError = null; const onChannelError = (error) => { channelError = channelError || error; @@ -5355,7 +5395,17 @@ async function downloadFileResumableFast( forceSettleOnError: true, }); if (channelError) throw channelError; - await verifyFastDownloadSamples(sftp, remoteHandle, localHandle, fileSize, transfer); + if (getSftpTransferConcurrency(sftp, DOWNLOAD_TRANSFER_CONCURRENCY) === 1) { + const closeResult = await closeSftpHandleBestEffort(sftp, remoteHandle); + remoteHandle = null; + if (closeResult.unclean) { + const error = new Error("SFTP body handle could not be closed before verification"); + error.noTransferFallback = true; + error.uncleanSftpChannel = true; + throw error; + } + } + await verifyFastDownloadSamples(sftp, remoteHandle, localHandle, fileSize, transfer, remotePath); } catch (error) { failed = true; throw error; @@ -5733,6 +5783,13 @@ async function downloadFile( await finishSuccessfulDownload(); return; } catch (err) { + if (err?.uncleanSftpChannel) { + // Sequential peers may still own an open handle after CLOSE failed. + // Do not hand that cached channel to later browse/transfer work, or + // discard a replacement channel that another operation installed. + if (client.sftp === sftp) abandonWedgedVerificationSftpChannel(client); + throw err; + } if (transfer.cancelled) throw err; // noTransferFallback means "do not keep using this dead channel". // A stale shared browse channel can still recover on one fresh diff --git a/electron/bridges/transferBridge.termSshd.test.cjs b/electron/bridges/transferBridge.termSshd.test.cjs new file mode 100644 index 000000000..f54fc9fc8 --- /dev/null +++ b/electron/bridges/transferBridge.termSshd.test.cjs @@ -0,0 +1,170 @@ +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const crypto = require("node:crypto"); +const { EventEmitter } = require("node:events"); +const transferBridge = require("./transferBridge.cjs"); +const tempDirBridge = require("./tempDirBridge.cjs"); + +async function downloadFromSequentialPeer(t, { corruptVerification = false, closeFailure = null, closeTimeout = false } = {}) { + const payload = crypto.randomBytes(3 * 32768 + 17); + const rewritten = Buffer.from(payload); + rewritten[40000] ^= 0xff; + const target = tempDirBridge.getTempFilePath(`term-sshd-${crypto.randomUUID()}.bin`); + const transferId = crypto.randomUUID(); + const staged = tempDirBridge.getTransferTempFilePath(transferId, path.basename(target)); + t.after(async () => { + await fs.rm(target, { force: true }); + await fs.rm(staged, { force: true }); + }); + const cursors = new Map(); + let opens = 0; + let reads = 0; + let active = 0; + let maxActive = 0; + let ended = 0; + const sftp = new EventEmitter(); + Object.assign(sftp, { + _client: { _remoteVer: "TERM-SSHD" }, + readdir(_p, callback) { callback(null, []); }, + stat(_p, callback) { callback(null, { size: payload.length, mtime: 1 }); }, + mkdir(_p, callback) { callback(null); }, + unlink(_p, callback) { callback(null); }, + open(_p, _flags, callback) { + if (cursors.size) return callback(new Error("General failure: one open handle per channel")); + const handle = Buffer.from(String(++opens)); + cursors.set(handle, 0); + callback(null, handle); + }, + read(handle, buffer, offset, length, _position, callback) { + // Reproduce TERM-SSHD: READ position is ignored; each handle advances. + const cursor = cursors.get(handle); + const source = corruptVerification && Number(handle.toString()) >= 2 ? rewritten : payload; + const count = Math.min(length, source.length - cursor); + source.copy(buffer, offset, cursor, cursor + count); + cursors.set(handle, cursor + count); + reads += count; + maxActive = Math.max(maxActive, ++active); + setImmediate(() => { active--; callback(null, count); }); + }, + close(handle, callback) { + if ((closeFailure === "verification" && opens >= 2) || (closeFailure === "body" && opens === 1)) { + if (closeTimeout) return; + return callback(new Error("General failure")); + } + cursors.delete(handle); callback(null); + }, + end() { ended++; }, + }); + const client = { + sftp, __netcattySingleChannelSsh: true, + stat: async () => ({ size: payload.length, mtime: 1 }), + client: { _remoteVer: "TERM-SSHD", sftp() { throw new Error("No terminal subsystem reuse"); } }, + }; + transferBridge.init({ sftpClients: new Map([["sequential", client]]) }); + const result = await transferBridge.startTransfer({ sender: { send() {} } }, { + transferId, sourcePath: "/source.bin", targetPath: target, + sourceType: "sftp", targetType: "local", sourceSftpId: "sequential", + totalBytes: payload.length, resumable: true, + }); + return { result, target, payload, opens, reads, maxActive, client, sftp, ended }; +} + +test("TERM-SSHD download reopens and verifies the complete file without seeking", async (t) => { + const actual = await downloadFromSequentialPeer(t); + assert.equal(actual.result.error, undefined); + assert.deepEqual(await fs.readFile(actual.target), actual.payload); + assert.ok(actual.opens >= 2, "verification must use a fresh handle"); + assert.ok(actual.reads >= 2 * actual.payload.length, "verify the full file, not just samples"); + assert.equal(actual.maxActive, 1); +}); + +test("TERM-SSHD full verification rejects changed bytes and never publishes the destination", async (t) => { + const actual = await downloadFromSequentialPeer(t, { corruptVerification: true }); + assert.match(actual.result.error || "", /source.*changed/i); + await assert.rejects(fs.stat(actual.target), { code: "ENOENT" }); +}); + +for (const closeFailure of ["body", "verification"]) { + for (const closeTimeout of [false, true]) { + test(`TERM-SSHD ${closeFailure} CLOSE ${closeTimeout ? "timeout" : "failure"} discards the shared channel without publication`, async (t) => { + const actual = await downloadFromSequentialPeer(t, { closeFailure, closeTimeout }); + assert.match(actual.result.error || "", new RegExp(`${closeFailure} handle could not be closed`)); + await assert.rejects(fs.stat(actual.target), { code: "ENOENT" }); + assert.equal(actual.client.sftp, null, "the wedged channel must not remain cached"); + assert.ok(actual.ended > 0, "dispose the uncertain remote handle with its channel"); + await assert.rejects(require("./sftpBridge.cjs").requireSftpChannel(actual.client), /Please reconnect/); + }); + } +} + +for (const corrupt of [false, true]) { + test(`TERM-SSHD uploads verify remote content before promotion (corrupt=${corrupt})`, async (t) => { + const payload = crypto.randomBytes(3 * 32768 + 17); + const source = tempDirBridge.getTempFilePath(`term-upload-${crypto.randomUUID()}.bin`); + await fs.writeFile(source, payload); + t.after(() => fs.rm(source, { force: true })); + const files = new Map(); + const handles = new Map(); + const target = `/target-${crypto.randomUUID()}.bin`; + const sftp = new EventEmitter(); + const missing = () => Object.assign(new Error("ENOENT"), { code: 2 }); + const stats = (p) => { + const data = files.get(String(p)); + if (!data) throw missing(); + return { size: data.length, mode: 0o100644, mtime: 1, isDirectory: () => false, isSymbolicLink: () => false }; + }; + Object.assign(sftp, { + _client: { _remoteVer: "TERM-SSHD" }, + readdir(_p, cb) { cb(null, []); }, mkdir(_p, cb) { cb(null); }, + stat(p, cb) { try { cb(null, stats(p)); } catch (err) { cb(err); } }, + lstat(p, cb) { try { cb(null, stats(p)); } catch (err) { cb(err); } }, + unlink(p, cb) { files.delete(String(p)); cb(null); }, + chmod(_p, _mode, cb) { cb(null); }, + open(p, flags, cb) { + const name = String(p); + if (flags === "w") files.set(name, Buffer.alloc(payload.length)); + const handle = Buffer.from(crypto.randomUUID()); + handles.set(handle, { name, cursor: 0 }); cb(null, handle); + }, + write(handle, buffer, offset, length, _position, cb) { + const h = handles.get(handle); + const data = files.get(h.name); + buffer.copy(data, h.cursor, offset, offset + length); + if (corrupt && h.cursor <= 40000 && h.cursor + length > 40000) data[40000] ^= 0xff; + h.cursor += length; setImmediate(() => cb(null)); + }, + read(handle, buffer, offset, length, _position, cb) { + const h = handles.get(handle); const data = files.get(h.name); + const count = Math.min(length, data.length - h.cursor); + data.copy(buffer, offset, h.cursor, h.cursor + count); h.cursor += count; + setImmediate(() => cb(null, count)); + }, + close(handle, cb) { handles.delete(handle); cb(null); }, + end() {}, + }); + const client = { + sftp, __netcattySingleChannelSsh: true, + stat: async (p) => stats(p), + rename: async (from, to) => { files.set(String(to), files.get(String(from))); files.delete(String(from)); }, + delete: async (p) => { files.delete(String(p)); }, + client: { _remoteVer: "TERM-SSHD", sftp() { throw new Error("No terminal subsystem reuse"); } }, + }; + transferBridge.init({ sftpClients: new Map([["sequential", client]]) }); + const result = await transferBridge.startTransfer({ sender: { send() {} } }, { + transferId: crypto.randomUUID(), sourcePath: source, targetPath: target, + sourceType: "local", targetType: "sftp", targetSftpId: "sequential", + totalBytes: payload.length, resumable: true, + }); + if (corrupt) { + assert.match(result.error || "", /content verification failed/i); + assert.equal(files.has(target), false, "corrupt stage must never be promoted"); + } else { + assert.equal(result.error, undefined); + assert.deepEqual(files.get(target), payload); + } + }); +} diff --git a/electron/bridges/transferLimits.cjs b/electron/bridges/transferLimits.cjs index 4fb1f8ec7..d7f419830 100644 --- a/electron/bridges/transferLimits.cjs +++ b/electron/bridges/transferLimits.cjs @@ -15,6 +15,17 @@ const UPLOAD_TRANSFER_CONCURRENCY = 64; // ssh2's fastGet default and, with the safe 32KB request size, restores the 2MB // in-flight window Netcatty used before the shared chunk-size fix in #2030. const DOWNLOAD_TRANSFER_CONCURRENCY = 64; + +// TERM-SSHD gateways can acknowledge concurrent WRITEs with misplaced data +// and return premature EOF for concurrent READs. Keep the normal window for +// other peers; this is a per-file request limit, not a global transfer limit. +function getSftpTransferConcurrency(sftp, requested) { + const software = sftp?._client?._remoteVer; + return typeof software === "string" + && /^(?:SSH-2\.0-)?TERM-SSHD(?:[_-][0-9].*)?$/i.test(software) + ? 1 + : requested; +} // Prefix verification must fail closed when a server stops answering, but allow // slow links to make progress without imposing a whole-transfer deadline. const SFTP_OPEN_TIMEOUT_MS = 15_000; @@ -51,4 +62,5 @@ module.exports = { SFTP_REQUEST_TIMEOUT_MS, TRANSFER_CHUNK_SIZE, UPLOAD_TRANSFER_CONCURRENCY, + getSftpTransferConcurrency, }; diff --git a/electron/bridges/transferLimits.test.cjs b/electron/bridges/transferLimits.test.cjs index 2c5e29c44..77e6b3149 100644 --- a/electron/bridges/transferLimits.test.cjs +++ b/electron/bridges/transferLimits.test.cjs @@ -8,8 +8,23 @@ const { SMALL_UPLOAD_SHARED_MAX_BYTES, UPLOAD_TRANSFER_CONCURRENCY, TRANSFER_CHUNK_SIZE, + getSftpTransferConcurrency, } = require("./transferLimits.cjs"); +test("TERM-SSHD SFTP requests use one in-flight range to preserve file contents", () => { + for (const software of ["TERM-SSHD", "term-sshd", "TERM-SSHD_1.0"]) { + assert.equal(getSftpTransferConcurrency({ _client: { _remoteVer: software } }, 64), 1); + } +}); + +test("the TERM-SSHD request policy does not slow other SSH peers or change chunk sizes", () => { + for (const software of ["OpenSSH_9.6", "JumpServer", "BHostSSH_7.0", "my-term-sshd-proxy"]) { + assert.equal(getSftpTransferConcurrency({ _client: { _remoteVer: software } }, 64), 64); + } + assert.equal(getSftpTransferConcurrency({}, 8), 8); + assert.equal(TRANSFER_CHUNK_SIZE, 32 * 1024); +}); + test("SFTP transfer limits preserve upload safety and the pre-regression download window", () => { assert.equal(UPLOAD_TRANSFER_CONCURRENCY, 64); assert.equal(DOWNLOAD_TRANSFER_CONCURRENCY, 64);