feat(ssh): implement KnownHostsService TOFU/MITM guard, sudo helper, and multiplexed SSHPool with ProxyJump

This commit is contained in:
tyuXX 2026-11-26 18:50:23 +00:00
parent df030ba8ba
commit b742f0ebf8
4 changed files with 1129 additions and 1 deletions

757
src/server/ssh/ssh-pool.ts Normal file
View file

@ -0,0 +1,757 @@
import type { Duplex } from 'node:stream';
import ssh2, { type Client, type ConnectConfig } from 'ssh2';
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
import type {
ServerConnectionStatus,
ServerRuntimeState,
} from '../../shared/ws-protocol.js';
import type { ConfigManager } from '../config/config-manager.js';
import type { VaultService } from '../security/vault.js';
import type { KnownHostsService } from './known-hosts.js';
import { buildEnvPrefix, prepareSudoExecution } from './sudo.js';
export interface ExecResult {
stdout: string;
stderr: string;
exitCode: number | null;
signal?: string;
durationMs: number;
}
export interface ExecOptions {
sudo?: boolean;
timeoutMs?: number;
env?: Record<string, string>;
stdin?: Buffer | string;
maxBytes?: number;
}
interface PooledConnection {
serverId: string;
client: Client;
connectedAt: number;
jumpHostId?: string;
childIds: Set<string>;
}
const DEFAULT_EXEC_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_BYTES = 2 * 1024 * 1024;
export class SSHPool {
private readonly connections = new Map<string, PooledConnection>();
private readonly inFlight = new Map<string, Promise<Client>>();
private readonly states = new Map<string, ServerRuntimeState>();
private readonly reconnectTimers = new Map<string, NodeJS.Timeout>();
private readonly reconnectAttempts = new Map<string, number>();
private readonly stateListeners = new Set<(states: ServerRuntimeState[]) => void>();
private closed = false;
constructor(
private readonly configManager: ConfigManager,
private readonly vaultService: VaultService,
private readonly knownHosts: KnownHostsService,
) {
this.knownHosts.onChange(() => {
this.refreshStatesFromKnownHosts();
});
}
onStateChange(listener: (states: ServerRuntimeState[]) => void): () => void {
this.stateListeners.add(listener);
return () => {
this.stateListeners.delete(listener);
};
}
getStates(): ServerRuntimeState[] {
const out: ServerRuntimeState[] = [];
for (const server of this.configManager.listServers()) {
out.push(this.buildStateForServer(server));
}
return out;
}
getState(serverId: string): ServerRuntimeState | undefined {
const server = this.configManager.getServer(serverId);
return server ? this.buildStateForServer(server) : undefined;
}
setOsDetected(serverId: string, os: 'linux' | 'bsd' | 'macos'): void {
const prev = this.states.get(serverId) ?? {
serverId,
status: 'connected' as ServerConnectionStatus,
};
if (prev.osDetected !== os) {
this.states.set(serverId, { ...prev, osDetected: os });
this.emitStates();
}
}
async acquireClient(
serverId: string,
visited: Set<string> = new Set(),
): Promise<Client> {
if (this.closed) {
throw new Error('SSHPool is closed');
}
const server = this.configManager.getServer(serverId);
if (!server) {
throw new Error(`Unknown server "${serverId}"`);
}
if (!server.enabled) {
this.updateState(serverId, { status: 'disabled' });
throw new Error(`Server "${serverId}" is disabled`);
}
if (this.vaultService.state !== 'unlocked') {
this.updateState(serverId, {
status: 'vault_locked',
lastError: 'Vault is locked',
});
throw new Error('Vault is locked');
}
if (visited.has(serverId)) {
throw new Error(`ProxyJump cycle detected involving "${serverId}"`);
}
const existing = this.connections.get(serverId);
if (existing) {
return existing.client;
}
const pending = this.inFlight.get(serverId);
if (pending) {
return pending;
}
const nextVisited = new Set(visited);
nextVisited.add(serverId);
const connectPromise = this.connectServer(server, nextVisited).finally(() => {
this.inFlight.delete(serverId);
});
this.inFlight.set(serverId, connectPromise);
return connectPromise;
}
async exec(
serverId: string,
command: string,
opts: ExecOptions = {},
): Promise<ExecResult> {
const client = await this.acquireClient(serverId);
const server = this.configManager.getServer(serverId);
if (!server) {
throw new Error(`Unknown server "${serverId}"`);
}
const envPrefix = buildEnvPrefix(opts.env);
let finalCommand = `${envPrefix}${command}`;
let stdinBuf: Buffer | undefined =
opts.stdin === undefined
? undefined
: typeof opts.stdin === 'string'
? Buffer.from(opts.stdin, 'utf8')
: Buffer.from(opts.stdin);
if (opts.sudo) {
let sudoPassword: string | undefined;
if (server.sudoCredentialId) {
const sudoCred = this.vaultService.getSecret(server.sudoCredentialId);
if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) {
sudoPassword = sudoCred.password;
}
}
const prepared = prepareSudoExecution(finalCommand, {
sudoPassword,
stdin: stdinBuf,
});
if (stdinBuf) stdinBuf.fill(0);
finalCommand = prepared.command;
stdinBuf = prepared.stdin;
}
const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS;
const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
const started = Date.now();
return new Promise<ExecResult>((resolve, reject) => {
let settled = false;
let timer: NodeJS.Timeout | null = null;
const stdoutChunks: Buffer[] = [];
const stderrChunks: Buffer[] = [];
let totalBytes = 0;
client.exec(finalCommand, (err, stream) => {
if (err) {
if (stdinBuf) stdinBuf.fill(0);
reject(err);
return;
}
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
if (stdinBuf) stdinBuf.fill(0);
fn();
};
timer = setTimeout(() => {
try {
stream.close();
} catch {
// Ignore close errors on timeout
}
finish(() =>
reject(new Error(`SSH exec timed out after ${timeoutMs}ms on "${serverId}"`)),
);
}, timeoutMs);
if (stdinBuf && stdinBuf.length > 0) {
stream.stdin.write(stdinBuf);
stdinBuf.fill(0);
}
stream.stdin.end();
stream.on('data', (chunk: Buffer) => {
if (totalBytes < maxBytes) {
const slice =
totalBytes + chunk.length > maxBytes
? chunk.subarray(0, maxBytes - totalBytes)
: chunk;
stdoutChunks.push(slice);
totalBytes += slice.length;
}
});
stream.stderr.on('data', (chunk: Buffer) => {
if (totalBytes < maxBytes) {
const slice =
totalBytes + chunk.length > maxBytes
? chunk.subarray(0, maxBytes - totalBytes)
: chunk;
stderrChunks.push(slice);
totalBytes += slice.length;
}
});
stream.on('close', (exitCode: number | null, signal?: string) => {
finish(() =>
resolve({
stdout: Buffer.concat(stdoutChunks).toString('utf8'),
stderr: Buffer.concat(stderrChunks).toString('utf8'),
exitCode: exitCode ?? null,
signal,
durationMs: Date.now() - started,
}),
);
});
stream.on('error', (streamErr: Error) => {
finish(() => reject(streamErr));
});
});
});
}
async forwardOutStream(
serverId: string,
dstHost: string,
dstPort: number,
timeoutMs = 10_000,
): Promise<Duplex> {
const client = await this.acquireClient(serverId);
return forwardOutOnClient(client, '127.0.0.1', 0, dstHost, dstPort, timeoutMs);
}
async verifyStandaloneKeyAuth(
server: ServerConfig,
privateKey: string,
passphrase?: string,
): Promise<void> {
if (this.vaultService.state !== 'unlocked') {
throw new Error('Vault is locked');
}
let hopStream: Duplex | undefined;
if (server.jumpHostId) {
const bastionClient = await this.acquireClient(server.jumpHostId, new Set([server.id]));
hopStream = await forwardOutOnClient(
bastionClient,
'127.0.0.1',
0,
server.host,
server.port,
);
}
const settings = this.configManager.getSettings();
const tempClient = new ssh2.Client();
try {
await new Promise<void>((resolve, reject) => {
let settled = false;
const done = (err?: Error) => {
if (settled) return;
settled = true;
if (err) reject(err);
else resolve();
};
tempClient.once('ready', () => done());
tempClient.once('error', (err) => done(err));
tempClient.once('close', () => done(new Error('Verification connection closed before ready')));
const cfg: ConnectConfig = {
username: server.username,
privateKey,
passphrase: passphrase || undefined,
readyTimeout: settings.sshReadyTimeoutMs,
hostVerifier: (keyBuf: Buffer) =>
this.knownHosts.verifyServerHostKey(server, keyBuf),
};
if (hopStream) {
cfg.sock = hopStream;
} else {
cfg.host = server.host;
cfg.port = server.port;
}
tempClient.connect(cfg);
});
const res = await new Promise<ExecResult>((resolve, reject) => {
tempClient.exec('echo gcoord-key-ok', (err, stream) => {
if (err) {
reject(err);
return;
}
const out: Buffer[] = [];
const errBuf: Buffer[] = [];
stream.on('data', (d: Buffer) => out.push(d));
stream.stderr.on('data', (d: Buffer) => errBuf.push(d));
stream.on('close', (exitCode: number | null) => {
resolve({
stdout: Buffer.concat(out).toString('utf8'),
stderr: Buffer.concat(errBuf).toString('utf8'),
exitCode: exitCode ?? null,
durationMs: 0,
});
});
});
});
if (res.exitCode !== 0 || res.stdout.trim() !== 'gcoord-key-ok') {
throw new Error(
`Key verification command failed (exit=${res.exitCode}): ${res.stderr.trim()}`,
);
}
} finally {
tempClient.end();
tempClient.destroy();
hopStream?.destroy();
}
}
async reconnect(serverId: string): Promise<Client> {
this.closeServer(serverId);
this.reconnectAttempts.delete(serverId);
return this.acquireClient(serverId);
}
syncWithConfig(): void {
const activeIds = new Set<string>();
for (const server of this.configManager.listServers()) {
activeIds.add(server.id);
if (!server.enabled) {
this.closeServer(server.id);
this.updateState(server.id, { status: 'disabled' });
} else if (!this.states.has(server.id)) {
this.updateState(server.id, {
status: this.vaultService.state === 'unlocked' ? 'disconnected' : 'vault_locked',
});
}
}
for (const id of [...this.connections.keys()]) {
if (!activeIds.has(id)) {
this.closeServer(id);
}
}
for (const id of [...this.states.keys()]) {
if (!activeIds.has(id)) {
this.states.delete(id);
}
}
this.emitStates();
}
closeServer(serverId: string): void {
const timer = this.reconnectTimers.get(serverId);
if (timer) {
clearTimeout(timer);
this.reconnectTimers.delete(serverId);
}
const conn = this.connections.get(serverId);
if (!conn) return;
this.connections.delete(serverId);
// Close dependent ProxyJump children first
for (const childId of [...conn.childIds]) {
this.closeServer(childId);
}
if (conn.jumpHostId) {
this.connections.get(conn.jumpHostId)?.childIds.delete(serverId);
}
try {
conn.client.end();
conn.client.destroy();
} catch {
// Ignore cleanup errors
}
const prev = this.states.get(serverId);
if (prev && prev.status === 'connected') {
this.updateState(serverId, { status: 'disconnected' });
}
}
closeAll(reason: 'panic_lock' | 'shutdown'): void {
if (reason === 'shutdown') {
this.closed = true;
}
for (const timer of this.reconnectTimers.values()) {
clearTimeout(timer);
}
this.reconnectTimers.clear();
for (const id of [...this.connections.keys()]) {
this.closeServer(id);
}
if (reason === 'panic_lock') {
for (const server of this.configManager.listServers()) {
this.states.set(server.id, {
serverId: server.id,
status: server.enabled ? 'vault_locked' : 'disabled',
lastError: server.enabled ? 'Panic Lock engaged' : undefined,
});
}
this.emitStates();
}
}
private async connectServer(
server: ServerConfig,
visited: Set<string>,
): Promise<Client> {
const cred = this.vaultService.getSecret(server.credentialId);
if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) {
const msg = `Missing or incompatible SSH credential "${server.credentialId}" in Vault`;
this.updateState(server.id, { status: 'auth_error', lastError: msg });
throw new Error(msg);
}
this.updateState(server.id, { status: 'connecting', lastError: undefined });
let hopStream: Duplex | undefined;
if (server.jumpHostId) {
const bastion = await this.acquireClient(server.jumpHostId, visited);
hopStream = await forwardOutOnClient(
bastion,
'127.0.0.1',
0,
server.host,
server.port,
);
}
const settings = this.configManager.getSettings();
const client = new ssh2.Client();
return new Promise<Client>((resolve, reject) => {
let settled = false;
const failConnect = (err: Error) => {
if (settled) return;
settled = true;
hopStream?.destroy();
try {
client.destroy();
} catch {
// Ignore destroy failure
}
const mismatch = this.knownHosts.getPendingMismatch(server.id);
const tofu = this.knownHosts.getPendingTofu(server.id);
let status: ServerConnectionStatus = 'disconnected';
if (mismatch) status = 'host_key_mismatch';
else if (tofu) status = 'tofu_pending';
else if (
/authentication|all configured authentication/i.test(err.message)
) {
status = 'auth_error';
}
this.updateState(server.id, {
status,
lastError: err.message,
tofuPending: tofu,
hostKeyMismatch: mismatch,
});
reject(err);
};
client.once('ready', () => {
if (settled) {
client.end();
return;
}
settled = true;
this.reconnectAttempts.delete(server.id);
const pooled: PooledConnection = {
serverId: server.id,
client,
connectedAt: Date.now(),
jumpHostId: server.jumpHostId,
childIds: new Set(),
};
this.connections.set(server.id, pooled);
if (server.jumpHostId) {
this.connections.get(server.jumpHostId)?.childIds.add(server.id);
}
this.updateState(server.id, {
status: 'connected',
connectedAt: pooled.connectedAt,
lastError: undefined,
tofuPending: undefined,
hostKeyMismatch: undefined,
});
resolve(client);
});
client.on('error', (err) => {
if (!settled) {
failConnect(err);
} else {
this.handleRuntimeDisconnect(server.id, err.message);
}
});
client.on('close', () => {
if (!settled) {
failConnect(new Error('SSH connection closed during handshake'));
} else {
this.handleRuntimeDisconnect(server.id);
}
});
const cfg: ConnectConfig = {
username: server.username,
keepaliveInterval: settings.sshKeepaliveMs,
keepaliveCountMax: 3,
readyTimeout: settings.sshReadyTimeoutMs,
hostVerifier: (keyBuf: Buffer) =>
this.knownHosts.verifyServerHostKey(server, keyBuf),
};
if (cred.type === 'ssh-key') {
cfg.privateKey = cred.privateKey;
if (cred.passphrase) cfg.passphrase = cred.passphrase;
} else {
cfg.password = cred.password;
}
if (hopStream) {
cfg.sock = hopStream;
} else {
cfg.host = server.host;
cfg.port = server.port;
}
client.connect(cfg);
});
}
private handleRuntimeDisconnect(serverId: string, errorMsg?: string): void {
const conn = this.connections.get(serverId);
if (!conn) return;
this.connections.delete(serverId);
for (const childId of [...conn.childIds]) {
this.closeServer(childId);
}
if (conn.jumpHostId) {
this.connections.get(conn.jumpHostId)?.childIds.delete(serverId);
}
const mismatch = this.knownHosts.getPendingMismatch(serverId);
const tofu = this.knownHosts.getPendingTofu(serverId);
const status: ServerConnectionStatus = mismatch
? 'host_key_mismatch'
: tofu
? 'tofu_pending'
: this.vaultService.state !== 'unlocked'
? 'vault_locked'
: 'disconnected';
this.updateState(serverId, {
status,
lastError: errorMsg,
tofuPending: tofu,
hostKeyMismatch: mismatch,
});
// Only auto-reconnect on transient network drops while unlocked
if (!this.closed && status === 'disconnected') {
const server = this.configManager.getServer(serverId);
if (server?.enabled && !this.reconnectTimers.has(serverId)) {
const attempt = this.reconnectAttempts.get(serverId) ?? 0;
const delayMs = Math.min(60_000, 1000 * 2 ** Math.min(attempt, 6));
this.reconnectAttempts.set(serverId, attempt + 1);
const timer = setTimeout(() => {
this.reconnectTimers.delete(serverId);
void this.acquireClient(serverId).catch(() => {
// Reconnect failure updates state via connectServer
});
}, delayMs);
timer.unref();
this.reconnectTimers.set(serverId, timer);
}
}
}
private refreshStatesFromKnownHosts(): void {
let changed = false;
for (const server of this.configManager.listServers()) {
const prev = this.states.get(server.id);
const tofu = this.knownHosts.getPendingTofu(server.id);
const mismatch = this.knownHosts.getPendingMismatch(server.id);
if (mismatch && prev?.status !== 'host_key_mismatch') {
this.states.set(server.id, {
...(prev ?? { serverId: server.id }),
status: 'host_key_mismatch',
hostKeyMismatch: mismatch,
tofuPending: undefined,
});
changed = true;
} else if (tofu && prev?.status !== 'tofu_pending') {
this.states.set(server.id, {
...(prev ?? { serverId: server.id }),
status: 'tofu_pending',
tofuPending: tofu,
hostKeyMismatch: undefined,
});
changed = true;
} else if (!tofu && !mismatch && (prev?.tofuPending || prev?.hostKeyMismatch)) {
this.states.set(server.id, {
...prev,
status: this.connections.has(server.id) ? 'connected' : 'disconnected',
tofuPending: undefined,
hostKeyMismatch: undefined,
});
changed = true;
}
}
if (changed) this.emitStates();
}
private buildStateForServer(server: ServerConfig): ServerRuntimeState {
const existing = this.states.get(server.id);
const tofu = this.knownHosts.getPendingTofu(server.id);
const mismatch = this.knownHosts.getPendingMismatch(server.id);
if (!server.enabled) {
return { serverId: server.id, status: 'disabled' };
}
if (mismatch) {
return {
...(existing ?? { serverId: server.id }),
status: 'host_key_mismatch',
hostKeyMismatch: mismatch,
};
}
if (tofu) {
return {
...(existing ?? { serverId: server.id }),
status: 'tofu_pending',
tofuPending: tofu,
};
}
if (this.vaultService.state !== 'unlocked') {
return {
...(existing ?? { serverId: server.id }),
status: 'vault_locked',
};
}
return (
existing ?? {
serverId: server.id,
status: this.connections.has(server.id) ? 'connected' : 'disconnected',
}
);
}
private updateState(
serverId: string,
patch: Partial<Omit<ServerRuntimeState, 'serverId'>>,
): void {
const prev = this.states.get(serverId) ?? {
serverId,
status: 'disconnected' as ServerConnectionStatus,
};
this.states.set(serverId, { ...prev, ...patch, serverId });
this.emitStates();
}
private emitStates(): void {
const snapshot = this.getStates();
for (const listener of this.stateListeners) {
try {
listener(snapshot);
} catch {
// Isolate subscriber errors
}
}
}
}
function forwardOutOnClient(
client: Client,
srcIp: string,
srcPort: number,
dstHost: string,
dstPort: number,
timeoutMs = 10_000,
): Promise<Duplex> {
return new Promise((resolve, reject) => {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
reject(new Error(`SSH forwardOut to ${dstHost}:${dstPort} timed out`));
}, timeoutMs);
client.forwardOut(srcIp, srcPort, dstHost, dstPort, (err, stream) => {
if (settled) {
if (!err && stream) stream.destroy();
return;
}
settled = true;
clearTimeout(timer);
if (err) {
reject(err);
} else {
resolve(stream);
}
});
});
}