security(ssh,sudo,keys): fix Sudo stdin leak, SSHPool Panic Lock/ProxyJump races, multi-algo known_hosts & OpenSSH import
This commit is contained in:
parent
9a27525def
commit
716627afdd
7 changed files with 944 additions and 151 deletions
|
|
@ -19,6 +19,7 @@ import {
|
|||
import type { VaultService } from '../../security/vault.js';
|
||||
import type { KeyManager } from '../../ssh/key-manager.js';
|
||||
import type { KnownHostsService } from '../../ssh/known-hosts.js';
|
||||
import { parseOpenSshConfig } from '../../ssh/ssh-config-import.js';
|
||||
import type { SSHPool } from '../../ssh/ssh-pool.js';
|
||||
|
||||
export interface ServersRouterDeps {
|
||||
|
|
@ -78,22 +79,173 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const hostPort = typeof req.query.hostPort === 'string' ? req.query.hostPort : '';
|
||||
const algorithm =
|
||||
typeof req.query.algorithm === 'string' && req.query.algorithm.trim()
|
||||
? req.query.algorithm.trim()
|
||||
: undefined;
|
||||
if (!hostPort) {
|
||||
res.status(400).json({ error: 'MISSING_HOST_PORT' });
|
||||
return;
|
||||
}
|
||||
const deleted = knownHosts.deleteKnownHost(hostPort);
|
||||
const deleted = knownHosts.deleteKnownHost(hostPort, algorithm);
|
||||
auditService.log({
|
||||
action: 'ssh.known_host_delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: hostPort,
|
||||
target: algorithm ? `${hostPort} (${algorithm})` : hostPort,
|
||||
status: deleted ? 'ok' : 'error',
|
||||
});
|
||||
res.json({ deleted });
|
||||
},
|
||||
);
|
||||
|
||||
const hasJumpCycle = (
|
||||
serverId: string,
|
||||
jumpHostId: string | undefined,
|
||||
extraMap?: Map<string, string | undefined>,
|
||||
): boolean => {
|
||||
const visited = new Set<string>([serverId]);
|
||||
let cur = jumpHostId;
|
||||
while (cur) {
|
||||
if (visited.has(cur)) return true;
|
||||
visited.add(cur);
|
||||
if (extraMap && extraMap.has(cur)) {
|
||||
cur = extraMap.get(cur);
|
||||
} else {
|
||||
cur = configManager.getServer(cur)?.jumpHostId;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
router.post(
|
||||
'/test-connection',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
async (req, res) => {
|
||||
const parsed = ServerConfigSchema.safeParse({
|
||||
...(typeof req.body === 'object' && req.body !== null ? req.body : {}),
|
||||
id:
|
||||
typeof (req.body as { id?: unknown } | undefined)?.id === 'string' &&
|
||||
(req.body as { id: string }).id.trim()
|
||||
? (req.body as { id: string }).id.trim()
|
||||
: 'test-probe-tmp',
|
||||
name:
|
||||
typeof (req.body as { name?: unknown } | undefined)?.name === 'string' &&
|
||||
(req.body as { name: string }).name.trim()
|
||||
? (req.body as { name: string }).name.trim()
|
||||
: 'Test Connection',
|
||||
});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
issues: parsed.error.issues,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (hasJumpCycle(parsed.data.id, parsed.data.jumpHostId)) {
|
||||
res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' });
|
||||
return;
|
||||
}
|
||||
const result = await sshPool.testConnection(parsed.data);
|
||||
res.json(result);
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/import-ssh-config',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const parsed = z
|
||||
.object({
|
||||
configText: z.string().min(1).max(256_000),
|
||||
defaultCredentialId: EntityIdSchema.optional(),
|
||||
apply: z.boolean().default(false),
|
||||
})
|
||||
.safeParse(req.body ?? {});
|
||||
if (!parsed.success) {
|
||||
res.status(400).json({ error: 'VALIDATION_ERROR', issues: parsed.error.issues });
|
||||
return;
|
||||
}
|
||||
|
||||
const preview = parseOpenSshConfig(parsed.data.configText);
|
||||
if (!parsed.data.apply) {
|
||||
res.json({ ...preview, createdIds: [] });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsed.data.defaultCredentialId) {
|
||||
res.status(400).json({
|
||||
error: 'MISSING_CREDENTIAL_ID',
|
||||
message: 'Select a default SSH credential before importing hosts',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const aliasToId = new Map<string, string>();
|
||||
const existingServers = configManager.listServers();
|
||||
const takenIds = new Set(existingServers.map((s) => s.id));
|
||||
for (const s of existingServers) {
|
||||
aliasToId.set(s.name, s.id);
|
||||
aliasToId.set(s.id, s.id);
|
||||
}
|
||||
|
||||
const resolvedIds = new Map<string, string>();
|
||||
for (const entry of preview.entries) {
|
||||
let finalId = entry.id;
|
||||
if (takenIds.has(finalId)) {
|
||||
let n = 2;
|
||||
while (takenIds.has(`${finalId.slice(0, 58)}-${n}`)) n++;
|
||||
finalId = `${finalId.slice(0, 58)}-${n}`;
|
||||
}
|
||||
takenIds.add(finalId);
|
||||
resolvedIds.set(entry.alias, finalId);
|
||||
aliasToId.set(entry.alias, finalId);
|
||||
}
|
||||
|
||||
const createdIds: string[] = [];
|
||||
for (const entry of preview.entries) {
|
||||
const finalId = resolvedIds.get(entry.alias)!;
|
||||
const jumpId = entry.jumpHostAlias
|
||||
? aliasToId.get(entry.jumpHostAlias)
|
||||
: undefined;
|
||||
const serverCfg = ServerConfigSchema.parse({
|
||||
id: finalId,
|
||||
name: entry.name,
|
||||
host: entry.host,
|
||||
port: entry.port,
|
||||
username: entry.username,
|
||||
credentialId: parsed.data.defaultCredentialId,
|
||||
...(jumpId && jumpId !== finalId ? { jumpHostId: jumpId } : {}),
|
||||
});
|
||||
configManager.saveConfigText(
|
||||
`servers/${serverCfg.id}.json`,
|
||||
JSON.stringify(serverCfg, null, 2),
|
||||
'ui',
|
||||
`Imported from OpenSSH config (${entry.alias})`,
|
||||
);
|
||||
createdIds.push(serverCfg.id);
|
||||
}
|
||||
|
||||
if (createdIds.length > 0) {
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.import_ssh_config',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: createdIds.join(','),
|
||||
status: 'ok',
|
||||
});
|
||||
}
|
||||
|
||||
res.status(201).json({ ...preview, createdIds });
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/rotate-keys',
|
||||
requireAuth(authService),
|
||||
|
|
@ -148,113 +300,142 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
},
|
||||
);
|
||||
|
||||
router.post('/', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse(req.body);
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Registered server via UI',
|
||||
);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.create',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.status(201).json({
|
||||
server: saved.config,
|
||||
warnings: saved.warnings,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
router.post(
|
||||
'/',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse(req.body);
|
||||
if (hasJumpCycle(parsed.id, parsed.jumpHostId)) {
|
||||
res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' });
|
||||
return;
|
||||
}
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Registered server via UI',
|
||||
);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.create',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save server',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.put('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse({
|
||||
...(req.body ?? {}),
|
||||
id: req.params.id,
|
||||
});
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated server via UI',
|
||||
);
|
||||
sshPool.closeServer(parsed.id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ server: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
res.status(201).json({
|
||||
server: saved.config,
|
||||
warnings: saved.warnings,
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to save server',
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to update server',
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
router.delete('/:id', requireAuth(authService), requireCsrf, enforceSafeMode, (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const deleted = configManager.deleteEntityFile(`servers/${id}.json`);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
router.put(
|
||||
'/:id',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
try {
|
||||
const parsed = ServerConfigSchema.parse({
|
||||
...(req.body ?? {}),
|
||||
id: req.params.id,
|
||||
});
|
||||
if (hasJumpCycle(parsed.id, parsed.jumpHostId)) {
|
||||
res.status(400).json({ error: 'PROXY_JUMP_CYCLE', message: 'ProxyJump cycle detected' });
|
||||
return;
|
||||
}
|
||||
const saved = configManager.saveConfigText(
|
||||
`servers/${parsed.id}.json`,
|
||||
JSON.stringify(parsed, null, 2),
|
||||
'ui',
|
||||
'Updated server via UI',
|
||||
);
|
||||
sshPool.closeServer(parsed.id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.update',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: parsed.id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ server: saved.config, warnings: saved.warnings });
|
||||
} catch (err) {
|
||||
if (err instanceof ZodError) {
|
||||
res.status(400).json({
|
||||
error: 'VALIDATION_ERROR',
|
||||
message: 'Invalid server configuration',
|
||||
issues: err.issues.map((i) => ({
|
||||
path: i.path.join('.') || '(root)',
|
||||
message: i.message,
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
res.status(400).json({
|
||||
error: 'SERVER_SAVE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to update server',
|
||||
});
|
||||
}
|
||||
sshPool.closeServer(id);
|
||||
knownHosts.clearServerPending(id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'SERVER_DELETE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to delete server',
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/:id',
|
||||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
(req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
try {
|
||||
const deleted = configManager.deleteEntityFile(`servers/${id}.json`);
|
||||
if (!deleted) {
|
||||
res.status(404).json({ error: 'SERVER_NOT_FOUND' });
|
||||
return;
|
||||
}
|
||||
sshPool.closeServer(id);
|
||||
knownHosts.clearServerPending(id);
|
||||
monitoringService.syncServers();
|
||||
auditService.log({
|
||||
action: 'server.delete',
|
||||
actorIp: req.clientIp ?? 'unknown',
|
||||
sessionIdHash: req.authSession!.idHash,
|
||||
target: id,
|
||||
status: 'ok',
|
||||
});
|
||||
res.json({ deleted: true });
|
||||
} catch (err) {
|
||||
res.status(400).json({
|
||||
error: 'SERVER_DELETE_ERROR',
|
||||
message: err instanceof Error ? err.message : 'Unable to delete server',
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/:id/reconnect',
|
||||
|
|
@ -286,6 +467,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z.object({ fingerprint: z.string().min(1) }).safeParse(req.body);
|
||||
|
|
@ -405,6 +587,7 @@ export function createServersRouter(deps: ServersRouterDeps): Router {
|
|||
requireAuth(authService),
|
||||
requireCsrf,
|
||||
enforceSafeMode,
|
||||
stepUpGuard,
|
||||
async (req, res) => {
|
||||
const id = String(req.params.id ?? '');
|
||||
const parsed = z.object({ credentialId: EntityIdSchema }).safeParse(req.body);
|
||||
|
|
|
|||
|
|
@ -7,13 +7,22 @@ import type { SSHPool } from './ssh-pool.js';
|
|||
|
||||
const OPENSSH_KEY_TYPES = new Set([
|
||||
'ssh-ed25519',
|
||||
'ssh-ed25519-cert-v01@openssh.com',
|
||||
'ssh-rsa',
|
||||
'ssh-rsa-cert-v01@openssh.com',
|
||||
'rsa-sha2-256',
|
||||
'rsa-sha2-512',
|
||||
'ssh-dss',
|
||||
'ecdsa-sha2-nistp256',
|
||||
'ecdsa-sha2-nistp256-cert-v01@openssh.com',
|
||||
'ecdsa-sha2-nistp384',
|
||||
'ecdsa-sha2-nistp384-cert-v01@openssh.com',
|
||||
'ecdsa-sha2-nistp521',
|
||||
'ecdsa-sha2-nistp521-cert-v01@openssh.com',
|
||||
'sk-ssh-ed25519@openssh.com',
|
||||
'sk-ssh-ed25519-cert-v01@openssh.com',
|
||||
'sk-ecdsa-sha2-nistp256@openssh.com',
|
||||
'sk-ecdsa-sha2-nistp256-cert-v01@openssh.com',
|
||||
]);
|
||||
|
||||
export interface AuthorizedKeyEntry {
|
||||
|
|
@ -135,6 +144,8 @@ function makeRotatedCredentialId(serverId: string): string {
|
|||
}
|
||||
|
||||
export class KeyManager {
|
||||
private readonly activeRotations = new Set<string>();
|
||||
|
||||
constructor(
|
||||
private readonly sshPool: SSHPool,
|
||||
private readonly vaultService: VaultService,
|
||||
|
|
@ -277,6 +288,32 @@ export class KeyManager {
|
|||
passphrase: string | undefined,
|
||||
actorIp: string,
|
||||
sessionIdHash: string | null,
|
||||
): Promise<KeyRotationResult> {
|
||||
if (this.activeRotations.has(serverId)) {
|
||||
return {
|
||||
serverId,
|
||||
ok: false,
|
||||
error: `Key rotation already in progress for "${serverId}"`,
|
||||
};
|
||||
}
|
||||
this.activeRotations.add(serverId);
|
||||
try {
|
||||
return await this.rotateSingleServerLocked(
|
||||
serverId,
|
||||
passphrase,
|
||||
actorIp,
|
||||
sessionIdHash,
|
||||
);
|
||||
} finally {
|
||||
this.activeRotations.delete(serverId);
|
||||
}
|
||||
}
|
||||
|
||||
private async rotateSingleServerLocked(
|
||||
serverId: string,
|
||||
passphrase: string | undefined,
|
||||
actorIp: string,
|
||||
sessionIdHash: string | null,
|
||||
): Promise<KeyRotationResult> {
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server) {
|
||||
|
|
@ -324,7 +361,7 @@ export class KeyManager {
|
|||
newSecret.passphrase,
|
||||
);
|
||||
|
||||
// Step 4: Verified! Persist updated credentialId in server JSON
|
||||
// Step 4: Verified! Persist updated credentialId without tearing down live PTY/tunnel sessions
|
||||
const updatedServer = { ...server, credentialId: newCredId };
|
||||
this.configManager.saveConfigText(
|
||||
`servers/${server.id}.json`,
|
||||
|
|
@ -333,9 +370,6 @@ export class KeyManager {
|
|||
`Atomic SSH key rotation -> ${newCredId}`,
|
||||
);
|
||||
|
||||
// Reconnect pool onto the new key
|
||||
await this.sshPool.reconnect(server.id);
|
||||
|
||||
// Cleanly remove old public key from authorized_keys if it differs
|
||||
if (oldFingerprint && oldFingerprint !== newMeta.fingerprint) {
|
||||
const afterInspect = await this.inspectAuthorizedKeys(server.id);
|
||||
|
|
|
|||
|
|
@ -12,11 +12,16 @@ export interface KnownHostRecord {
|
|||
updatedAt: number;
|
||||
}
|
||||
|
||||
export function normalizeHostForKey(rawHost: string): string {
|
||||
const clean = rawHost.trim().toLowerCase().replace(/^\[|\]$/g, '');
|
||||
return clean.includes(':') ? `[${clean}]` : clean;
|
||||
}
|
||||
|
||||
export function buildHostPortKey(server: Pick<ServerConfig, 'host' | 'port' | 'jumpHostId'>): string {
|
||||
const hostLower = server.host.trim().toLowerCase();
|
||||
const hostNormalized = normalizeHostForKey(server.host);
|
||||
return server.jumpHostId
|
||||
? `${server.jumpHostId}->${hostLower}:${server.port}`
|
||||
: `${hostLower}:${server.port}`;
|
||||
? `${server.jumpHostId}->${hostNormalized}:${server.port}`
|
||||
: `${hostNormalized}:${server.port}`;
|
||||
}
|
||||
|
||||
export function parseHostKeyBuffer(keyBuf: Buffer): {
|
||||
|
|
@ -45,12 +50,30 @@ export class KnownHostsService {
|
|||
private readonly pendingTofu = new Map<string, PendingTofuInfo>();
|
||||
private readonly pendingMismatches = new Map<string, HostKeyAlert>();
|
||||
private readonly listeners = new Set<() => void>();
|
||||
private readonly mismatchListeners = new Set<(alert: HostKeyAlert) => void>();
|
||||
|
||||
constructor(
|
||||
private readonly db: Database.Database,
|
||||
private readonly auditService?: AuditService,
|
||||
) {}
|
||||
|
||||
onHostKeyMismatch(listener: (alert: HostKeyAlert) => void): () => void {
|
||||
this.mismatchListeners.add(listener);
|
||||
return () => {
|
||||
this.mismatchListeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
private emitMismatch(alert: HostKeyAlert): void {
|
||||
for (const cb of this.mismatchListeners) {
|
||||
try {
|
||||
cb(alert);
|
||||
} catch {
|
||||
// Isolate subscriber failures
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onChange(listener: () => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
|
|
@ -63,19 +86,19 @@ export class KnownHostsService {
|
|||
const { algorithm, fingerprint } = parseHostKeyBuffer(keyBuf);
|
||||
const now = Date.now();
|
||||
|
||||
const row = this.db
|
||||
const exactRow = this.db
|
||||
.prepare(
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ?',
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ? AND algorithm = ?',
|
||||
)
|
||||
.get(hostPortKey) as KnownHostRecord | undefined;
|
||||
.get(hostPortKey, algorithm) as KnownHostRecord | undefined;
|
||||
|
||||
if (row) {
|
||||
if (row.fingerprint === fingerprint) {
|
||||
if (exactRow) {
|
||||
if (exactRow.fingerprint === fingerprint) {
|
||||
const hadPending =
|
||||
this.pendingTofu.delete(server.id) || this.pendingMismatches.delete(server.id);
|
||||
this.db
|
||||
.prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ?')
|
||||
.run(now, hostPortKey);
|
||||
.prepare('UPDATE known_hosts SET updated_at = ? WHERE host_port = ? AND algorithm = ?')
|
||||
.run(now, hostPortKey, algorithm);
|
||||
if (hadPending) this.emitChange();
|
||||
return true;
|
||||
}
|
||||
|
|
@ -86,7 +109,7 @@ export class KnownHostsService {
|
|||
host: server.host,
|
||||
port: server.port,
|
||||
algorithm,
|
||||
expectedFingerprint: row.fingerprint,
|
||||
expectedFingerprint: exactRow.fingerprint,
|
||||
actualFingerprint: fingerprint,
|
||||
detectedAt: now,
|
||||
};
|
||||
|
|
@ -99,10 +122,12 @@ export class KnownHostsService {
|
|||
status: 'denied',
|
||||
details: {
|
||||
hostPortKey,
|
||||
expected: row.fingerprint,
|
||||
algorithm,
|
||||
expected: exactRow.fingerprint,
|
||||
actual: fingerprint,
|
||||
},
|
||||
});
|
||||
this.emitMismatch(alert);
|
||||
this.emitChange();
|
||||
return false;
|
||||
}
|
||||
|
|
@ -141,8 +166,9 @@ export class KnownHostsService {
|
|||
actorIp: 'hub',
|
||||
target: server.id,
|
||||
status: 'denied',
|
||||
details: { hostPortKey, expected, actual: fingerprint },
|
||||
details: { hostPortKey, algorithm, expected, actual: fingerprint },
|
||||
});
|
||||
this.emitMismatch(alert);
|
||||
this.emitChange();
|
||||
return false;
|
||||
}
|
||||
|
|
@ -238,7 +264,7 @@ export class KnownHostsService {
|
|||
listKnownHosts(): KnownHostRecord[] {
|
||||
return this.db
|
||||
.prepare(
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC',
|
||||
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts ORDER BY host_port ASC, algorithm ASC',
|
||||
)
|
||||
.all() as KnownHostRecord[];
|
||||
}
|
||||
|
|
@ -272,15 +298,21 @@ export class KnownHostsService {
|
|||
this.emitChange();
|
||||
}
|
||||
|
||||
deleteKnownHost(hostPort: string): boolean {
|
||||
const res = this.db
|
||||
.prepare('DELETE FROM known_hosts WHERE host_port = ?')
|
||||
.run(hostPort);
|
||||
deleteKnownHost(hostPort: string, algorithm?: string): boolean {
|
||||
const res = algorithm
|
||||
? this.db
|
||||
.prepare('DELETE FROM known_hosts WHERE host_port = ? AND algorithm = ?')
|
||||
.run(hostPort, algorithm)
|
||||
: this.db.prepare('DELETE FROM known_hosts WHERE host_port = ?').run(hostPort);
|
||||
for (const [sid, p] of this.pendingTofu.entries()) {
|
||||
if (p.hostPortKey === hostPort) this.pendingTofu.delete(sid);
|
||||
if (p.hostPortKey === hostPort && (!algorithm || p.algorithm === algorithm)) {
|
||||
this.pendingTofu.delete(sid);
|
||||
}
|
||||
}
|
||||
for (const [sid, m] of this.pendingMismatches.entries()) {
|
||||
if (m.hostPortKey === hostPort) this.pendingMismatches.delete(sid);
|
||||
if (m.hostPortKey === hostPort && (!algorithm || m.algorithm === algorithm)) {
|
||||
this.pendingMismatches.delete(sid);
|
||||
}
|
||||
}
|
||||
if (res.changes > 0) this.emitChange();
|
||||
return res.changes > 0;
|
||||
|
|
|
|||
149
src/server/ssh/ssh-config-import.ts
Normal file
149
src/server/ssh/ssh-config-import.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
export interface ParsedOpenSshHost {
|
||||
alias: string;
|
||||
id: string;
|
||||
name: string;
|
||||
host: string;
|
||||
port: number;
|
||||
username: string;
|
||||
jumpHostAlias?: string;
|
||||
}
|
||||
|
||||
export interface OpenSshImportPreview {
|
||||
entries: ParsedOpenSshHost[];
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
function slugifyHostId(alias: string): string {
|
||||
const clean = alias
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, '-')
|
||||
.replace(/^[^a-z0-9]+|[-_.]+$/g, '')
|
||||
.slice(0, 64);
|
||||
return clean || 'srv';
|
||||
}
|
||||
|
||||
function stripComment(line: string): string {
|
||||
let inQuotes = false;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const ch = line[i]!;
|
||||
if (ch === '"') inQuotes = !inQuotes;
|
||||
else if (ch === '#' && !inQuotes) return line.slice(0, i);
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
function unquoteVal(val: string): string {
|
||||
const t = val.trim();
|
||||
if (t.length >= 2 && t.startsWith('"') && t.endsWith('"')) {
|
||||
return t.slice(1, -1);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
export function parseOpenSshConfig(text: string): OpenSshImportPreview {
|
||||
const warnings: string[] = [];
|
||||
const rawLines = text.split(/\r?\n/);
|
||||
|
||||
interface DraftBlock {
|
||||
patterns: string[];
|
||||
hostName?: string;
|
||||
port?: number;
|
||||
user?: string;
|
||||
proxyJump?: string;
|
||||
}
|
||||
|
||||
const blocks: DraftBlock[] = [];
|
||||
let current: DraftBlock | null = null;
|
||||
|
||||
for (let i = 0; i < rawLines.length; i++) {
|
||||
const cleaned = stripComment(rawLines[i]!).trim();
|
||||
if (!cleaned) continue;
|
||||
|
||||
const eqOrSpace = /^([A-Za-z][A-Za-z0-9]*)\s*(?:=|\s+)\s*(.+)$/.exec(cleaned);
|
||||
if (!eqOrSpace) {
|
||||
warnings.push(`Line ${i + 1}: ignored unparseable directive`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = eqOrSpace[1]!.toLowerCase();
|
||||
const rawVal = unquoteVal(eqOrSpace[2]!);
|
||||
|
||||
if (key === 'match') {
|
||||
current = null;
|
||||
warnings.push(`Line ${i + 1}: skipped unsupported Match block`);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (key === 'host') {
|
||||
const patterns = rawVal.split(/\s+/).filter(Boolean);
|
||||
current = { patterns };
|
||||
blocks.push(current);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!current) continue;
|
||||
|
||||
if (key === 'hostname') {
|
||||
current.hostName = rawVal;
|
||||
} else if (key === 'port') {
|
||||
const p = Number.parseInt(rawVal, 10);
|
||||
if (Number.isInteger(p) && p >= 1 && p <= 65535) {
|
||||
current.port = p;
|
||||
} else {
|
||||
warnings.push(`Line ${i + 1}: invalid Port "${rawVal}"`);
|
||||
}
|
||||
} else if (key === 'user') {
|
||||
current.user = rawVal;
|
||||
} else if (key === 'proxyjump') {
|
||||
const firstHop = rawVal.split(',')[0]?.trim();
|
||||
if (firstHop && firstHop.toLowerCase() !== 'none') {
|
||||
const atIdx = firstHop.lastIndexOf('@');
|
||||
const hopHost = atIdx >= 0 ? firstHop.slice(atIdx + 1) : firstHop;
|
||||
const colonIdx = hopHost.lastIndexOf(':');
|
||||
current.proxyJump = colonIdx > 0 && !hopHost.includes(']') ? hopHost.slice(0, colonIdx) : hopHost;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const entries: ParsedOpenSshHost[] = [];
|
||||
const usedIds = new Set<string>();
|
||||
|
||||
for (const blk of blocks) {
|
||||
for (const alias of blk.patterns) {
|
||||
if (alias.includes('*') || alias.includes('?') || alias.startsWith('!')) {
|
||||
warnings.push(`Skipped wildcard/negated Host pattern "${alias}"`);
|
||||
continue;
|
||||
}
|
||||
const host = (blk.hostName ?? alias).trim();
|
||||
if (!host || /\s/.test(host)) {
|
||||
warnings.push(`Skipped Host "${alias}": invalid host name`);
|
||||
continue;
|
||||
}
|
||||
const username = (blk.user ?? 'root').trim();
|
||||
if (!username || /\s/.test(username)) {
|
||||
warnings.push(`Skipped Host "${alias}": invalid username`);
|
||||
continue;
|
||||
}
|
||||
|
||||
let id = slugifyHostId(alias);
|
||||
if (usedIds.has(id)) {
|
||||
let n = 2;
|
||||
while (usedIds.has(`${id.slice(0, 58)}-${n}`)) n++;
|
||||
id = `${id.slice(0, 58)}-${n}`;
|
||||
}
|
||||
usedIds.add(id);
|
||||
|
||||
entries.push({
|
||||
alias,
|
||||
id,
|
||||
name: alias,
|
||||
host,
|
||||
port: blk.port ?? 22,
|
||||
username,
|
||||
...(blk.proxyJump ? { jumpHostAlias: blk.proxyJump } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { entries, warnings };
|
||||
}
|
||||
|
|
@ -7,13 +7,29 @@ import ssh2, {
|
|||
} from 'ssh2';
|
||||
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
|
||||
import type {
|
||||
HostKeyAlert,
|
||||
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';
|
||||
import {
|
||||
buildEnvPrefix,
|
||||
posixSingleQuote,
|
||||
prepareSudoExecution,
|
||||
SUDO_PTY_PROMPT,
|
||||
} from './sudo.js';
|
||||
|
||||
export interface ServerTestResult {
|
||||
ok: boolean;
|
||||
latencyMs: number;
|
||||
osDetected?: 'linux' | 'bsd' | 'macos';
|
||||
hostFingerprint?: string;
|
||||
tofuRequired?: boolean;
|
||||
hostKeyMismatch?: HostKeyAlert;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ExecResult {
|
||||
stdout: string;
|
||||
|
|
@ -58,6 +74,9 @@ 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 pendingClients = new Map<string, Set<Client>>();
|
||||
private readonly serverEpoch = new Map<string, number>();
|
||||
private poolEpoch = 0;
|
||||
private readonly states = new Map<string, ServerRuntimeState>();
|
||||
private readonly reconnectTimers = new Map<string, NodeJS.Timeout>();
|
||||
private readonly reconnectAttempts = new Map<string, number>();
|
||||
|
|
@ -74,6 +93,24 @@ export class SSHPool {
|
|||
});
|
||||
}
|
||||
|
||||
private getServerEpoch(serverId: string): number {
|
||||
return this.serverEpoch.get(serverId) ?? 0;
|
||||
}
|
||||
|
||||
private validateJumpChain(serverId: string): void {
|
||||
const chain = new Set<string>();
|
||||
let currentId: string | undefined = serverId;
|
||||
while (currentId) {
|
||||
if (chain.has(currentId)) {
|
||||
throw new Error(`ProxyJump cycle detected involving "${currentId}"`);
|
||||
}
|
||||
chain.add(currentId);
|
||||
const srv = this.configManager.getServer(currentId);
|
||||
if (!srv) break;
|
||||
currentId = srv.jumpHostId;
|
||||
}
|
||||
}
|
||||
|
||||
onStateChange(listener: (states: ServerRuntimeState[]) => void): () => void {
|
||||
this.stateListeners.add(listener);
|
||||
return () => {
|
||||
|
|
@ -132,6 +169,7 @@ export class SSHPool {
|
|||
if (visited.has(serverId)) {
|
||||
throw new Error(`ProxyJump cycle detected involving "${serverId}"`);
|
||||
}
|
||||
this.validateJumpChain(serverId);
|
||||
|
||||
const existing = this.connections.get(serverId);
|
||||
if (existing) {
|
||||
|
|
@ -145,19 +183,42 @@ export class SSHPool {
|
|||
|
||||
const nextVisited = new Set(visited);
|
||||
nextVisited.add(serverId);
|
||||
const startPoolEpoch = this.poolEpoch;
|
||||
const startSrvEpoch = this.getServerEpoch(serverId);
|
||||
|
||||
const connectPromise = this.connectServer(server, nextVisited).finally(() => {
|
||||
this.inFlight.delete(serverId);
|
||||
const connectPromise = this.connectServer(
|
||||
server,
|
||||
nextVisited,
|
||||
startPoolEpoch,
|
||||
startSrvEpoch,
|
||||
).finally(() => {
|
||||
if (this.inFlight.get(serverId) === connectPromise) {
|
||||
this.inFlight.delete(serverId);
|
||||
}
|
||||
});
|
||||
this.inFlight.set(serverId, connectPromise);
|
||||
return connectPromise;
|
||||
}
|
||||
|
||||
private getSudoPassword(server: ServerConfig): string | undefined {
|
||||
if (!server.sudoCredentialId) return undefined;
|
||||
const sudoCred = this.vaultService.getRuntimeSecret(server.sudoCredentialId);
|
||||
if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) {
|
||||
return sudoCred.password;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private prepareCommand(
|
||||
server: ServerConfig,
|
||||
command: string,
|
||||
opts: { sudo?: boolean; env?: Record<string, string>; stdin?: Buffer | string },
|
||||
): { finalCommand: string; stdinBuf?: Buffer } {
|
||||
opts: {
|
||||
sudo?: boolean;
|
||||
env?: Record<string, string>;
|
||||
stdin?: Buffer | string;
|
||||
ptyPrompt?: boolean;
|
||||
},
|
||||
): { finalCommand: string; stdinBuf?: Buffer; ptyPassword?: string } {
|
||||
const envPrefix = buildEnvPrefix(opts.env);
|
||||
let finalCommand = `${envPrefix}${command}`;
|
||||
let stdinBuf: Buffer | undefined =
|
||||
|
|
@ -168,20 +229,16 @@ export class SSHPool {
|
|||
: Buffer.from(opts.stdin);
|
||||
|
||||
if (opts.sudo) {
|
||||
let sudoPassword: string | undefined;
|
||||
if (server.sudoCredentialId) {
|
||||
const sudoCred = this.vaultService.getRuntimeSecret(server.sudoCredentialId);
|
||||
if (sudoCred && (sudoCred.type === 'sudo-password' || sudoCred.type === 'ssh-password')) {
|
||||
sudoPassword = sudoCred.password;
|
||||
}
|
||||
}
|
||||
const sudoPassword = this.getSudoPassword(server);
|
||||
const prepared = prepareSudoExecution(finalCommand, {
|
||||
sudoPassword,
|
||||
stdin: stdinBuf,
|
||||
ptyPrompt: opts.ptyPrompt,
|
||||
});
|
||||
if (stdinBuf) stdinBuf.fill(0);
|
||||
finalCommand = prepared.command;
|
||||
stdinBuf = prepared.stdin;
|
||||
return { finalCommand, stdinBuf, ptyPassword: prepared.ptyPassword };
|
||||
}
|
||||
|
||||
return { finalCommand, stdinBuf };
|
||||
|
|
@ -228,7 +285,10 @@ export class SSHPool {
|
|||
throw new Error(`Unknown server "${serverId}"`);
|
||||
}
|
||||
|
||||
const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
|
||||
const { finalCommand, stdinBuf, ptyPassword } = this.prepareCommand(server, command, {
|
||||
...opts,
|
||||
ptyPrompt: Boolean(opts.pty),
|
||||
});
|
||||
|
||||
return new Promise<ExecStreamHandle>((resolve, reject) => {
|
||||
const execOpts = opts.pty
|
||||
|
|
@ -248,6 +308,21 @@ export class SSHPool {
|
|||
return;
|
||||
}
|
||||
|
||||
let sudoSent = false;
|
||||
let promptProbeBuf = '';
|
||||
const maybeSendPtyPassword = (chunk: Buffer) => {
|
||||
if (!ptyPassword || sudoSent) return;
|
||||
promptProbeBuf = (promptProbeBuf + chunk.toString('utf8')).slice(-256);
|
||||
if (promptProbeBuf.includes(SUDO_PTY_PROMPT)) {
|
||||
sudoSent = true;
|
||||
channel.stdin.write(`${ptyPassword}\n`);
|
||||
}
|
||||
};
|
||||
if (ptyPassword) {
|
||||
channel.on('data', maybeSendPtyPassword);
|
||||
channel.stderr?.on('data', maybeSendPtyPassword);
|
||||
}
|
||||
|
||||
let exitCode: number | null = null;
|
||||
let signal: string | undefined;
|
||||
const done = new Promise<{ exitCode: number | null; signal?: string }>(
|
||||
|
|
@ -303,10 +378,94 @@ export class SSHPool {
|
|||
throw new Error(`Unknown server "${serverId}"`);
|
||||
}
|
||||
|
||||
const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
|
||||
const rawStdinBuf =
|
||||
opts.stdin === undefined
|
||||
? undefined
|
||||
: typeof opts.stdin === 'string'
|
||||
? Buffer.from(opts.stdin, 'utf8')
|
||||
: Buffer.from(opts.stdin);
|
||||
|
||||
const timeoutMs = opts.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS;
|
||||
const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
// When both sudo password and non-empty stdin exist, avoid concatenating them into sudo's stdin:
|
||||
// probe `sudo -n true` first; otherwise stage the payload in a private 0600 temp file.
|
||||
if (opts.sudo && rawStdinBuf && rawStdinBuf.length > 0) {
|
||||
const sudoPassword = this.getSudoPassword(server);
|
||||
const envPrefix = buildEnvPrefix(opts.env);
|
||||
const fullCmd = `${envPrefix}${command}`;
|
||||
const quotedCmd = posixSingleQuote(fullCmd);
|
||||
|
||||
if (sudoPassword) {
|
||||
const noPassProbe = await this.execRaw(client, serverId, 'sudo -n true', undefined, 5_000, 4096);
|
||||
if (noPassProbe.exitCode === 0) {
|
||||
try {
|
||||
return await this.execRaw(
|
||||
client,
|
||||
serverId,
|
||||
`sudo -n sh -c ${quotedCmd}`,
|
||||
rawStdinBuf,
|
||||
opts.timeoutMs,
|
||||
opts.maxBytes,
|
||||
);
|
||||
} finally {
|
||||
rawStdinBuf.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
const mk = await this.execRaw(
|
||||
client,
|
||||
serverId,
|
||||
'f=$(mktemp /tmp/.gcoord_in.XXXXXX) && chmod 600 "$f" && printf "%s" "$f"',
|
||||
undefined,
|
||||
10_000,
|
||||
1024,
|
||||
);
|
||||
const tmpFile = mk.stdout.trim();
|
||||
if (mk.exitCode === 0 && tmpFile.startsWith('/tmp/.gcoord_in.')) {
|
||||
try {
|
||||
const stage = await this.execRaw(
|
||||
client,
|
||||
serverId,
|
||||
`cat > ${posixSingleQuote(tmpFile)}`,
|
||||
rawStdinBuf,
|
||||
opts.timeoutMs,
|
||||
4096,
|
||||
);
|
||||
if (stage.exitCode === 0) {
|
||||
const pwBuf = Buffer.from(`${sudoPassword}\n`, 'utf8');
|
||||
try {
|
||||
const execCmd = `sudo -S -k -p '' sh -c ${quotedCmd} < ${posixSingleQuote(tmpFile)}`;
|
||||
return await this.execRaw(
|
||||
client,
|
||||
serverId,
|
||||
execCmd,
|
||||
pwBuf,
|
||||
opts.timeoutMs,
|
||||
opts.maxBytes,
|
||||
);
|
||||
} finally {
|
||||
pwBuf.fill(0);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
rawStdinBuf.fill(0);
|
||||
await this.execRaw(client, serverId, `rm -f -- ${posixSingleQuote(tmpFile)}`, undefined, 5_000, 1024).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rawStdinBuf?.fill(0);
|
||||
|
||||
const { finalCommand, stdinBuf } = this.prepareCommand(server, command, opts);
|
||||
return this.execRaw(client, serverId, finalCommand, stdinBuf, opts.timeoutMs, opts.maxBytes);
|
||||
}
|
||||
|
||||
private execRaw(
|
||||
client: Client,
|
||||
serverId: string,
|
||||
finalCommand: string,
|
||||
stdinBuf: Buffer | undefined,
|
||||
timeoutMs = DEFAULT_EXEC_TIMEOUT_MS,
|
||||
maxBytes = DEFAULT_MAX_BYTES,
|
||||
): Promise<ExecResult> {
|
||||
const started = Date.now();
|
||||
|
||||
return new Promise<ExecResult>((resolve, reject) => {
|
||||
|
|
@ -341,6 +500,7 @@ export class SSHPool {
|
|||
reject(new Error(`SSH exec timed out after ${timeoutMs}ms on "${serverId}"`)),
|
||||
);
|
||||
}, timeoutMs);
|
||||
timer.unref();
|
||||
|
||||
if (stdinBuf && stdinBuf.length > 0) {
|
||||
stream.stdin.write(stdinBuf);
|
||||
|
|
@ -501,6 +661,112 @@ export class SSHPool {
|
|||
}
|
||||
}
|
||||
|
||||
async testConnection(candidate: ServerConfig): Promise<ServerTestResult> {
|
||||
const started = Date.now();
|
||||
if (!this.vaultService.isRuntimeReady) {
|
||||
return { ok: false, latencyMs: 0, error: 'Vault is locked' };
|
||||
}
|
||||
const cred = this.vaultService.getRuntimeSecret(candidate.credentialId);
|
||||
if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) {
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: 0,
|
||||
error: `Missing or incompatible SSH credential "${candidate.credentialId}" in Vault`,
|
||||
};
|
||||
}
|
||||
|
||||
let hopStream: Duplex | undefined;
|
||||
const settings = this.configManager.getSettings();
|
||||
const client = new ssh2.Client();
|
||||
let observedFp: string | undefined;
|
||||
|
||||
try {
|
||||
if (candidate.jumpHostId) {
|
||||
const bastion = await this.acquireClient(
|
||||
candidate.jumpHostId,
|
||||
new Set([candidate.id]),
|
||||
);
|
||||
hopStream = await forwardOutOnClient(
|
||||
bastion,
|
||||
'127.0.0.1',
|
||||
0,
|
||||
candidate.host,
|
||||
candidate.port,
|
||||
);
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const done = (err?: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
};
|
||||
client.once('ready', () => done());
|
||||
client.once('error', (err) => done(err));
|
||||
client.once('close', () => done(new Error('SSH connection closed during test')));
|
||||
|
||||
const cfg: ConnectConfig = {
|
||||
username: candidate.username,
|
||||
readyTimeout: settings.sshReadyTimeoutMs,
|
||||
hostVerifier: (keyBuf: Buffer) => {
|
||||
const verified = this.knownHosts.verifyServerHostKey(candidate, keyBuf);
|
||||
const tofu = this.knownHosts.getPendingTofu(candidate.id);
|
||||
const mismatch = this.knownHosts.getPendingMismatch(candidate.id);
|
||||
observedFp = mismatch?.actualFingerprint ?? tofu?.fingerprint;
|
||||
return verified;
|
||||
},
|
||||
};
|
||||
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 = candidate.host;
|
||||
cfg.port = candidate.port;
|
||||
}
|
||||
client.connect(cfg);
|
||||
});
|
||||
|
||||
const uname = await this.execRaw(client, candidate.id, 'uname -s', undefined, 5_000, 512);
|
||||
const rawOs = uname.stdout.trim().toLowerCase();
|
||||
const osDetected = rawOs.includes('freebsd') || rawOs.includes('openbsd') || rawOs.includes('netbsd')
|
||||
? 'bsd'
|
||||
: rawOs.includes('darwin')
|
||||
? 'macos'
|
||||
: 'linux';
|
||||
return {
|
||||
ok: true,
|
||||
latencyMs: Date.now() - started,
|
||||
osDetected,
|
||||
hostFingerprint: observedFp,
|
||||
};
|
||||
} catch (err) {
|
||||
const tofu = this.knownHosts.getPendingTofu(candidate.id);
|
||||
const mismatch = this.knownHosts.getPendingMismatch(candidate.id);
|
||||
return {
|
||||
ok: false,
|
||||
latencyMs: Date.now() - started,
|
||||
hostFingerprint: mismatch?.actualFingerprint ?? tofu?.fingerprint ?? observedFp,
|
||||
tofuRequired: Boolean(tofu),
|
||||
hostKeyMismatch: mismatch,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
};
|
||||
} finally {
|
||||
try {
|
||||
client.end();
|
||||
client.destroy();
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
hopStream?.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
async reconnect(serverId: string): Promise<Client> {
|
||||
this.closeServer(serverId);
|
||||
this.reconnectAttempts.delete(serverId);
|
||||
|
|
@ -542,12 +808,27 @@ export class SSHPool {
|
|||
}
|
||||
|
||||
closeServer(serverId: string): void {
|
||||
this.serverEpoch.set(serverId, this.getServerEpoch(serverId) + 1);
|
||||
this.inFlight.delete(serverId);
|
||||
const timer = this.reconnectTimers.get(serverId);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this.reconnectTimers.delete(serverId);
|
||||
}
|
||||
|
||||
const pendingSet = this.pendingClients.get(serverId);
|
||||
if (pendingSet) {
|
||||
for (const c of [...pendingSet]) {
|
||||
try {
|
||||
c.end();
|
||||
c.destroy();
|
||||
} catch {
|
||||
// Ignore pending client destroy error
|
||||
}
|
||||
}
|
||||
this.pendingClients.delete(serverId);
|
||||
}
|
||||
|
||||
const conn = this.connections.get(serverId);
|
||||
if (!conn) return;
|
||||
|
||||
|
|
@ -575,6 +856,8 @@ export class SSHPool {
|
|||
}
|
||||
|
||||
closeAll(reason: 'panic_lock' | 'shutdown' | 'vault_sealed'): void {
|
||||
this.poolEpoch += 1;
|
||||
this.inFlight.clear();
|
||||
if (reason === 'shutdown') {
|
||||
this.closed = true;
|
||||
}
|
||||
|
|
@ -584,6 +867,18 @@ export class SSHPool {
|
|||
}
|
||||
this.reconnectTimers.clear();
|
||||
|
||||
for (const [id, pendingSet] of [...this.pendingClients.entries()]) {
|
||||
for (const c of [...pendingSet]) {
|
||||
try {
|
||||
c.end();
|
||||
c.destroy();
|
||||
} catch {
|
||||
// Ignore destroy error
|
||||
}
|
||||
}
|
||||
this.pendingClients.delete(id);
|
||||
}
|
||||
|
||||
for (const id of [...this.connections.keys()]) {
|
||||
this.closeServer(id);
|
||||
}
|
||||
|
|
@ -604,6 +899,8 @@ export class SSHPool {
|
|||
private async connectServer(
|
||||
server: ServerConfig,
|
||||
visited: Set<string>,
|
||||
startPoolEpoch: number,
|
||||
startSrvEpoch: number,
|
||||
): Promise<Client> {
|
||||
const cred = this.vaultService.getRuntimeSecret(server.credentialId);
|
||||
if (!cred || (cred.type !== 'ssh-key' && cred.type !== 'ssh-password')) {
|
||||
|
|
@ -617,6 +914,14 @@ export class SSHPool {
|
|||
let hopStream: Duplex | undefined;
|
||||
if (server.jumpHostId) {
|
||||
const bastion = await this.acquireClient(server.jumpHostId, visited);
|
||||
if (
|
||||
this.closed ||
|
||||
!this.vaultService.isRuntimeReady ||
|
||||
this.poolEpoch !== startPoolEpoch ||
|
||||
this.getServerEpoch(server.id) !== startSrvEpoch
|
||||
) {
|
||||
throw new Error('SSH connection aborted due to pool reset or Vault lock');
|
||||
}
|
||||
hopStream = await forwardOutOnClient(
|
||||
bastion,
|
||||
'127.0.0.1',
|
||||
|
|
@ -628,6 +933,20 @@ export class SSHPool {
|
|||
|
||||
const settings = this.configManager.getSettings();
|
||||
const client = new ssh2.Client();
|
||||
let setForServer = this.pendingClients.get(server.id);
|
||||
if (!setForServer) {
|
||||
setForServer = new Set();
|
||||
this.pendingClients.set(server.id, setForServer);
|
||||
}
|
||||
setForServer.add(client);
|
||||
|
||||
const untrackPending = () => {
|
||||
const s = this.pendingClients.get(server.id);
|
||||
if (s) {
|
||||
s.delete(client);
|
||||
if (s.size === 0) this.pendingClients.delete(server.id);
|
||||
}
|
||||
};
|
||||
|
||||
return new Promise<Client>((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
|
@ -635,6 +954,7 @@ export class SSHPool {
|
|||
const failConnect = (err: Error) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
untrackPending();
|
||||
hopStream?.destroy();
|
||||
try {
|
||||
client.destroy();
|
||||
|
|
@ -642,6 +962,16 @@ export class SSHPool {
|
|||
// Ignore destroy failure
|
||||
}
|
||||
|
||||
if (
|
||||
this.closed ||
|
||||
!this.vaultService.isRuntimeReady ||
|
||||
this.poolEpoch !== startPoolEpoch ||
|
||||
this.getServerEpoch(server.id) !== startSrvEpoch
|
||||
) {
|
||||
reject(err);
|
||||
return;
|
||||
}
|
||||
|
||||
const mismatch = this.knownHosts.getPendingMismatch(server.id);
|
||||
const tofu = this.knownHosts.getPendingTofu(server.id);
|
||||
let status: ServerConnectionStatus = 'disconnected';
|
||||
|
|
@ -664,8 +994,23 @@ export class SSHPool {
|
|||
};
|
||||
|
||||
client.once('ready', () => {
|
||||
if (settled) {
|
||||
client.end();
|
||||
untrackPending();
|
||||
const invalidated =
|
||||
settled ||
|
||||
this.closed ||
|
||||
!this.vaultService.isRuntimeReady ||
|
||||
this.poolEpoch !== startPoolEpoch ||
|
||||
this.getServerEpoch(server.id) !== startSrvEpoch;
|
||||
if (invalidated) {
|
||||
settled = true;
|
||||
hopStream?.destroy();
|
||||
try {
|
||||
client.end();
|
||||
client.destroy();
|
||||
} catch {
|
||||
// Ignore close failure
|
||||
}
|
||||
reject(new Error('SSH connection aborted due to Panic Lock, seal, or reset'));
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
|
|
@ -710,6 +1055,16 @@ export class SSHPool {
|
|||
}
|
||||
});
|
||||
|
||||
if (
|
||||
this.closed ||
|
||||
!this.vaultService.isRuntimeReady ||
|
||||
this.poolEpoch !== startPoolEpoch ||
|
||||
this.getServerEpoch(server.id) !== startSrvEpoch
|
||||
) {
|
||||
failConnect(new Error('SSH connection aborted due to pool reset or Vault lock'));
|
||||
return;
|
||||
}
|
||||
|
||||
const cfg: ConnectConfig = {
|
||||
username: server.username,
|
||||
keepaliveInterval: settings.sshKeepaliveMs,
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
export const SUDO_PTY_PROMPT = '[gcoord-sudo-prompt] ';
|
||||
|
||||
export function posixSingleQuote(value: string): string {
|
||||
return `'${value.replace(/'/g, "'\\''")}'`;
|
||||
}
|
||||
|
|
@ -16,13 +18,31 @@ export function buildEnvPrefix(env?: Record<string, string>): string {
|
|||
|
||||
export function prepareSudoExecution(
|
||||
command: string,
|
||||
options: { sudoPassword?: string; stdin?: Buffer | string } = {},
|
||||
): { command: string; stdin?: Buffer } {
|
||||
options: {
|
||||
sudoPassword?: string;
|
||||
stdin?: Buffer | string;
|
||||
ptyPrompt?: boolean;
|
||||
} = {},
|
||||
): { command: string; stdin?: Buffer; ptyPassword?: string } {
|
||||
const quoted = posixSingleQuote(command);
|
||||
if (options.sudoPassword !== undefined && options.sudoPassword.length > 0) {
|
||||
if (options.ptyPrompt) {
|
||||
const extraStdin =
|
||||
options.stdin === undefined
|
||||
? undefined
|
||||
: typeof options.stdin === 'string'
|
||||
? Buffer.from(options.stdin, 'utf8')
|
||||
: Buffer.from(options.stdin);
|
||||
return {
|
||||
command: `sudo -S -k -p ${posixSingleQuote(SUDO_PTY_PROMPT)} sh -c ${quoted}`,
|
||||
stdin: extraStdin,
|
||||
ptyPassword: options.sudoPassword,
|
||||
};
|
||||
}
|
||||
|
||||
const pwPrefix = Buffer.from(`${options.sudoPassword}\n`, 'utf8');
|
||||
let combined = pwPrefix;
|
||||
if (options.stdin !== undefined) {
|
||||
if (options.stdin !== undefined && options.stdin.length > 0) {
|
||||
const extra =
|
||||
typeof options.stdin === 'string'
|
||||
? Buffer.from(options.stdin, 'utf8')
|
||||
|
|
@ -31,7 +51,7 @@ export function prepareSudoExecution(
|
|||
pwPrefix.fill(0);
|
||||
}
|
||||
return {
|
||||
command: `sudo -S -p '' sh -c ${quoted}`,
|
||||
command: `sudo -S -k -p '' sh -c ${quoted}`,
|
||||
stdin: combined,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -401,7 +401,27 @@ export class MockSshServer {
|
|||
let stdin = rawStdin;
|
||||
|
||||
// Handle sudo wrappers produced by prepareSudoExecution
|
||||
if (command.startsWith("sudo -S -p '' sh -c ")) {
|
||||
if (command.startsWith("sudo -S -k -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 -k -p '' sh -c ".length));
|
||||
} else if (command.startsWith("sudo -S -k -p '[gcoord-sudo-prompt] ' 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 -k -p '[gcoord-sudo-prompt] ' sh -c ".length),
|
||||
);
|
||||
} else 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;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue