315 lines
9.2 KiB
TypeScript
315 lines
9.2 KiB
TypeScript
import crypto from 'node:crypto';
|
|
import type Database from 'better-sqlite3';
|
|
import type { ServerConfig } from '../../shared/schemas/server.schema.js';
|
|
import type { HostKeyAlert, PendingTofuInfo } from '../../shared/ws-protocol.js';
|
|
import type { AuditService } from '../security/audit.js';
|
|
|
|
export interface KnownHostRecord {
|
|
hostPort: string;
|
|
algorithm: string;
|
|
fingerprint: string;
|
|
trustedAt: number;
|
|
updatedAt: number;
|
|
}
|
|
|
|
export function buildHostPortKey(server: Pick<ServerConfig, 'host' | 'port' | 'jumpHostId'>): string {
|
|
const hostLower = server.host.trim().toLowerCase();
|
|
return server.jumpHostId
|
|
? `${server.jumpHostId}->${hostLower}:${server.port}`
|
|
: `${hostLower}:${server.port}`;
|
|
}
|
|
|
|
export function parseHostKeyBuffer(keyBuf: Buffer): {
|
|
algorithm: string;
|
|
fingerprint: string;
|
|
} {
|
|
let algorithm = 'unknown';
|
|
if (keyBuf.length >= 4) {
|
|
const algoLen = keyBuf.readUInt32BE(0);
|
|
if (algoLen > 0 && 4 + algoLen <= keyBuf.length) {
|
|
algorithm = keyBuf.subarray(4, 4 + algoLen).toString('ascii');
|
|
}
|
|
}
|
|
const digest = crypto
|
|
.createHash('sha256')
|
|
.update(keyBuf)
|
|
.digest('base64')
|
|
.replace(/=+$/, '');
|
|
return {
|
|
algorithm,
|
|
fingerprint: `SHA256:${digest}`,
|
|
};
|
|
}
|
|
|
|
export class KnownHostsService {
|
|
private readonly pendingTofu = new Map<string, PendingTofuInfo>();
|
|
private readonly pendingMismatches = new Map<string, HostKeyAlert>();
|
|
private readonly listeners = new Set<() => void>();
|
|
|
|
constructor(
|
|
private readonly db: Database.Database,
|
|
private readonly auditService?: AuditService,
|
|
) {}
|
|
|
|
onChange(listener: () => void): () => void {
|
|
this.listeners.add(listener);
|
|
return () => {
|
|
this.listeners.delete(listener);
|
|
};
|
|
}
|
|
|
|
verifyServerHostKey(server: ServerConfig, keyBuf: Buffer): boolean {
|
|
const hostPortKey = buildHostPortKey(server);
|
|
const { algorithm, fingerprint } = parseHostKeyBuffer(keyBuf);
|
|
const now = Date.now();
|
|
|
|
const row = this.db
|
|
.prepare(
|
|
'SELECT host_port AS hostPort, algorithm, fingerprint, trusted_at AS trustedAt, updated_at AS updatedAt FROM known_hosts WHERE host_port = ?',
|
|
)
|
|
.get(hostPortKey) as KnownHostRecord | undefined;
|
|
|
|
if (row) {
|
|
if (row.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);
|
|
if (hadPending) this.emitChange();
|
|
return true;
|
|
}
|
|
|
|
const alert: HostKeyAlert = {
|
|
serverId: server.id,
|
|
hostPortKey,
|
|
host: server.host,
|
|
port: server.port,
|
|
algorithm,
|
|
expectedFingerprint: row.fingerprint,
|
|
actualFingerprint: fingerprint,
|
|
detectedAt: now,
|
|
};
|
|
this.pendingTofu.delete(server.id);
|
|
this.pendingMismatches.set(server.id, alert);
|
|
this.auditService?.log({
|
|
action: 'ssh.host_key_mismatch',
|
|
actorIp: 'hub',
|
|
target: server.id,
|
|
status: 'denied',
|
|
details: {
|
|
hostPortKey,
|
|
expected: row.fingerprint,
|
|
actual: fingerprint,
|
|
},
|
|
});
|
|
this.emitChange();
|
|
return false;
|
|
}
|
|
|
|
// No known_hosts entry yet: check optional pre-seeded fingerprint in server JSON
|
|
if (server.hostKeyFingerprint) {
|
|
const expected = server.hostKeyFingerprint.trim();
|
|
if (expected === fingerprint) {
|
|
this.upsertKnownHost(hostPortKey, algorithm, fingerprint, now);
|
|
this.pendingTofu.delete(server.id);
|
|
this.pendingMismatches.delete(server.id);
|
|
this.auditService?.log({
|
|
action: 'ssh.host_key_preseeded',
|
|
actorIp: 'hub',
|
|
target: server.id,
|
|
status: 'ok',
|
|
details: { hostPortKey, fingerprint },
|
|
});
|
|
this.emitChange();
|
|
return true;
|
|
}
|
|
|
|
const alert: HostKeyAlert = {
|
|
serverId: server.id,
|
|
hostPortKey,
|
|
host: server.host,
|
|
port: server.port,
|
|
algorithm,
|
|
expectedFingerprint: expected,
|
|
actualFingerprint: fingerprint,
|
|
detectedAt: now,
|
|
};
|
|
this.pendingMismatches.set(server.id, alert);
|
|
this.auditService?.log({
|
|
action: 'ssh.host_key_mismatch',
|
|
actorIp: 'hub',
|
|
target: server.id,
|
|
status: 'denied',
|
|
details: { hostPortKey, expected, actual: fingerprint },
|
|
});
|
|
this.emitChange();
|
|
return false;
|
|
}
|
|
|
|
// Strict TOFU: pause and require explicit admin confirmation
|
|
this.pendingMismatches.delete(server.id);
|
|
this.pendingTofu.set(server.id, {
|
|
serverId: server.id,
|
|
hostPortKey,
|
|
host: server.host,
|
|
port: server.port,
|
|
algorithm,
|
|
fingerprint,
|
|
firstSeenAt: now,
|
|
});
|
|
this.emitChange();
|
|
return false;
|
|
}
|
|
|
|
approveTofu(serverId: string, fingerprint: string): KnownHostRecord {
|
|
const pending = this.pendingTofu.get(serverId);
|
|
if (!pending) {
|
|
throw new Error(`No pending TOFU host key awaiting approval for "${serverId}"`);
|
|
}
|
|
if (pending.fingerprint !== fingerprint.trim()) {
|
|
throw new Error('TOFU fingerprint mismatch; re-verify before approving');
|
|
}
|
|
|
|
const now = Date.now();
|
|
this.upsertKnownHost(pending.hostPortKey, pending.algorithm, pending.fingerprint, now);
|
|
this.pendingTofu.delete(serverId);
|
|
this.emitChange();
|
|
|
|
return {
|
|
hostPort: pending.hostPortKey,
|
|
algorithm: pending.algorithm,
|
|
fingerprint: pending.fingerprint,
|
|
trustedAt: now,
|
|
updatedAt: now,
|
|
};
|
|
}
|
|
|
|
resetMismatch(serverId: string, newFingerprint: string): KnownHostRecord {
|
|
const mismatch = this.pendingMismatches.get(serverId);
|
|
if (!mismatch) {
|
|
throw new Error(`No host key mismatch recorded for "${serverId}"`);
|
|
}
|
|
if (mismatch.actualFingerprint !== newFingerprint.trim()) {
|
|
throw new Error('Provided fingerprint does not match observed remote host key');
|
|
}
|
|
|
|
const now = Date.now();
|
|
this.upsertKnownHost(
|
|
mismatch.hostPortKey,
|
|
mismatch.algorithm,
|
|
mismatch.actualFingerprint,
|
|
now,
|
|
);
|
|
this.pendingMismatches.delete(serverId);
|
|
this.emitChange();
|
|
|
|
return {
|
|
hostPort: mismatch.hostPortKey,
|
|
algorithm: mismatch.algorithm,
|
|
fingerprint: mismatch.actualFingerprint,
|
|
trustedAt: now,
|
|
updatedAt: now,
|
|
};
|
|
}
|
|
|
|
clearServerPending(serverId: string): void {
|
|
const changed =
|
|
this.pendingTofu.delete(serverId) || this.pendingMismatches.delete(serverId);
|
|
if (changed) this.emitChange();
|
|
}
|
|
|
|
getPendingTofu(serverId: string): PendingTofuInfo | undefined {
|
|
return this.pendingTofu.get(serverId);
|
|
}
|
|
|
|
listPendingTofu(): PendingTofuInfo[] {
|
|
return [...this.pendingTofu.values()];
|
|
}
|
|
|
|
getPendingMismatch(serverId: string): HostKeyAlert | undefined {
|
|
return this.pendingMismatches.get(serverId);
|
|
}
|
|
|
|
listPendingMismatches(): HostKeyAlert[] {
|
|
return [...this.pendingMismatches.values()];
|
|
}
|
|
|
|
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',
|
|
)
|
|
.all() as KnownHostRecord[];
|
|
}
|
|
|
|
replaceAllKnownHosts(
|
|
records: Array<
|
|
Pick<KnownHostRecord, 'hostPort' | 'algorithm' | 'fingerprint'> &
|
|
Partial<Pick<KnownHostRecord, 'trustedAt' | 'updatedAt'>>
|
|
>,
|
|
): void {
|
|
const now = Date.now();
|
|
const tx = this.db.transaction(() => {
|
|
this.db.prepare('DELETE FROM known_hosts').run();
|
|
const ins = this.db.prepare(
|
|
`INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at)
|
|
VALUES (?, ?, ?, ?, ?)`,
|
|
);
|
|
for (const r of records) {
|
|
ins.run(
|
|
r.hostPort,
|
|
r.algorithm,
|
|
r.fingerprint,
|
|
r.trustedAt ?? now,
|
|
r.updatedAt ?? now,
|
|
);
|
|
}
|
|
});
|
|
tx();
|
|
this.pendingTofu.clear();
|
|
this.pendingMismatches.clear();
|
|
this.emitChange();
|
|
}
|
|
|
|
deleteKnownHost(hostPort: string): boolean {
|
|
const res = 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);
|
|
}
|
|
for (const [sid, m] of this.pendingMismatches.entries()) {
|
|
if (m.hostPortKey === hostPort) this.pendingMismatches.delete(sid);
|
|
}
|
|
if (res.changes > 0) this.emitChange();
|
|
return res.changes > 0;
|
|
}
|
|
|
|
private upsertKnownHost(
|
|
hostPortKey: string,
|
|
algorithm: string,
|
|
fingerprint: string,
|
|
now: number,
|
|
): void {
|
|
this.db
|
|
.prepare(
|
|
`INSERT INTO known_hosts (host_port, algorithm, fingerprint, trusted_at, updated_at)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
ON CONFLICT(host_port, algorithm) DO UPDATE SET
|
|
fingerprint = excluded.fingerprint,
|
|
updated_at = excluded.updated_at`,
|
|
)
|
|
.run(hostPortKey, algorithm, fingerprint, now, now);
|
|
}
|
|
|
|
private emitChange(): void {
|
|
for (const listener of this.listeners) {
|
|
try {
|
|
listener();
|
|
} catch {
|
|
// Isolate subscriber failures
|
|
}
|
|
}
|
|
}
|
|
}
|