Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(windows): validate ProxyCommand token values and kill the proxy tree on Windows

review2cf062a8c4f4
diff --git a/CLAUDE.md b/CLAUDE.md
index a662c3448..0537ad425 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8486,12 +8486,18 @@ unix-socket forward and dev-server `-L` forward over it. POSIX keeps OpenSSH unt
**ProxyCommand** (`proxy-command.ts`) runs on the target or the FIRST hop, as OpenSSH does:
`%h %p %r %n %k %%` expanded (an unknown `%x` is an error by name), POSIX `sh -c 'exec …'`,
Windows `cmd.exe /d /s /c`, the child's stdio is the socket, its stderr is in the connect error,
- ConnectTimeout covers the wait for its first byte, and it is killed with the connection.
+ ConnectTimeout covers the wait for its first byte, and it is killed with the connection (on
+ Windows as a TREE, `taskkill /t /f` — the proxy is cmd.exe's child, and killing cmd.exe alone
+ orphans it). Every substituted VALUE (`%h %r %n %k`) is refused if it carries a shell/cmd
+ metacharacter or a leading `-`: the line goes to `sh -c` / `cmd.exe /c`, and Windows' OpenSSH
+ (9.5) predates the CVE-2023-51385 host/user check.
`ProxyUseFdpass yes` is refused by name. ProxyJump wins when `ssh -G` prints both.
- **Other honored `~/.ssh/config` options:** `ForwardAgent` (yes / path / `$VAR`) — requested on
- the TARGET connection's PTY channels only, never on a hop or a background exec/SFTP channel (that
- would hand the agent to every status probe), and a server that refuses it costs one log line, not
- the terminal. Options it does NOT honor (`certificatefile`, config `Local/Remote/DynamicForward`)
+ the TARGET connection's PTY channels only, never on a hop or a background exec/SFTP channel, and
+ a server that refuses it costs one log line, not the terminal. Note what that does NOT buy: sshd
+ creates the agent socket once per CONNECTION, so after the first terminal asks, later sessions on
+ that shared connection (background execs included) also see `SSH_AUTH_SOCK` — exactly what an
+ OpenSSH ControlMaster does. Do not document it as "background calls never get the agent". Options it does NOT honor (`certificatefile`, config `Local/Remote/DynamicForward`)
are named in ONE warning per connection (`UNSUPPORTED_OPTIONS`), never silently dropped; user and
`@cert-authority` certificates are a later phase.
- **`-L` dev-server forwards** (`NativeMux.forwardLocal`): the parser accepts ONLY the loopback spec
diff --git a/src/core/remote-ssh/native/proxy-command.test.ts b/src/core/remote-ssh/native/proxy-command.test.ts
index f7aa8c352..03a0d3a3c 100644
--- a/src/core/remote-ssh/native/proxy-command.test.ts
+++ b/src/core/remote-ssh/native/proxy-command.test.ts
@@ -18,6 +18,21 @@ describe('expandProxyTokens', () => {
it('%k is HostKeyAlias when one is set', () => {
expect(expandProxyTokens('x %k', { ...T, hostKeyAlias: 'alias' })).toBe('x alias')
})
+ it.each([
+ ['%h', { hostname: 'a&calc' }],
+ ['%h', { hostname: 'a;rm -rf ~' }],
+ ['%n', { originalHost: 'box|x' }],
+ ['%n', { originalHost: '$(id)' }],
+ ['%r', { user: 'dev`id`' }],
+ ['%r', { user: '-oProxyCommand=x' }],
+ ['%k', { hostKeyAlias: 'a^b' }],
+ ['%h', { hostname: '100%x' }]
+ ])('a %s value carrying a shell/cmd metacharacter is refused, never interpolated', (tok, over) => {
+ expect(() => expandProxyTokens(`nc ${tok} %p`, { ...T, ...over })).toThrow(/not allowed in a host or user name/)
+ })
+ it('ordinary values (IPv6, dotted names, user with dot/underscore) still expand', () => {
+ expect(expandProxyTokens('nc %h %p %r', { ...T, hostname: 'fe80::1', user: 'first.last_x' })).toBe('nc fe80::1 2222 first.last_x')
+ })
it('an unknown token is an error by name, never passed through', () => {
expect(() => expandProxyTokens('nc %h %C', T)).toThrow(/unknown token %C/)
expect(() => expandProxyTokens('trailing %', T)).toThrow(/unknown token %/)
@@ -106,6 +121,30 @@ describe('proxyCommandSocket', () => {
await exited
})
+ it('Windows: destroying the stream kills the whole TREE (cmd.exe and the proxy under it)', async () => {
+ const children: import('child_process').ChildProcess[] = []
+ const killed: number[] = []
+ const sock = proxyCommandSocket('x', {
+ timeoutMs: 5000,
+ platform: 'win32',
+ env: { ComSpec: 'cmd.exe' },
+ killTree: (pid) => {
+ killed.push(pid)
+ children[0].kill()
+ },
+ spawn: (f, a, o) => {
+ const c = nodeSpawn(`process.stdout.write('SSH-2.0-x\\r\\n');setInterval(()=>{},1000)`)(f, a, o)
+ children.push(c)
+ return c
+ }
+ })
+ await new Promise((r) => sock.once('data', r))
+ const exited = new Promise((r) => children[0].once('exit', r))
+ sock.destroy()
+ await exited
+ expect(killed).toEqual([children[0].pid])
+ })
+
it('a spawn that fails is an error, not a hang', async () => {
const sock = proxyCommandSocket('x', {
timeoutMs: 5000,
diff --git a/src/core/remote-ssh/native/proxy-command.ts b/src/core/remote-ssh/native/proxy-command.ts
index dd25d6d60..d49ed2c6c 100644
--- a/src/core/remote-ssh/native/proxy-command.ts
+++ b/src/core/remote-ssh/native/proxy-command.ts
@@ -10,7 +10,7 @@
// `ProxyUseFdpass yes` (the proxy hands back a connected fd over a unix socket) cannot be served
// from Node and is refused by name by the caller.
-import { spawn as nodeSpawn, type ChildProcess } from 'child_process'
+import { execFile, spawn as nodeSpawn, type ChildProcess } from 'child_process'
import { Duplex } from 'stream'
/** The values OpenSSH substitutes into a ProxyCommand (sshconnect.c `expand_proxy_command`). */
@@ -27,22 +27,37 @@ export interface ProxyTokens {
hostKeyAlias?: string
}
-/** Expand `%h %p %r %n %k %%`; throws on any other `%x`, naming it. */
+/**
+ * Characters a substituted VALUE may not carry: the expanded line is handed to `/bin/sh -c` or
+ * `cmd.exe /c`, so a host or user holding a shell or cmd metacharacter would run as a command.
+ * OpenSSH >= 9.6 refuses the same class for user/host (CVE-2023-51385); Windows ships 9.5, and the
+ * no-binary path never asks OpenSSH at all — so the check lives here, at the interpolation site.
+ */
+const UNSAFE_TOKEN_VALUE = /[\s'"`$\\;&<>|(){}^%!*?[\]\x00-\x1f\x7f]/
+
+function safeValue(k: string, v: string): string {
+ if (!v || v.startsWith('-') || UNSAFE_TOKEN_VALUE.test(v)) {
+ throw new Error(`ssh: ProxyCommand: %${k} value ${JSON.stringify(v)} contains characters that are not allowed in a host or user name`)
+ }
+ return v
+}
+
+/** Expand `%h %p %r %n %k %%`; throws on any other `%x`, naming it, and on an unsafe value. */
export function expandProxyTokens(cmd: string, t: ProxyTokens): string {
return cmd.replace(/%(.?)/g, (_m, k: string) => {
switch (k) {
case '%':
return '%'
case 'h':
- return t.hostname
+ return safeValue(k, t.hostname)
case 'p':
return String(t.port)
case 'r':
- return t.user
+ return safeValue(k, t.user)
case 'n':
- return t.originalHost
+ return safeValue(k, t.originalHost)
case 'k':
- return t.hostKeyAlias ?? t.originalHost
+ return safeValue(k, t.hostKeyAlias ?? t.originalHost)
default:
throw new Error(`ssh: ProxyCommand: unknown token %${k} in "${cmd}"`)
}
@@ -68,6 +83,13 @@ export type ProxySpawn = (file: string, args: string[], opts: { verbatim: boolea
const defaultSpawn: ProxySpawn = (file, args, opts) =>
nodeSpawn(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, windowsVerbatimArguments: opts.verbatim })
+/** `taskkill /t /f` — the same tree kill project-setup-runner-local.ts uses. Best-effort. */
+function defaultKillTree(pid: number): void {
+ execFile('taskkill', ['/pid', String(pid), '/t', '/f'], { windowsHide: true }, () => {
+ // ENOENT / "not found": it already exited.
+ })
+}
+
/** How much of the proxy's stderr is kept for an error message. */
const STDERR_KEEP = 4096
@@ -79,14 +101,29 @@ const STDERR_KEEP = 4096
*/
export function proxyCommandSocket(
cmd: string,
- opts: { timeoutMs: number; platform?: NodeJS.Platform; spawn?: ProxySpawn; env?: NodeJS.ProcessEnv }
+ opts: {
+ timeoutMs: number
+ platform?: NodeJS.Platform
+ spawn?: ProxySpawn
+ env?: NodeJS.ProcessEnv
+ /** Test seam: kill a Windows process TREE by pid (default `taskkill /pid <pid> /t /f`). */
+ killTree?: (pid: number) => void
+ }
): Duplex {
- const { file, args, verbatim } = proxyCommandArgv(cmd, opts.platform, opts.env)
+ const platform = opts.platform ?? process.platform
+ const { file, args, verbatim } = proxyCommandArgv(cmd, platform, opts.env)
let stderr = ''
let gotData = false
let child: ChildProcess | null = null
const kill = (): void => {
- if (child && child.exitCode === null && child.signalCode === null) child.kill()
+ if (!child || child.exitCode !== null || child.signalCode !== null) return
+ // Windows: the child is cmd.exe, and the proxy (ncat, ssh -W, …) is ITS child — killing cmd.exe
+ // alone orphans the proxy holding the connection. POSIX needs no tree: `exec` replaced the sh.
+ if (platform === 'win32' && child.pid) {
+ ;(opts.killTree ?? defaultKillTree)(child.pid)
+ return
+ }
+ child.kill()
}
const why = (msg: string): Error => {
const tail = stderr.trim().split(/\r?\n/).pop()