feat(ssh): implement authorized_keys manager and atomic zero-lockout Ed25519 key rotation
This commit is contained in:
parent
b742f0ebf8
commit
45f0ff630f
1 changed files with 425 additions and 0 deletions
425
src/server/ssh/key-manager.ts
Normal file
425
src/server/ssh/key-manager.ts
Normal file
|
|
@ -0,0 +1,425 @@
|
|||
import crypto from 'node:crypto';
|
||||
import type { VaultCredentialMeta } from '../../shared/schemas/vault.schema.js';
|
||||
import type { ConfigManager } from '../config/config-manager.js';
|
||||
import type { AuditService } from '../security/audit.js';
|
||||
import { computeOpenSshFingerprint, type VaultService } from '../security/vault.js';
|
||||
import type { SSHPool } from './ssh-pool.js';
|
||||
|
||||
const OPENSSH_KEY_TYPES = new Set([
|
||||
'ssh-ed25519',
|
||||
'ssh-rsa',
|
||||
'ssh-dss',
|
||||
'ecdsa-sha2-nistp256',
|
||||
'ecdsa-sha2-nistp384',
|
||||
'ecdsa-sha2-nistp521',
|
||||
'sk-ssh-ed25519@openssh.com',
|
||||
'sk-ecdsa-sha2-nistp256@openssh.com',
|
||||
]);
|
||||
|
||||
export interface AuthorizedKeyEntry {
|
||||
lineNumber: number;
|
||||
rawLine: string;
|
||||
options?: string;
|
||||
keyType: string;
|
||||
fingerprint: string;
|
||||
comment?: string;
|
||||
isCurrentServerKey: boolean;
|
||||
matchedVaultCredentialId?: string;
|
||||
}
|
||||
|
||||
export interface KeyRotationResult {
|
||||
serverId: string;
|
||||
ok: boolean;
|
||||
rolledBack?: boolean;
|
||||
oldCredentialId?: string;
|
||||
newCredentialId?: string;
|
||||
fingerprint?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
function splitTokensRespectingQuotes(line: string): Array<{ text: string; start: number }> {
|
||||
const tokens: Array<{ text: string; start: number }> = [];
|
||||
let i = 0;
|
||||
while (i < line.length) {
|
||||
while (i < line.length && /\s/.test(line[i]!)) i++;
|
||||
if (i >= line.length) break;
|
||||
const start = i;
|
||||
let inQuotes = false;
|
||||
let escaped = false;
|
||||
while (i < line.length) {
|
||||
const ch = line[i]!;
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
} else if (ch === '\\' && inQuotes) {
|
||||
escaped = true;
|
||||
} else if (ch === '"') {
|
||||
inQuotes = !inQuotes;
|
||||
} else if (!inQuotes && /\s/.test(ch)) {
|
||||
break;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
tokens.push({ text: line.slice(start, i), start });
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
export function parseAuthorizedKeys(
|
||||
content: string,
|
||||
vaultCreds: VaultCredentialMeta[] = [],
|
||||
activeCredentialId?: string,
|
||||
): AuthorizedKeyEntry[] {
|
||||
const byFingerprint = new Map<string, VaultCredentialMeta>();
|
||||
for (const cred of vaultCreds) {
|
||||
if (cred.type === 'ssh-key' && cred.fingerprint) {
|
||||
byFingerprint.set(cred.fingerprint, cred);
|
||||
}
|
||||
}
|
||||
|
||||
const lines = content.split(/\r?\n/);
|
||||
const entries: AuthorizedKeyEntry[] = [];
|
||||
|
||||
lines.forEach((rawLine, idx) => {
|
||||
const trimmed = rawLine.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) return;
|
||||
|
||||
const tokens = splitTokensRespectingQuotes(trimmed);
|
||||
const keyTypeIdx = tokens.findIndex((t) => OPENSSH_KEY_TYPES.has(t.text));
|
||||
if (keyTypeIdx < 0 || keyTypeIdx + 1 >= tokens.length) return;
|
||||
|
||||
const keyTypeTok = tokens[keyTypeIdx]!;
|
||||
const keyDataTok = tokens[keyTypeIdx + 1]!;
|
||||
const options =
|
||||
keyTypeIdx > 0 ? trimmed.slice(0, keyTypeTok.start).trim() : undefined;
|
||||
const commentStart =
|
||||
keyTypeIdx + 2 < tokens.length ? tokens[keyTypeIdx + 2]!.start : -1;
|
||||
const comment = commentStart >= 0 ? trimmed.slice(commentStart).trim() : undefined;
|
||||
|
||||
try {
|
||||
const fingerprint = computeOpenSshFingerprint(
|
||||
`${keyTypeTok.text} ${keyDataTok.text}`,
|
||||
);
|
||||
const matched = byFingerprint.get(fingerprint);
|
||||
entries.push({
|
||||
lineNumber: idx + 1,
|
||||
rawLine,
|
||||
options,
|
||||
keyType: keyTypeTok.text,
|
||||
fingerprint,
|
||||
comment: comment || undefined,
|
||||
matchedVaultCredentialId: matched?.id,
|
||||
isCurrentServerKey: Boolean(
|
||||
activeCredentialId && matched?.id === activeCredentialId,
|
||||
),
|
||||
});
|
||||
} catch {
|
||||
// Skip malformed key blobs
|
||||
}
|
||||
});
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function normalizeAuthorizedKeysContent(lines: string[]): string {
|
||||
const filtered = lines.map((l) => l.replace(/\r$/, '')).filter((l, idx, arr) => {
|
||||
// Keep non-empty lines; collapse trailing blank lines cleanly
|
||||
return idx < arr.length - 1 || l.length > 0;
|
||||
});
|
||||
return filtered.length > 0 ? `${filtered.join('\n')}\n` : '';
|
||||
}
|
||||
|
||||
function makeRotatedCredentialId(serverId: string): string {
|
||||
const suffix = `${Date.now().toString(36)}-${crypto.randomBytes(2).toString('hex')}`;
|
||||
const prefix = serverId.slice(0, Math.max(1, 64 - suffix.length - 1));
|
||||
return `${prefix}-${suffix}`;
|
||||
}
|
||||
|
||||
export class KeyManager {
|
||||
constructor(
|
||||
private readonly sshPool: SSHPool,
|
||||
private readonly vaultService: VaultService,
|
||||
private readonly configManager: ConfigManager,
|
||||
private readonly auditService: AuditService,
|
||||
) {}
|
||||
|
||||
async inspectAuthorizedKeys(serverId: string): Promise<{
|
||||
raw: string;
|
||||
entries: AuthorizedKeyEntry[];
|
||||
}> {
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server) {
|
||||
throw new Error(`Unknown server "${serverId}"`);
|
||||
}
|
||||
|
||||
const res = await this.sshPool.exec(
|
||||
serverId,
|
||||
'[ -f ~/.ssh/authorized_keys ] && cat ~/.ssh/authorized_keys || true',
|
||||
);
|
||||
if (res.exitCode !== 0) {
|
||||
throw new Error(
|
||||
`Failed to read ~/.ssh/authorized_keys on "${serverId}": ${res.stderr.trim()}`,
|
||||
);
|
||||
}
|
||||
|
||||
const vaultCreds =
|
||||
this.vaultService.state === 'unlocked' ? this.vaultService.listMetadata() : [];
|
||||
const entries = parseAuthorizedKeys(res.stdout, vaultCreds, server.credentialId);
|
||||
return { raw: res.stdout, entries };
|
||||
}
|
||||
|
||||
async deployVaultKey(
|
||||
serverId: string,
|
||||
credentialId: string,
|
||||
actor = { ip: 'hub', sessionIdHash: null as string | null },
|
||||
): Promise<{ deployed: boolean; alreadyPresent: boolean; fingerprint: string }> {
|
||||
const cred = this.vaultService.getSecret(credentialId);
|
||||
if (!cred || cred.type !== 'ssh-key' || !cred.publicKey) {
|
||||
throw new Error(`Vault credential "${credentialId}" is not an SSH key with a publicKey`);
|
||||
}
|
||||
const pubLine = cred.publicKey.trim();
|
||||
const fingerprint = cred.fingerprint ?? computeOpenSshFingerprint(pubLine);
|
||||
|
||||
const { raw, entries } = await this.inspectAuthorizedKeys(serverId);
|
||||
if (entries.some((e) => e.fingerprint === fingerprint)) {
|
||||
return { deployed: false, alreadyPresent: true, fingerprint };
|
||||
}
|
||||
|
||||
const lines = raw ? raw.split(/\r?\n/) : [];
|
||||
const nextContent = normalizeAuthorizedKeysContent([...lines, pubLine]);
|
||||
await this.writeAuthorizedKeysAtomic(serverId, nextContent);
|
||||
|
||||
this.auditService.log({
|
||||
action: 'ssh.key_deploy',
|
||||
actorIp: actor.ip,
|
||||
sessionIdHash: actor.sessionIdHash,
|
||||
target: `${serverId}:${credentialId}`,
|
||||
status: 'ok',
|
||||
details: { fingerprint },
|
||||
});
|
||||
|
||||
return { deployed: true, alreadyPresent: false, fingerprint };
|
||||
}
|
||||
|
||||
async revokeAuthorizedKey(
|
||||
serverId: string,
|
||||
fingerprint: string,
|
||||
options: { force?: boolean; actorIp?: string; sessionIdHash?: string | null } = {},
|
||||
): Promise<{ removedCount: number }> {
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server) {
|
||||
throw new Error(`Unknown server "${serverId}"`);
|
||||
}
|
||||
|
||||
const activeCred = this.vaultService.getSecret(server.credentialId);
|
||||
const activeFp =
|
||||
activeCred?.type === 'ssh-key'
|
||||
? activeCred.fingerprint ??
|
||||
(activeCred.publicKey ? computeOpenSshFingerprint(activeCred.publicKey) : undefined)
|
||||
: undefined;
|
||||
|
||||
if (activeFp && activeFp === fingerprint && !options.force) {
|
||||
throw new Error(
|
||||
'Refusing to revoke the active GCoordinator SSH key without force=true',
|
||||
);
|
||||
}
|
||||
|
||||
const { raw, entries } = await this.inspectAuthorizedKeys(serverId);
|
||||
const matchingLines = new Set(
|
||||
entries.filter((e) => e.fingerprint === fingerprint).map((e) => e.lineNumber),
|
||||
);
|
||||
if (matchingLines.size === 0) {
|
||||
return { removedCount: 0 };
|
||||
}
|
||||
|
||||
const keptLines = raw
|
||||
.split(/\r?\n/)
|
||||
.filter((_line, idx) => !matchingLines.has(idx + 1));
|
||||
await this.writeAuthorizedKeysAtomic(
|
||||
serverId,
|
||||
normalizeAuthorizedKeysContent(keptLines),
|
||||
);
|
||||
|
||||
this.auditService.log({
|
||||
action: 'ssh.key_revoke',
|
||||
actorIp: options.actorIp ?? 'hub',
|
||||
sessionIdHash: options.sessionIdHash ?? null,
|
||||
target: serverId,
|
||||
status: 'ok',
|
||||
details: { fingerprint, removedCount: matchingLines.size },
|
||||
});
|
||||
|
||||
return { removedCount: matchingLines.size };
|
||||
}
|
||||
|
||||
async rotateKeys(options: {
|
||||
serverIds: string[];
|
||||
passphrase?: string;
|
||||
actorIp?: string;
|
||||
sessionIdHash?: string | null;
|
||||
}): Promise<KeyRotationResult[]> {
|
||||
const results: KeyRotationResult[] = [];
|
||||
for (const serverId of options.serverIds) {
|
||||
results.push(
|
||||
await this.rotateSingleServer(
|
||||
serverId,
|
||||
options.passphrase,
|
||||
options.actorIp ?? 'hub',
|
||||
options.sessionIdHash ?? null,
|
||||
),
|
||||
);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private async rotateSingleServer(
|
||||
serverId: string,
|
||||
passphrase: string | undefined,
|
||||
actorIp: string,
|
||||
sessionIdHash: string | null,
|
||||
): Promise<KeyRotationResult> {
|
||||
const server = this.configManager.getServer(serverId);
|
||||
if (!server) {
|
||||
return { serverId, ok: false, error: `Unknown server "${serverId}"` };
|
||||
}
|
||||
|
||||
const oldCred = this.vaultService.getSecret(server.credentialId);
|
||||
const oldFingerprint =
|
||||
oldCred?.type === 'ssh-key'
|
||||
? oldCred.fingerprint ??
|
||||
(oldCred.publicKey ? computeOpenSshFingerprint(oldCred.publicKey) : undefined)
|
||||
: undefined;
|
||||
|
||||
const newCredId = makeRotatedCredentialId(server.id);
|
||||
const newMeta = this.vaultService.generateEd25519Credential({
|
||||
id: newCredId,
|
||||
name: `${server.name} Key (${new Date().toISOString().slice(0, 10)})`,
|
||||
comment: `gcoord-${server.id}`,
|
||||
passphrase,
|
||||
});
|
||||
const newSecret = this.vaultService.getSecret(newCredId);
|
||||
if (newSecret?.type !== 'ssh-key' || !newSecret.publicKey) {
|
||||
this.vaultService.deleteCredential(newCredId);
|
||||
return { serverId, ok: false, error: 'Failed to read generated Ed25519 key' };
|
||||
}
|
||||
|
||||
let originalRaw = '';
|
||||
let appended = false;
|
||||
|
||||
try {
|
||||
const inspected = await this.inspectAuthorizedKeys(serverId);
|
||||
originalRaw = inspected.raw;
|
||||
|
||||
const updatedRaw = normalizeAuthorizedKeysContent([
|
||||
...originalRaw.split(/\r?\n/),
|
||||
newSecret.publicKey.trim(),
|
||||
]);
|
||||
await this.writeAuthorizedKeysAtomic(serverId, updatedRaw);
|
||||
appended = true;
|
||||
|
||||
// Step 3: Strict fresh handshake authenticating ONLY with the new key
|
||||
await this.sshPool.verifyStandaloneKeyAuth(
|
||||
server,
|
||||
newSecret.privateKey,
|
||||
newSecret.passphrase,
|
||||
);
|
||||
|
||||
// Step 4: Verified! Persist updated credentialId in server JSON
|
||||
const updatedServer = { ...server, credentialId: newCredId };
|
||||
this.configManager.saveConfigText(
|
||||
`servers/${server.id}.json`,
|
||||
JSON.stringify(updatedServer, null, 2),
|
||||
'ui',
|
||||
`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);
|
||||
const removeLines = new Set(
|
||||
afterInspect.entries
|
||||
.filter((e) => e.fingerprint === oldFingerprint)
|
||||
.map((e) => e.lineNumber),
|
||||
);
|
||||
if (removeLines.size > 0) {
|
||||
const kept = afterInspect.raw
|
||||
.split(/\r?\n/)
|
||||
.filter((_l, idx) => !removeLines.has(idx + 1));
|
||||
await this.writeAuthorizedKeysAtomic(
|
||||
server.id,
|
||||
normalizeAuthorizedKeysContent(kept),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
this.auditService.log({
|
||||
action: 'ssh.key_rotate',
|
||||
actorIp,
|
||||
sessionIdHash,
|
||||
target: server.id,
|
||||
status: 'ok',
|
||||
details: {
|
||||
oldCredentialId: server.credentialId,
|
||||
newCredentialId: newCredId,
|
||||
fingerprint: newMeta.fingerprint,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
serverId: server.id,
|
||||
ok: true,
|
||||
oldCredentialId: server.credentialId,
|
||||
newCredentialId: newCredId,
|
||||
fingerprint: newMeta.fingerprint,
|
||||
};
|
||||
} catch (err) {
|
||||
const errorMsg = err instanceof Error ? err.message : String(err);
|
||||
|
||||
// Automatic zero-lockout rollback over existing connection
|
||||
let rolledBack = false;
|
||||
if (appended) {
|
||||
try {
|
||||
await this.writeAuthorizedKeysAtomic(serverId, originalRaw);
|
||||
rolledBack = true;
|
||||
} catch {
|
||||
rolledBack = false;
|
||||
}
|
||||
}
|
||||
this.vaultService.deleteCredential(newCredId);
|
||||
|
||||
this.auditService.log({
|
||||
action: 'ssh.key_rotate',
|
||||
actorIp,
|
||||
sessionIdHash,
|
||||
target: server.id,
|
||||
status: 'error',
|
||||
details: { rolledBack, error: errorMsg },
|
||||
});
|
||||
|
||||
return {
|
||||
serverId: server.id,
|
||||
ok: false,
|
||||
rolledBack,
|
||||
oldCredentialId: server.credentialId,
|
||||
error: errorMsg,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async writeAuthorizedKeysAtomic(serverId: string, content: string): Promise<void> {
|
||||
const cmd =
|
||||
'umask 077 && mkdir -p ~/.ssh && chmod 700 ~/.ssh && ' +
|
||||
'cat > ~/.ssh/authorized_keys.gcoord.tmp.$$ && ' +
|
||||
'chmod 600 ~/.ssh/authorized_keys.gcoord.tmp.$$ && ' +
|
||||
'mv ~/.ssh/authorized_keys.gcoord.tmp.$$ ~/.ssh/authorized_keys';
|
||||
|
||||
const res = await this.sshPool.exec(serverId, cmd, { stdin: content });
|
||||
if (res.exitCode !== 0) {
|
||||
throw new Error(
|
||||
`Failed to update ~/.ssh/authorized_keys on "${serverId}": ${res.stderr.trim()}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue