Skip to content

The agent that grows with you

fix: keep desktop SSH control sockets short under deep homes

etherneta25271828434
diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.ts
index 5696f601e6e..0effe1663a6 100644
--- a/apps/desktop/electron/ssh-connection.test.ts
+++ b/apps/desktop/electron/ssh-connection.test.ts
@@ -109,6 +109,45 @@ test('controlSocketPath default base stays under sun_path even with the temp-lis
assert.ok(!p.includes('/var/folders/'), 'default base must not be os.tmpdir() on macOS')
})
+test.runIf(process.platform !== 'win32')(
+ 'deep HOME uses a private short directory and binds a real listener',
+ async () => {
+ const previousHome = process.env.HOME
+ process.env.HOME = path.join(os.tmpdir(), 'deep-home-' + 'x'.repeat(110))
+ const net = await import('node:net')
+ const listener = net.createServer()
+
+ try {
+ const spawnFn = scriptedSpawn(args => (args.includes('check') ? { code: 255 } : { code: 0 }))
+ const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: true })
+ assert.equal(conn.controlPath, controlSocketPath('me', 'box', 22))
+ assert.ok(!conn.controlPath.startsWith(process.env.HOME))
+ await conn.open()
+ const dir = path.dirname(conn.controlPath)
+ const st = fs.lstatSync(dir)
+ assert.ok(st.isDirectory() && !st.isSymbolicLink())
+ assert.equal(st.uid, process.getuid())
+ assert.equal(st.mode & 0o777, 0o700)
+ const temporaryPath = `${conn.controlPath}.0123456789abcdef`
+ assert.ok(Buffer.byteLength(temporaryPath) <= 104)
+ await new Promise<void>((resolve, reject) => {
+ listener.once('error', reject)
+ listener.listen(temporaryPath, resolve)
+ })
+ } finally {
+ if (previousHome === undefined) {
+ delete process.env.HOME
+ } else {
+ process.env.HOME = previousHome
+ }
+
+ if (listener.listening) {
+ await new Promise<void>((resolve, reject) => listener.close(error => (error ? reject(error) : resolve())))
+ }
+ }
+ }
+)
+
test('baseSshOptions carries the house ControlMaster/BatchMode/accept-new policy', () => {
const opts = baseSshOptions('/tmp/x.sock', 15000)
const joined = opts.join(' ')
@@ -552,6 +591,7 @@ test('mux open() does not classify a signal-killed master with empty stderr as u
return { signal: 'SIGHUP', stderr: '' }
})
+
const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, controlDir: '/tmp/d' })
await assert.rejects(() => conn.open(), (err: any) => assertSignalDeathNotUnreachable(err, 'SIGHUP'))
@@ -573,6 +613,7 @@ test('forward() does not classify a signal death with empty stderr as unreachabl
test('close() does not report a signal-killed -O exit with empty stderr as unreachable', async () => {
const logs: string[] = []
+
const spawnFn = scriptedSpawn(args => {
if (args.includes('check')) {
return { code: 255 }
@@ -584,6 +625,7 @@ test('close() does not report a signal-killed -O exit with empty stderr as unrea
return { signal: 'SIGINT', stderr: '' }
})
+
const conn = new SshConnection(
{ host: 'box', user: 'me' },
{ spawnFn, controlDir: '/tmp/d', rememberLog: line => logs.push(line) }
@@ -619,6 +661,7 @@ test('a signal death that already printed an unreachable ssh error stays unreach
stderr: 'ssh: connect to host box port 22: Connection refused'
}
])
+
const conn = new SshConnection({ host: 'box', user: 'me' }, { spawnFn, mux: false })
await assert.rejects(
diff --git a/apps/desktop/electron/ssh-connection.ts b/apps/desktop/electron/ssh-connection.ts
index 42385dfb405..ac324f2e432 100644
--- a/apps/desktop/electron/ssh-connection.ts
+++ b/apps/desktop/electron/ssh-connection.ts
@@ -173,12 +173,9 @@ function redactSecrets(text) {
// across reconnects so ControlMaster reuse works, short so the full path stays
// under sun_path's 104-byte limit.
//
-// CRITICAL (macOS): the base dir must be SHORT. os.tmpdir() on macOS is the
-// per-user `/var/folders/xx/yyyy…/T/` (~49 bytes), and OpenSSH binds a
-// TEMPORARY listener at `<ControlPath>.<16 random chars>` while establishing
-// the master — so a path that itself fits 104 still overflows at bind time. We
-// root under a short per-user base (`~/.hermes/desktop-ssh`) so even worst case
-// (~72 bytes on macOS) stays clear. Windows has no AF_UNIX sun_path limit.
+// OpenSSH binds a temporary listener at `<ControlPath>.<16 random chars>`.
+// The home (and macOS's os.tmpdir()) can be too deep even when the socket
+// itself fits sun_path. Windows has no AF_UNIX sun_path limit.
function controlSocketPath(user, host, port, baseDir?, identity: any = {}) {
const dir = baseDir || defaultControlDir()
const keyPathIdentity = path.normalize(String(identity.keyPath || ''))
@@ -198,14 +195,35 @@ function controlSocketPath(user, host, port, baseDir?, identity: any = {}) {
return path.join(dir, `${id}.sock`)
}
+function shortControlDir(): string {
+ return `/tmp/hermes-ssh-${process.getuid!()}`
+}
+
function defaultControlDir(): string {
- // POSIX: a SHORT, PER-USER base stays under the socket limit AND avoids a
- // world-shared /tmp dir (no symlink-hijack surface). Created 0700 in open().
if (process.platform === 'win32') {
return path.join(os.tmpdir(), 'hermes-desktop-ssh')
}
- return path.join(platformDefaultHermesHome(os.homedir()), 'desktop-ssh')
+ const homeDir = path.join(platformDefaultHermesHome(os.homedir()), 'desktop-ssh')
+
+ // Include the filename and OpenSSH's temporary-listener suffix in the byte budget.
+ return Buffer.byteLength(path.join(homeDir, '0123456789abcdef.sock.0123456789abcdef')) <= 104
+ ? homeDir
+ : shortControlDir()
+}
+
+function checkShortControlParent(): void {
+ // /tmp can be a symlink on macOS. Inspect its resolved directory before
+ // creating anything there; the sticky bit protects an owned child from rename.
+ const st = fs.statSync(fs.realpathSync('/tmp'))
+
+ if (
+ !st.isDirectory() ||
+ (st.uid !== 0 && st.uid !== process.getuid!()) ||
+ ((st.mode & 0o022) !== 0 && (st.mode & 0o1000) === 0)
+ ) {
+ throw new Error('Unsafe SSH control parent: /tmp must be owned by root or this user and sticky if writable.')
+ }
}
// Command construction (pure — the unit tests exercise these directly)
@@ -720,6 +738,28 @@ class SshConnection {
// a live master is a no-op). No-mux: there is no master; validate auth +
// reachability with a one-shot `ssh true` so failures classify identically.
async open({ signal }: any = {}) {
+ if (this._mux) {
+ const controlDir = path.dirname(this.controlPath)
+
+ if (process.platform !== 'win32' && controlDir === shortControlDir()) {
+ checkShortControlParent()
+ }
+
+ fs.mkdirSync(controlDir, { recursive: true, mode: 0o700 })
+
+ if (process.platform !== 'win32') {
+ const st = fs.lstatSync(controlDir)
+
+ if (st.isSymbolicLink() || !st.isDirectory() || st.uid !== process.getuid!()) {
+ throw new Error(`Unsafe SSH control dir: ${controlDir} is not a directory owned by this user (no symlinks).`)
+ }
+
+ if ((st.mode & 0o777) !== 0o700) {
+ fs.chmodSync(controlDir, 0o700)
+ }
+ }
+ }
+
if (await this.isAlive({ signal })) {
// -O check passing is not proof the master works: a ControlPersist master
// can survive a failed teardown with wedged channels (observed on macOS
@@ -759,34 +799,6 @@ class SshConnection {
return
}
- const controlDir = path.dirname(this.controlPath)
-
- try {
- fs.mkdirSync(controlDir, { recursive: true, mode: 0o700 })
- } catch {
- void 0
- }
-
- if (process.platform !== 'win32') {
- const st = fs.lstatSync(controlDir)
-
- if (st.isSymbolicLink()) {
- throw new Error(`Unsafe SSH control dir: ${controlDir} is a symlink.`)
- }
-
- if (!st.isDirectory()) {
- throw new Error(`Unsafe SSH control dir: ${controlDir} is not a directory.`)
- }
-
- if (st.uid !== process.getuid!()) {
- throw new Error(`Unsafe SSH control dir: ${controlDir} is owned by uid ${st.uid}, not ${process.getuid!()}.`)
- }
-
- if ((st.mode & 0o777) !== 0o700) {
- fs.chmodSync(controlDir, 0o700)
- }
- }
-
const args = buildMasterArgs(this, this._connectTimeoutMs)
this._logLine(`opening control master to ${target(this.user, this.host)}:${this.port}`)
let result