GCoordinator/tests/helpers/mock-ssh-server.ts

338 lines
11 KiB
TypeScript

import net from 'node:net';
import ssh2, { type Connection, type Server } from 'ssh2';
import { computeOpenSshFingerprint } from '../../src/server/security/vault.js';
export interface MockSshOptions {
username: string;
password?: string;
sudoPassword?: string;
os?: 'Linux' | 'FreeBSD' | 'Darwin';
authorizedKeys?: string[];
allowTcpForward?: boolean;
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;
}
export class MockSshServer {
public port = 0;
public hostFingerprint = '';
public authorizedKeys: string[];
public pollCount = 0;
public lastSudoStdin = '';
private hostPrivateKey: string;
private server: Server | null = null;
private readonly activeConns = new Set<Connection>();
constructor(public readonly options: MockSshOptions) {
this.authorizedKeys = [...(options.authorizedKeys ?? [])];
const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mock-host' });
this.hostPrivateKey = kp.private;
this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim());
}
async start(listenPort = 0): Promise<number> {
if (this.server) return this.port;
const srv = new ssh2.Server(
{ hostKeys: [this.hostPrivateKey] },
(client) => this.handleClient(client),
);
await new Promise<void>((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<string> {
const prevPort = this.port;
await this.close();
const kp = ssh2.utils.generateKeyPairSync('ed25519', { comment: 'mitm-host' });
this.hostPrivateKey = kp.private;
this.hostFingerprint = computeOpenSshFingerprint(kp.public.trim());
await this.start(prevPort);
return this.hostFingerprint;
}
async close(): Promise<void> {
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<void>((resolve) => s.close(() => resolve()));
}
}
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.on('session', (accept) => {
const session = accept();
session.on('exec', (acceptExec, _rejectExec, info) => {
const stream = acceptExec();
const stdinChunks: Buffer[] = [];
stream.on('data', (chunk: Buffer) => {
stdinChunks.push(chunk);
});
stream.on('end', () => {
const stdinText = Buffer.concat(stdinChunks).toString('utf8');
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();
});
});
});
});
}
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 <Link#1> 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 <Link#4> 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 };
}
}