import { execFileSync } from 'node:child_process'; import fs from 'node:fs'; import net from 'node:net'; import os from 'node:os'; import path from 'node:path'; import ssh2, { type Attributes, type Connection, type Server } from 'ssh2'; import { computeOpenSshFingerprint, generateValidEd25519KeyPair, } from '../../src/server/security/vault.js'; export interface MockSshOptions { username: string; password?: string; sudoPassword?: string; os?: 'Linux' | 'FreeBSD' | 'Darwin'; authorizedKeys?: string[]; allowTcpForward?: boolean; sftpRootDir?: string; onExec?: ( command: string, stdin: string, ) => { stdout: string; stderr?: string; exitCode: number } | null; } function unquoteSinglePosix(quoted: string): string { const s = quoted.trim(); if (s.startsWith("'") && s.endsWith("'")) { return s.slice(1, -1).replace(/'\\''/g, "'"); } return s; } function toSftpAttrs(st: fs.Stats): Attributes { return { mode: st.mode, uid: st.uid, gid: st.gid, size: st.size, atime: Math.floor(st.atimeMs / 1000), mtime: Math.floor(st.mtimeMs / 1000), }; } function mapSftpFlags(flags: number): number { const M = ssh2.utils.sftp.OPEN_MODE; const read = (flags & M.READ) !== 0; const write = (flags & M.WRITE) !== 0; let out = read && write ? fs.constants.O_RDWR : write ? fs.constants.O_WRONLY : fs.constants.O_RDONLY; if ((flags & M.CREAT) !== 0) out |= fs.constants.O_CREAT; if ((flags & M.TRUNC) !== 0) out |= fs.constants.O_TRUNC; if ((flags & M.APPEND) !== 0) out |= fs.constants.O_APPEND; if ((flags & M.EXCL) !== 0) out |= fs.constants.O_EXCL; return out; } export class MockSshServer { public port = 0; public hostFingerprint = ''; public authorizedKeys: string[]; public pollCount = 0; public lastSudoStdin = ''; public lastPtySize: { cols: number; rows: number } | null = null; public ptyCount = 0; public readonly sftpRootDir: string; private readonly ownsSftpRoot: boolean; private hostPrivateKey: string; private server: Server | null = null; private readonly activeConns = new Set(); private readonly remoteForwarders = new Map(); constructor(public readonly options: MockSshOptions) { this.authorizedKeys = [...(options.authorizedKeys ?? [])]; if (options.sftpRootDir) { this.sftpRootDir = path.resolve(options.sftpRootDir); fs.mkdirSync(this.sftpRootDir, { recursive: true }); this.ownsSftpRoot = false; } else { this.sftpRootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mock-ssh-sftp-')); this.ownsSftpRoot = true; } const kp = generateValidEd25519KeyPair({ comment: 'mock-host' }); this.hostPrivateKey = kp.privateKey; this.hostFingerprint = kp.fingerprint; } private resolveVirtualPath(vPath: string): { normPosix: string; absPath: string } { const trimmed = vPath.trim(); let candidate = trimmed; if (!candidate || candidate === '.' || candidate === '~') { candidate = '/'; } else if (candidate.startsWith('~/')) { candidate = `/${candidate.slice(2)}`; } else if (!candidate.startsWith('/')) { candidate = `/${candidate}`; } const normPosix = path.posix.normalize(candidate); const rel = normPosix === '/' ? '' : normPosix.slice(1); const absPath = path.resolve(this.sftpRootDir, rel); if ( absPath !== this.sftpRootDir && !absPath.startsWith(`${this.sftpRootDir}${path.sep}`) ) { throw new Error(`Path escapes SFTP root: ${vPath}`); } return { normPosix, absPath }; } async start(listenPort = 0): Promise { if (this.server) return this.port; const srv = new ssh2.Server( { hostKeys: [this.hostPrivateKey] }, (client) => this.handleClient(client), ); await new Promise((resolve, reject) => { srv.once('error', reject); srv.listen(listenPort, '127.0.0.1', () => { srv.off('error', reject); resolve(); }); }); this.server = srv; const addr = srv.address(); this.port = typeof addr === 'object' && addr ? addr.port : listenPort; return this.port; } async swapHostKey(): Promise { const prevPort = this.port; await this.close(); const kp = generateValidEd25519KeyPair({ comment: 'mitm-host' }); this.hostPrivateKey = kp.privateKey; this.hostFingerprint = kp.fingerprint; await this.start(prevPort); return this.hostFingerprint; } async close(): Promise { for (const srv of this.remoteForwarders.values()) { try { srv.close(); } catch { // Ignore close errors } } this.remoteForwarders.clear(); for (const c of this.activeConns) { try { c.end(); } catch { // Ignore close errors } } this.activeConns.clear(); if (this.server) { const s = this.server; this.server = null; await new Promise((resolve) => s.close(() => resolve())); } if (this.ownsSftpRoot) { fs.rmSync(this.sftpRootDir, { recursive: true, force: true }); } } get activeConnectionCount(): number { return this.activeConns.size; } private handleClient(client: Connection): void { this.activeConns.add(client); client.on('close', () => { this.activeConns.delete(client); }); client.on('error', () => { this.activeConns.delete(client); }); client.on('authentication', (ctx) => { if (ctx.username !== this.options.username) { ctx.reject(['publickey', 'password']); return; } if (ctx.method === 'password' && this.options.password) { if (ctx.password === this.options.password) { ctx.accept(); return; } ctx.reject(['publickey', 'password']); return; } if (ctx.method === 'publickey') { for (const line of this.authorizedKeys) { const parsed = ssh2.utils.parseKey(line.trim()); if (parsed instanceof Error || Array.isArray(parsed)) continue; if ( ctx.key.algo === parsed.type && ctx.key.data.equals(parsed.getPublicSSH()) ) { if (!ctx.signature) { ctx.accept(); return; } if ( ctx.blob && parsed.verify(ctx.blob, ctx.signature, ctx.hashAlgo) === true ) { ctx.accept(); return; } } } ctx.reject(['publickey', 'password']); return; } ctx.reject(['publickey', 'password']); }); client.on('ready', () => { client.on('tcpip', (accept, reject, info) => { if (this.options.allowTcpForward === false) { reject(); return; } const upstream = net.connect(info.destPort, info.destIP, () => { const channel = accept(); channel.pipe(upstream).pipe(channel); channel.on('close', () => upstream.destroy()); upstream.on('close', () => channel.destroy()); }); upstream.on('error', () => { reject(); }); }); (client as unknown as NodeJS.EventEmitter).on( 'request', ( accept: ((port?: number) => void) | undefined, reject: (() => void) | undefined, name: string, info: { bindAddr: string; bindPort: number }, ) => { if (name === 'tcpip-forward') { if (this.options.allowTcpForward === false) { reject?.(); return; } const fwdSrv = net.createServer((sock) => { const addr = fwdSrv.address(); const boundPort = typeof addr === 'object' && addr ? addr.port : info.bindPort; client.forwardOut( info.bindAddr, boundPort, sock.remoteAddress ?? '127.0.0.1', sock.remotePort ?? 0, (err, channel) => { if (err) { sock.destroy(); return; } sock.pipe(channel); channel.pipe(sock); sock.on('close', () => channel.destroy()); channel.on('close', () => sock.destroy()); }, ); }); fwdSrv.listen(info.bindPort || 0, '127.0.0.1', () => { const addr = fwdSrv.address(); const chosenPort = typeof addr === 'object' && addr ? addr.port : info.bindPort; this.remoteForwarders.set(`${info.bindAddr}:${chosenPort}`, fwdSrv); accept?.(chosenPort); }); return; } if (name === 'cancel-tcpip-forward') { const key = `${info.bindAddr}:${info.bindPort}`; const fwdSrv = this.remoteForwarders.get(key); if (fwdSrv) { this.remoteForwarders.delete(key); fwdSrv.close(() => accept?.()); } else { accept?.(); } } }, ); client.on('session', (accept) => { const session = accept(); session.on('pty', (acceptPty, _rejectPty, info) => { this.lastPtySize = { cols: info.cols, rows: info.rows }; acceptPty?.(); }); session.on('window-change', (acceptWin, _rejectWin, info) => { this.lastPtySize = { cols: info.cols, rows: info.rows }; acceptWin?.(); }); session.on('shell', (acceptShell) => { this.ptyCount += 1; const stream = acceptShell(); let cwd = '/'; let lineBuf = ''; stream.write('\x1b[32mmock$\x1b[0m '); stream.on('data', (chunk: Buffer) => { const text = chunk.toString('utf8'); for (const ch of text) { if (ch === '\x03') { lineBuf = ''; stream.write('^C\r\n\x1b[32mmock$\x1b[0m '); continue; } if (ch === '\r' || ch === '\n') { const cmd = lineBuf.trim(); lineBuf = ''; stream.write('\r\n'); if (cmd === 'exit') { stream.exit(0); stream.end(); return; } if (cmd === 'pwd') { stream.write(`${cwd}\r\n`); } else if (cmd.startsWith('cd ')) { const rawArg = unquoteSinglePosix(cmd.slice(3).replace(/^--\s+/, '').trim()); cwd = rawArg.startsWith('/') ? path.posix.normalize(rawArg) : path.posix.normalize(path.posix.join(cwd, rawArg)); } else if (cmd.startsWith('echo ')) { stream.write(`${cmd.slice(5)}\r\n`); } else if (cmd) { stream.write(`ran:${cmd}\r\n`); } stream.write('\x1b[32mmock$\x1b[0m '); continue; } lineBuf += ch; stream.write(ch); } }); }); session.on('sftp', (acceptSftp) => { this.attachSftpServer(acceptSftp()); }); session.on('exec', (acceptExec, _rejectExec, info) => { const stream = acceptExec(); const stdinChunks: Buffer[] = []; let finished = false; const finishExec = () => { if (finished) return; finished = true; const stdinText = Buffer.concat(stdinChunks).toString('utf8'); const binaryResult = this.evaluateBinaryCommand(info.command); if (binaryResult) { if (!stream.writable || stream.writableEnded) return; if (binaryResult.stdout.length > 0) stream.write(binaryResult.stdout); if (binaryResult.stderr && stream.stderr.writable && !stream.stderr.writableEnded) { stream.stderr.write(binaryResult.stderr); } stream.exit(binaryResult.exitCode); stream.end(); return; } const result = this.evaluateCommand(info.command, stdinText); if (!stream.writable || stream.writableEnded) return; if (result.stdout) stream.write(result.stdout); if (result.stderr && stream.stderr.writable && !stream.stderr.writableEnded) { stream.stderr.write(result.stderr); } stream.exit(result.exitCode); stream.end(); }; stream.on('data', (chunk: Buffer) => { stdinChunks.push(chunk); }); stream.on('end', finishExec); // When pty is allocated on exec (e.g. interactive debug-shell), client keeps stdin open until command exits setTimeout(() => { if (!finished && stdinChunks.length === 0) { finishExec(); } }, 15); }); }); }); } private evaluateCommand( rawCommand: string, rawStdin: string, ): { stdout: string; stderr?: string; exitCode: number } { let command = rawCommand.trim(); let stdin = rawStdin; // Handle sudo wrappers produced by prepareSudoExecution if (command.startsWith("sudo -S -p '' sh -c ")) { const nl = stdin.indexOf('\n'); const suppliedPw = nl >= 0 ? stdin.slice(0, nl) : stdin; this.lastSudoStdin = suppliedPw; stdin = nl >= 0 ? stdin.slice(nl + 1) : ''; if (this.options.sudoPassword && suppliedPw !== this.options.sudoPassword) { return { stdout: '', stderr: 'sudo: incorrect password', exitCode: 1 }; } command = unquoteSinglePosix(command.slice("sudo -S -p '' sh -c ".length)); } else if (command.startsWith('sudo -n sh -c ')) { command = unquoteSinglePosix(command.slice('sudo -n sh -c '.length)); } if (this.options.onExec) { const custom = this.options.onExec(command, stdin); if (custom) return custom; } if (command === 'echo gcoord-key-ok') { return { stdout: 'gcoord-key-ok\n', exitCode: 0 }; } if (command === 'uname -s') { return { stdout: `${this.options.os ?? 'Linux'}\n`, exitCode: 0 }; } if (command.includes('cat ~/.ssh/authorized_keys')) { const body = this.authorizedKeys.length > 0 ? `${this.authorizedKeys.join('\n')}\n` : ''; return { stdout: body, exitCode: 0 }; } if (command.includes('mv ~/.ssh/authorized_keys.gcoord.tmp')) { this.authorizedKeys = stdin .split(/\r?\n/) .map((l) => l.trim()) .filter(Boolean); return { stdout: '', exitCode: 0 }; } // Metrics commands if (command.includes('===STAT===')) { this.pollCount += 1; const busy = 1000 + this.pollCount * 150; const idle = 9000 + this.pollCount * 850; const rx = 100_000 + this.pollCount * 25_000; const tx = 50_000 + this.pollCount * 10_000; const stdout = [ '===STAT===', `cpu ${busy} 0 100 ${idle} 50 0 0 0 0 0`, '===MEM===', 'MemTotal: 16384000 kB', 'MemAvailable: 10240000 kB', '===LOAD===', '0.42 0.35 0.28 1/200 1234', '===UPTIME===', '86400.50 172000.00', '===NET===', 'Inter-| Receive | Transmit', ' face |bytes packets errs drop fifo frame compressed multicast|bytes packets', ' lo: 999999 100 0 0 0 0 0 0 999999 100', ` eth0: ${rx} 500 0 0 0 0 0 0 ${tx} 400`, '===DF===', 'Filesystem Type 1024-blocks Used Available Capacity Mounted on', 'tmpfs tmpfs 102400 10240 92160 10% /run', '/dev/sda1 ext4 104857600 41943040 62914560 40% /', '/dev/sdb1 xfs 52428800 10485760 41943040 20% /data', ].join('\n'); return { stdout: `${stdout}\n`, exitCode: 0 }; } if (command.includes('===SYSCTL===') && this.options.os === 'FreeBSD') { this.pollCount += 1; const bootSec = Math.floor(Date.now() / 1000) - 3600; const stdout = [ '===SYSCTL===', '8589934592', '4096', '{ 0.31 0.25 0.19 }', `{ sec = ${bootSec}, usec = 0 }`, `${500 + this.pollCount * 20} 0 100 5 ${4000 + this.pollCount * 80}`, '===VMSTAT===', ' procs memory page', ' 1 0 0 200000 500000 0 0 0', '===NET===', 'Name Mtu Network Address Ipkts Ierrs Idrop Ibytes Opkts Oerrs Obytes Coll', `vtnet0 1500 52:54:00:12:34:56 100 0 0 ${10000 + this.pollCount * 1000} 100 0 ${5000 + this.pollCount * 500} 0`, '===DF===', 'Filesystem Type 1K-blocks Used Avail Capacity Mounted on', 'devfs devfs 1 1 0 100% /dev', '/dev/vtbd0p2 ufs 41943040 16777216 25165824 40% /', ].join('\n'); return { stdout: `${stdout}\n`, exitCode: 0 }; } if (command.includes('===TOP===') && this.options.os === 'Darwin') { this.pollCount += 1; const bootSec = Math.floor(Date.now() / 1000) - 7200; const stdout = [ '===SYSCTL===', '17179869184', '16384', '{ 1.15 0.90 0.75 }', `{ sec = ${bootSec}, usec = 0 }`, '===VMSTAT===', 'Pages active: 250000.', 'Pages wired down: 100000.', 'Pages occupied by compressor: 50000.', '===TOP===', 'CPU usage: 18.50% user, 6.50% sys, 75.00% idle', '===NET===', 'Name Mtu Network Address Ipkts Ierrs Ibytes Opkts Oerrs Obytes Coll', `en0 1500 aa:bb:cc:dd:ee:ff 100 0 ${20000 + this.pollCount * 2000} 100 0 ${8000 + this.pollCount * 800} 0`, '===DF===', 'Filesystem 1024-blocks Used Available Capacity Mounted on', '/dev/disk3s1 488245288 195298115 292947173 40% /', ].join('\n'); return { stdout: `${stdout}\n`, exitCode: 0 }; } // Inspector command if (command.includes('===PROCS===')) { const stdout = [ '===PROCS===', ' PID USER %CPU %MEM RSS COMMAND', ' 101 root 12.4 1.8 65536 /usr/bin/node server.js', ' 202 postgres 4.1 3.2 131072 postgres: main process', '===PORTS===', 'Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port Process', 'tcp LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=10,fd=3))', 'tcp LISTEN 0 511 127.0.0.1:5432 0.0.0.0:* users:(("postgres",pid=202,fd=5))', '===THERMAL===', 'x86_pkg_temp:46500', ].join('\n'); return { stdout: `${stdout}\n`, exitCode: 0 }; } return { stdout: `ok:${command}\n`, exitCode: 0 }; } private evaluateBinaryCommand( rawCommand: string, ): { stdout: Buffer; stderr?: string; exitCode: number } | null { // Support streamed SFTP folder archive command in integration tests const tarMatch = /tar -C ('(?:[^']|'\\'')*'|\S+) -cf - ('(?:[^']|'\\'')*'|\S+) \| gzip -c/.exec( rawCommand, ); if (tarMatch) { try { const virtualParent = unquoteSinglePosix(tarMatch[1]!); const baseName = unquoteSinglePosix(tarMatch[2]!); const { absPath: absParent } = this.resolveVirtualPath(virtualParent); const outBuf = execFileSync('tar', ['-C', absParent, '-czf', '-', baseName]); return { stdout: outBuf, exitCode: 0 }; } catch (err) { return { stdout: Buffer.alloc(0), stderr: err instanceof Error ? err.message : String(err), exitCode: 1, }; } } return null; } private attachSftpServer(sftp: ssh2.SFTPWrapper): void { const SC = ssh2.utils.sftp.STATUS_CODE; let nextId = 1; const files = new Map(); const dirs = new Map(); const makeHandle = (id: number): Buffer => { const b = Buffer.allocUnsafe(4); b.writeUInt32BE(id, 0); return b; }; const readId = (h: Buffer): number => h.readUInt32BE(0); const sendErr = (reqId: number, err: unknown) => { const code = (err as { code?: string })?.code; sftp.status(reqId, code === 'ENOENT' ? SC.NO_SUCH_FILE : SC.FAILURE, String(err)); }; sftp.on('REALPATH', (reqId, reqPath) => { try { const { normPosix, absPath } = this.resolveVirtualPath(reqPath); const st = fs.existsSync(absPath) ? fs.statSync(absPath) : fs.statSync(this.sftpRootDir); sftp.name(reqId, [ { filename: normPosix, longname: normPosix, attrs: toSftpAttrs(st), }, ]); } catch (err) { sendErr(reqId, err); } }); sftp.on('STAT', (reqId, reqPath) => { try { const { absPath } = this.resolveVirtualPath(reqPath); sftp.attrs(reqId, toSftpAttrs(fs.statSync(absPath))); } catch (err) { sendErr(reqId, err); } }); sftp.on('LSTAT', (reqId, reqPath) => { try { const { absPath } = this.resolveVirtualPath(reqPath); sftp.attrs(reqId, toSftpAttrs(fs.lstatSync(absPath))); } catch (err) { sendErr(reqId, err); } }); sftp.on('FSTAT', (reqId, handle) => { const entry = files.get(readId(handle)); if (!entry) { sftp.status(reqId, SC.FAILURE); return; } sftp.attrs(reqId, toSftpAttrs(fs.fstatSync(entry.fd))); }); sftp.on('OPENDIR', (reqId, reqPath) => { try { const { absPath } = this.resolveVirtualPath(reqPath); if (!fs.statSync(absPath).isDirectory()) { sftp.status(reqId, SC.FAILURE, 'Not a directory'); return; } const id = nextId++; dirs.set(id, { absPath, done: false }); sftp.handle(reqId, makeHandle(id)); } catch (err) { sendErr(reqId, err); } }); sftp.on('READDIR', (reqId, handle) => { const entry = dirs.get(readId(handle)); if (!entry) { sftp.status(reqId, SC.FAILURE); return; } if (entry.done) { sftp.status(reqId, SC.EOF); return; } entry.done = true; try { const items = fs.readdirSync(entry.absPath); sftp.name( reqId, items.map((name) => { const st = fs.lstatSync(path.join(entry.absPath, name)); return { filename: name, longname: `${st.isDirectory() ? 'd' : '-'}rwxr-xr-x 1 mock mock ${st.size} Jan 1 00:00 ${name}`, attrs: toSftpAttrs(st), }; }), ); } catch (err) { sendErr(reqId, err); } }); sftp.on('OPEN', (reqId, filename, flags, attrs) => { try { const { absPath } = this.resolveVirtualPath(filename); const mode = attrs?.mode ? attrs.mode & 0o7777 : 0o644; const fd = fs.openSync(absPath, mapSftpFlags(flags), mode); const id = nextId++; files.set(id, { fd, absPath }); sftp.handle(reqId, makeHandle(id)); } catch (err) { sendErr(reqId, err); } }); sftp.on('READ', (reqId, handle, offset, len) => { const entry = files.get(readId(handle)); if (!entry) { sftp.status(reqId, SC.FAILURE); return; } const buf = Buffer.allocUnsafe(len); const bytesRead = fs.readSync(entry.fd, buf, 0, len, offset); if (bytesRead === 0) { sftp.status(reqId, SC.EOF); return; } sftp.data(reqId, buf.subarray(0, bytesRead)); }); sftp.on('WRITE', (reqId, handle, offset, data) => { const entry = files.get(readId(handle)); if (!entry) { sftp.status(reqId, SC.FAILURE); return; } fs.writeSync(entry.fd, data, 0, data.length, offset); sftp.status(reqId, SC.OK); }); sftp.on('CLOSE', (reqId, handle) => { const id = readId(handle); const f = files.get(id); if (f) { files.delete(id); fs.closeSync(f.fd); sftp.status(reqId, SC.OK); return; } if (dirs.delete(id)) { sftp.status(reqId, SC.OK); return; } sftp.status(reqId, SC.OK); }); sftp.on('MKDIR', (reqId, reqPath) => { try { const { absPath } = this.resolveVirtualPath(reqPath); fs.mkdirSync(absPath); sftp.status(reqId, SC.OK); } catch (err) { sendErr(reqId, err); } }); sftp.on('RMDIR', (reqId, reqPath) => { try { const { absPath } = this.resolveVirtualPath(reqPath); fs.rmdirSync(absPath); sftp.status(reqId, SC.OK); } catch (err) { sendErr(reqId, err); } }); sftp.on('REMOVE', (reqId, reqPath) => { try { const { absPath } = this.resolveVirtualPath(reqPath); fs.unlinkSync(absPath); sftp.status(reqId, SC.OK); } catch (err) { sendErr(reqId, err); } }); sftp.on('RENAME', (reqId, oldPath, newPath) => { try { const a = this.resolveVirtualPath(oldPath).absPath; const b = this.resolveVirtualPath(newPath).absPath; fs.renameSync(a, b); sftp.status(reqId, SC.OK); } catch (err) { sendErr(reqId, err); } }); sftp.on('SETSTAT', (reqId, reqPath, attrs) => { try { const { absPath } = this.resolveVirtualPath(reqPath); if (attrs.mode !== undefined) { fs.chmodSync(absPath, attrs.mode & 0o7777); } sftp.status(reqId, SC.OK); } catch (err) { sendErr(reqId, err); } }); sftp.on('FSETSTAT', (reqId, handle, attrs) => { const entry = files.get(readId(handle)); if (!entry) { sftp.status(reqId, SC.FAILURE); return; } if (attrs.mode !== undefined) { fs.fchmodSync(entry.fd, attrs.mode & 0o7777); } sftp.status(reqId, SC.OK); }); sftp.on('EXTENDED', (reqId, extName, extData) => { if (extName === 'posix-rename@openssh.com') { try { const len1 = extData.readUInt32BE(0); const oldPath = extData.subarray(4, 4 + len1).toString('utf8'); const len2 = extData.readUInt32BE(4 + len1); const newPath = extData.subarray(8 + len1, 8 + len1 + len2).toString('utf8'); fs.renameSync( this.resolveVirtualPath(oldPath).absPath, this.resolveVirtualPath(newPath).absPath, ); sftp.status(reqId, SC.OK); } catch (err) { sendErr(reqId, err); } return; } sftp.status(reqId, SC.OP_UNSUPPORTED); }); } }