Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Improve SSH connection by adding sshHostKeys on PKI Sync host settings
Carlos Monastyrski2ef2f4479c28
diff --git a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts b/backend/src/services/app-connection/ssh/ssh-connection-fns.tsindex 5bd5cd1de2..84986a22b5 100644--- a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts+++ b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts@@ -13,6 +13,12 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enumsimport { SshConnectionMethod } from "./ssh-connection-enums";import { TSshConnectionConfig } from "./ssh-connection-types";+import {+ describeKeyType,+ negotiableAlgorithmsForKnownHosts,+ presentedKeyMatchesKnownHosts,+ SSH_SERVER_HOST_KEY_ALGORITHMS+} from "./ssh-host-key-fns";const SSH_TIMEOUT = 50_000;const SSH_RETRY_DELAY = 5_000;@@ -24,6 +30,7 @@ const delay = (ms: number): Promise<void> =>});export type TSshConnectionOptions = {+ expectedHostKeys?: string;maxRetries?: number;retryDelay?: number;};@@ -39,23 +46,49 @@ export const getSshConnectionListItem = () => {const attemptSshConnection = (credentials: TSshConnectionConfig,targetHost: string,- targetPort: number+ targetPort: number,+ expectedHostKeys?: string): Promise<Client> => {return new Promise((resolve, reject) => {const client = new Client();+ let hostKeyRejected = false;+ let presentedKeyType: string | undefined;+const connectConfig: ConnectConfig = {host: targetHost,port: targetPort,readyTimeout: SSH_TIMEOUT,tryKeyboard: false,+ ...(expectedHostKeys+ ? {+ hostVerifier: (hostKey: Buffer) => {+ const matches = presentedKeyMatchesKnownHosts(hostKey, expectedHostKeys);+ if (!matches) {+ hostKeyRejected = true;+ presentedKeyType = describeKeyType(hostKey);+ }+ return matches;+ }+ }+ : {}),algorithms: {- serverHostKey: ["rsa-sha2-512", "rsa-sha2-256", "ssh-rsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp521"]+ serverHostKey: expectedHostKeys+ ? negotiableAlgorithmsForKnownHosts(expectedHostKeys)+ : [...SSH_SERVER_HOST_KEY_ALGORITHMS]}};client.on("error", (err: Error) => {client.destroy();+ if (hostKeyRejected) {+ reject(+ new Error(+ `SSH Error: the ${presentedKeyType} host key presented by ${credentials.credentials.host} is not one of this sync's trusted host keys, so no credential was sent. Either the host was rebuilt and its keys need re-reading, or this is not the host you expect.`+ )+ );+ return;+ }if (err instanceof Error) {if (err.message.includes("authentication") ||@@ -132,7 +165,7 @@ export const getSshConnectionClient = async (try {logger.info(`[host=${targetHost}] [port=${targetPort}] SSH connection attempt ${attempt}/${maxRetries}`);// eslint-disable-next-line no-await-in-loop- const client = await attemptSshConnection(credentials, targetHost, targetPort);+ const client = await attemptSshConnection(credentials, targetHost, targetPort, options?.expectedHostKeys);if (attempt > 1) {logger.info(`[host=${targetHost}] [port=${targetPort}] SSH connection succeeded on attempt ${attempt}`);}@@ -219,13 +252,14 @@ export const withSshConnection = async <T>(gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;},- operation: (client: Client) => Promise<T>+ operation: (client: Client) => Promise<T>,+ options?: TSshConnectionOptions): Promise<T> =>executeWithPotentialGateway(config,gatewayServices.gatewayV2Service,async (targetHost, targetPort) => {- const client = await getSshConnectionClient(config, targetHost, targetPort);+ const client = await getSshConnectionClient(config, targetHost, targetPort, options);try {return await operation(client);} finally {diff --git a/backend/src/services/app-connection/ssh/ssh-host-key-fns.test.ts b/backend/src/services/app-connection/ssh/ssh-host-key-fns.test.tsnew file mode 100644index 0000000000..0a212d8406--- /dev/null+++ b/backend/src/services/app-connection/ssh/ssh-host-key-fns.test.ts@@ -0,0 +1,114 @@+import { describe, expect, it } from "vitest";++import {+ assertKnownHostKeysAreNegotiable,+ describeKeyType,+ isKnownHostKeysValid,+ negotiableAlgorithmsForKnownHosts,+ parseKnownHostKeys,+ presentedKeyMatchesKnownHosts+} from "./ssh-host-key-fns";++const RSA = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDLpnBHDX8Xz4V3xkGvHY6L9nCwHZ0Vp7iEYq2ThTgKlm5R";+const ECDSA = "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFzQ1n4pQfR9dLpXvJ7cKmQ";+const ED25519 = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGx3vQnPqZ4hR8yLmWkKdT5oUvBcXeJfAaQiNrMsHtEw";++describe("parseKnownHostKeys", () => {+ it("reads a bare 'type base64' line", () => {+ const [key] = parseKnownHostKeys(RSA);+ expect(key.keyType).toBe("ssh-rsa");+ expect(key.key.length).toBeGreaterThan(0);+ });++ it("ignores the host column that ssh-keyscan prefixes", () => {+ expect(parseKnownHostKeys(`172.31.34.53 ${RSA}`)[0].keyType).toBe("ssh-rsa");+ });++ it("reads every key from a multi-line paste, which is what ssh-keyscan prints", () => {+ const keys = parseKnownHostKeys([RSA, ECDSA, ED25519].map((k) => `host ${k}`).join("\n"));+ expect(keys.map((k) => k.keyType)).toEqual(["ssh-rsa", "ecdsa-sha2-nistp256", "ssh-ed25519"]);+ });++ it("skips comments and blank lines", () => {+ expect(parseKnownHostKeys(`# comment\n\n${RSA}\n\n`)).toHaveLength(1);+ });++ it.each([+ ["empty", ""],+ ["only a comment", "# nothing here"],+ ["a fingerprint rather than a key", "SHA256:47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU"],+ ["a key type with no key", "ssh-rsa"],+ ["non-base64 key material", "ssh-rsa not!valid!base64!"]+ ])("rejects %s", (_label, input) => {+ expect(() => parseKnownHostKeys(input)).toThrow();+ });++ it("names ssh-keyscan in the rejection so the user knows where to get the value", () => {+ expect(() => parseKnownHostKeys("garbage")).toThrow(/ssh-keyscan/);+ });+});++describe("assertKnownHostKeysAreNegotiable", () => {+ it("accepts a paste containing a key this client negotiates", () => {+ expect(() => assertKnownHostKeysAreNegotiable(parseKnownHostKeys(`${ED25519}\n${RSA}`))).not.toThrow();+ });++ // the failure the fingerprint format could not catch until the first connection attempt+ it("rejects a paste of only key types this client never negotiates, at save time", () => {+ expect(() => assertKnownHostKeysAreNegotiable(parseKnownHostKeys(ED25519))).toThrow(/ssh-ed25519/);+ expect(isKnownHostKeysValid(ED25519)).toBe(false);+ });++ it("explains which types are negotiated", () => {+ expect(() => assertKnownHostKeysAreNegotiable(parseKnownHostKeys(ED25519))).toThrow(/ssh-rsa/);+ });+});++describe("presentedKeyMatchesKnownHosts", () => {+ const rsaKey = parseKnownHostKeys(RSA)[0].key;+ const ecdsaKey = parseKnownHostKeys(ECDSA)[0].key;++ it("matches when the presented key is in the trusted set", () => {+ expect(presentedKeyMatchesKnownHosts(rsaKey, `${ED25519}\n${RSA}\n${ECDSA}`)).toBe(true);+ });++ it("matches whichever algorithm gets negotiated, so no picking is required", () => {+ const both = `${RSA}\n${ECDSA}`;+ expect(presentedKeyMatchesKnownHosts(rsaKey, both)).toBe(true);+ expect(presentedKeyMatchesKnownHosts(ecdsaKey, both)).toBe(true);+ });++ it("rejects a key that is not in the set", () => {+ expect(presentedKeyMatchesKnownHosts(ecdsaKey, RSA)).toBe(false);+ });++ it("rejects a truncated key rather than matching on a prefix", () => {+ expect(presentedKeyMatchesKnownHosts(rsaKey.subarray(0, rsaKey.length - 4), RSA)).toBe(false);+ });+});++describe("describeKeyType", () => {+ it("reads the algorithm name out of the wire format", () => {+ expect(describeKeyType(parseKnownHostKeys(RSA)[0].key)).toBe("ssh-rsa");+ expect(describeKeyType(parseKnownHostKeys(ED25519)[0].key)).toBe("ssh-ed25519");+ });+});++describe("negotiableAlgorithmsForKnownHosts", () => {+ it("offers only RSA when only an RSA key is trusted", () => {+ expect(negotiableAlgorithmsForKnownHosts(RSA)).toEqual(["rsa-sha2-512", "rsa-sha2-256", "ssh-rsa"]);+ });++ it("offers only ECDSA when only an ECDSA key is trusted", () => {+ expect(negotiableAlgorithmsForKnownHosts(ECDSA)).toEqual(["ecdsa-sha2-nistp256"]);+ });++ it("offers both when both are trusted", () => {+ expect(negotiableAlgorithmsForKnownHosts(`${RSA}\n${ECDSA}`)).toContain("rsa-sha2-512");+ expect(negotiableAlgorithmsForKnownHosts(`${RSA}\n${ECDSA}`)).toContain("ecdsa-sha2-nistp256");+ });++ it("ignores trusted keys of types that are never negotiated", () => {+ expect(negotiableAlgorithmsForKnownHosts(`${ED25519}\n${RSA}`)).not.toContain("ssh-ed25519");+ });+});diff --git a/backend/src/services/app-connection/ssh/ssh-host-key-fns.ts b/backend/src/services/app-connection/ssh/ssh-host-key-fns.tsnew file mode 100644index 0000000000..317cdc67da--- /dev/null+++ b/backend/src/services/app-connection/ssh/ssh-host-key-fns.ts@@ -0,0 +1,93 @@+import RE2 from "re2";++import { BadRequestError } from "@app/lib/errors";++export const SSH_SERVER_HOST_KEY_ALGORITHMS = [+ "rsa-sha2-512",+ "rsa-sha2-256",+ "ssh-rsa",+ "ecdsa-sha2-nistp256",+ "ecdsa-sha2-nistp521"+] as const;++export type TSshServerHostKeyAlgorithm = (typeof SSH_SERVER_HOST_KEY_ALGORITHMS)[number];++const NEGOTIABLE_KEY_TYPES = new Set(["ssh-rsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp521"]);++const WHITESPACE = new RE2("\\s+");+const BASE64 = new RE2("^[A-Za-z0-9+/]+={0,2}$");++export type TKnownHostKey = { keyType: string; key: Buffer };++export const KNOWN_HOST_KEY_EXAMPLE = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...";++export const parseKnownHostKeys = (value: string): TKnownHostKey[] => {+ const keys: TKnownHostKey[] = [];++ value+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0 && !line.startsWith("#"))+ .forEach((line) => {+ const parts = line.split(WHITESPACE).filter((part) => part.length > 0);+ const typeIndex = parts.findIndex((part) => part.startsWith("ssh-") || part.startsWith("ecdsa-"));++ if (typeIndex === -1 || !parts[typeIndex + 1]) {+ throw new BadRequestError({+ message: `'${line.slice(0, 60)}' is not an SSH host key. Paste the output of 'ssh-keyscan <host>', for example '${KNOWN_HOST_KEY_EXAMPLE}'.`+ });+ }++ const keyType = parts[typeIndex];+ const encoded = parts[typeIndex + 1];++ if (!BASE64.test(encoded)) {+ throw new BadRequestError({+ message: `The ${keyType} host key is not valid base64. Paste the output of 'ssh-keyscan <host>' without editing it.`+ });+ }++ keys.push({ keyType, key: Buffer.from(encoded, "base64") });+ });++ if (!keys.length) {+ throw new BadRequestError({+ message: `No SSH host key found. Paste the output of 'ssh-keyscan <host>', for example '${KNOWN_HOST_KEY_EXAMPLE}'.`+ });+ }++ return keys;+};++export const assertKnownHostKeysAreNegotiable = (keys: TKnownHostKey[]) => {+ if (keys.some(({ keyType }) => NEGOTIABLE_KEY_TYPES.has(keyType))) return;++ const listed = [...new Set(keys.map(({ keyType }) => keyType))].join(", ");+ throw new BadRequestError({+ message: `The host keys provided are ${listed}, and this sync negotiates ${[...NEGOTIABLE_KEY_TYPES].join(", ")}. Paste the full output of 'ssh-keyscan <host>' so a key this sync can negotiate is included.`+ });+};++export const isKnownHostKeysValid = (value: string): boolean => {+ try {+ assertKnownHostKeysAreNegotiable(parseKnownHostKeys(value));+ return true;+ } catch {+ return false;+ }+};++export const presentedKeyMatchesKnownHosts = (presented: Buffer, expected: string): boolean =>+ parseKnownHostKeys(expected).some(({ key }) => key.equals(presented));++export const negotiableAlgorithmsForKnownHosts = (expected: string): TSshServerHostKeyAlgorithm[] => {+ const trusted = new Set(parseKnownHostKeys(expected).map(({ keyType }) => keyType));+ return SSH_SERVER_HOST_KEY_ALGORITHMS.filter((algorithm) =>+ algorithm.startsWith("rsa-sha2-") || algorithm === "ssh-rsa" ? trusted.has("ssh-rsa") : trusted.has(algorithm)+ );+};++export const describeKeyType = (presented: Buffer): string => {+ const nameLength = presented.readUInt32BE(0);+ return nameLength > 0 && nameLength < 64 ? presented.subarray(4, 4 + nameLength).toString("ascii") : "unknown";+};diff --git a/backend/src/services/app-connection/ssh/ssh-host-key-verification.test.ts b/backend/src/services/app-connection/ssh/ssh-host-key-verification.test.tsnew file mode 100644index 0000000000..5ef5044f48--- /dev/null+++ b/backend/src/services/app-connection/ssh/ssh-host-key-verification.test.ts@@ -0,0 +1,122 @@+import crypto from "node:crypto";++import { Client, Server } from "ssh2";+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";++import { AppConnection } from "../app-connection-enums";+import { SshConnectionMethod } from "./ssh-connection-enums";+import { getSshConnectionClient } from "./ssh-connection-fns";+import { TSshConnectionConfig } from "./ssh-connection-types";+import { describeKeyType } from "./ssh-host-key-fns";++vi.mock("@app/lib/logger", () => ({+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }+}));++vi.mock("@app/lib/validator", () => ({+ blockLocalAndPrivateIpAddresses: vi.fn()+}));++describe("ssh host key verification", () => {+ const { privateKey } = crypto.generateKeyPairSync("rsa", {+ modulusLength: 2048,+ privateKeyEncoding: { type: "pkcs1", format: "pem" },+ publicKeyEncoding: { type: "pkcs1", format: "pem" }+ });++ let server: Server;+ let port: number;+ let authAttempts: { method: string; password?: string }[] = [];+ let serverHostKeyLine: string;++ const config = {+ app: AppConnection.SSH,+ method: SshConnectionMethod.Password,+ credentials: { host: "127.0.0.1", port: 0, username: "svc-certs", password: "s3cret-bind-password" },+ orgId: "org"+ } as unknown as TSshConnectionConfig;++ const connect = (expectedHostKeys?: string) =>+ getSshConnectionClient(config, "127.0.0.1", port, { maxRetries: 1, expectedHostKeys });++ beforeAll(async () => {+ server = new Server({ hostKeys: [privateKey] }, (client) => {+ client.on("authentication", (ctx) => {+ authAttempts.push({+ method: ctx.method,+ password: (ctx as unknown as { password?: string }).password+ });+ ctx.accept();+ });+ client.on("ready", () => client.end());+ client.on("error", () => {});+ });++ await new Promise<void>((resolve) => {+ server.listen(0, "127.0.0.1", () => {+ port = (server.address() as { port: number }).port;+ resolve();+ });+ });++ serverHostKeyLine = await new Promise<string>((resolve, reject) => {+ const sniffer = new Client();+ sniffer.on("error", reject);+ sniffer.on("ready", () => sniffer.destroy());+ sniffer.connect({+ host: "127.0.0.1",+ port,+ username: "sniff",+ password: "sniff",+ hostVerifier: (key: Buffer) => {+ resolve(`${describeKeyType(key)} ${key.toString("base64")}`);+ return true;+ }+ });+ });+ }, 30_000);++ afterAll(() => server?.close());++ it("reaches authentication when nothing is pinned, the previous behaviour", async () => {+ authAttempts = [];+ (await connect()).destroy();+ expect(authAttempts.length).toBeGreaterThan(0);+ }, 30_000);++ it("authenticates when the server presents a trusted key", async () => {+ authAttempts = [];+ (await connect(serverHostKeyLine)).destroy();+ expect(authAttempts.length).toBeGreaterThan(0);+ }, 30_000);++ it("never sends the password when the pinned fingerprint does not match", async () => {+ authAttempts = [];+ const wrong = `ssh-rsa ${crypto.randomBytes(279).toString("base64")}`;++ await expect(connect(wrong)).rejects.toThrow(/is not one of this sync's trusted host keys/);++ expect(authAttempts).toEqual([]);+ expect(JSON.stringify(authAttempts)).not.toContain("s3cret-bind-password");+ }, 30_000);++ it("names the algorithm the host presented", async () => {+ const wrong = `ssh-rsa ${crypto.randomBytes(279).toString("base64")}`;+ await expect(connect(wrong)).rejects.toThrow(/ssh-rsa host key presented by/);+ }, 30_000);++ it("accepts a full ssh-keyscan style paste with the host column and several keys", async () => {+ authAttempts = [];+ const paste = [+ "127.0.0.1 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGx3vQnPqZ4hR8yLmWkKdT5oUvBcXeJfAaQiNrMsHtEw",+ `127.0.0.1 ${serverHostKeyLine}`+ ].join("\n");+ (await connect(paste)).destroy();+ expect(authAttempts.length).toBeGreaterThan(0);+ }, 30_000);++ it("reports a mismatch as a host key problem, not as bad credentials", async () => {+ const wrong = `ssh-rsa ${crypto.randomBytes(279).toString("base64")}`;+ await expect(connect(wrong)).rejects.not.toThrow(/credentials invalid/);+ }, 30_000);+});diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.tsindex 863420bfe0..7acf65ee5f 100644--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts@@ -109,6 +109,10 @@ const buildLdapBackedSshConfig = async (} as TSshConnectionConfig;};+const sshPinOptions = (pkiSync: { destinationConfig: unknown }) => ({+ expectedHostKeys: (pkiSync.destinationConfig as TLinuxServerPkiSyncConfig).sshHostKeys || undefined+});+const buildSshConfig = async (pkiSync: THealthCheckTarget,gatewayServices: TGatewayServices@@ -421,104 +425,114 @@ export const linuxServerPkiSyncFactory = ({return buildHealthCheckFailureSyncResult(certificateMap, healthCheck);}- await withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async (client) => {- const sftp = await openSftp(client);- await removeStaleTempFiles(sftp, config.destinationPath);+ await withSshConnection(+ sshConfig,+ { gatewayV2Service, gatewayPoolService },+ async (client) => {+ const sftp = await openSftp(client);+ await removeStaleTempFiles(sftp, config.destinationPath);- for (const [baseName, certData] of Object.entries(certificateMap)) {- const { cert, privateKey, certificateChain, certificateId } = certData;+ for (const [baseName, certData] of Object.entries(certificateMap)) {+ const { cert, privateKey, certificateChain, certificateId } = certData;- if (!cert) {- skippedCertificates.push({ name: baseName, reason: "Missing certificate data" });- // eslint-disable-next-line no-continue- continue;- }+ if (!cert) {+ skippedCertificates.push({ name: baseName, reason: "Missing certificate data" });+ // eslint-disable-next-line no-continue+ continue;+ }- // Private key is required for PKCS#12, and for PEM when the operator asked to include it.- // If the key is not available (external CSR or HSM key), fail rather than deliver a keyless file.- const keyRequired = format === PkiSyncExportFormat.Pkcs12 || includePrivateKey;- if (keyRequired && !privateKey) {- failedUploads.push({- name: baseName,- error:- "Private key is required but is not available for this certificate (for example, it was issued from an external CSR)"- });- // eslint-disable-next-line no-continue- continue;- }+ // Private key is required for PKCS#12, and for PEM when the operator asked to include it.+ // If the key is not available (external CSR or HSM key), fail rather than deliver a keyless file.+ const keyRequired = format === PkiSyncExportFormat.Pkcs12 || includePrivateKey;+ if (keyRequired && !privateKey) {+ failedUploads.push({+ name: baseName,+ error:+ "Private key is required but is not available for this certificate (for example, it was issued from an external CSR)"+ });+ // eslint-disable-next-line no-continue+ continue;+ }- try {- const files = await exportCertificateForSync({- ...exportOptions,- certificate: cert,- certificateChain,- privateKey,- password: exportPassword,- alias: baseName- });+ try {+ const files = await exportCertificateForSync({+ ...exportOptions,+ certificate: cert,+ certificateChain,+ privateKey,+ password: exportPassword,+ alias: baseName+ });++ const writtenPaths: string[] = [];+ for (const file of files) {+ const filePath = path.posix.join(config.destinationPath, `${baseName}${file.suffix}`);+ try {+ await writeFileAtomic(+ sftp,+ filePath,+ file.content,+ file.isPrivateKey ? privateKeyMode : certificateMode+ );+ } catch (writeErr) {+ const msg = (writeErr as Error)?.message ?? "";+ if (NO_SUCH_FILE_ERROR.test(msg)) {+ throw new PkiSyncError({+ message: `Destination directory "${config.destinationPath}" does not exist or is not writable`+ });+ }+ throw writeErr;+ }+ await applyOwnership(client, options.owner, options.group, filePath);+ writtenPaths.push(filePath);+ deliveredPaths.add(filePath);+ }- const writtenPaths: string[] = [];- for (const file of files) {- const filePath = path.posix.join(config.destinationPath, `${baseName}${file.suffix}`);- try {- await writeFileAtomic(sftp, filePath, file.content, file.isPrivateKey ? privateKeyMode : certificateMode);- } catch (writeErr) {- const msg = (writeErr as Error)?.message ?? "";- if (NO_SUCH_FILE_ERROR.test(msg)) {- throw new PkiSyncError({- message: `Destination directory "${config.destinationPath}" does not exist or is not writable`+ const primaryPath = writtenPaths[0];+ deliveredCertificates.push({ paths: writtenPaths, commonName: certData.commonName ?? undefined });+ if (typeof certificateId === "string") {+ let record = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);+ if (!record) {+ [record] = await certificateSyncDAL.addCertificates(pkiSync.id, [+ { certificateId, externalIdentifier: primaryPath }+ ]);+ }+ if (record) {+ await certificateSyncDAL.updateById(record.id, {+ externalIdentifier: primaryPath,+ syncMetadata: { files: writtenPaths }});}- throw writeErr;}- await applyOwnership(client, options.owner, options.group, filePath);- writtenPaths.push(filePath);- deliveredPaths.add(filePath);- }- const primaryPath = writtenPaths[0];- deliveredCertificates.push({ paths: writtenPaths, commonName: certData.commonName ?? undefined });- if (typeof certificateId === "string") {- let record = await certificateSyncDAL.findByPkiSyncAndCertificate(pkiSync.id, certificateId);- if (!record) {- [record] = await certificateSyncDAL.addCertificates(pkiSync.id, [- { certificateId, externalIdentifier: primaryPath }- ]);- }- if (record) {- await certificateSyncDAL.updateById(record.id, {- externalIdentifier: primaryPath,- syncMetadata: { files: writtenPaths }- });- }+ uploaded += 1;+ logger.info(+ `Linux Server PKI sync [syncId=${pkiSync.id}]: wrote ${writtenPaths.length} file(s) for "${baseName}"`+ );+ } catch (err) {+ failedUploads.push({ name: baseName, error: describeFailure(err) });}+ }- uploaded += 1;+ // Delete files for certificates no longer active and drop their tracking rows.+ if (canRemoveCertificates && failedUploads.length === 0) {+ const reconciliation = await reconcileLinuxServerRemovals({+ sftp,+ pkiSync,+ certificateMap,+ deliveredPaths,+ certificateSyncDAL+ });+ removed += reconciliation.removed;+ failedRemovals.push(...reconciliation.failedRemovals);+ } else if (canRemoveCertificates) {logger.info(- `Linux Server PKI sync [syncId=${pkiSync.id}]: wrote ${writtenPaths.length} file(s) for "${baseName}"`+ `Linux Server PKI sync [syncId=${pkiSync.id}]: skipped certificate removal because ${failedUploads.length} certificate(s) failed to deliver`);- } catch (err) {- failedUploads.push({ name: baseName, error: describeFailure(err) });}- }-- // Delete files for certificates no longer active and drop their tracking rows.- if (canRemoveCertificates && failedUploads.length === 0) {- const reconciliation = await reconcileLinuxServerRemovals({- sftp,- pkiSync,- certificateMap,- deliveredPaths,- certificateSyncDAL- });- removed += reconciliation.removed;- failedRemovals.push(...reconciliation.failedRemovals);- } else if (canRemoveCertificates) {- logger.info(- `Linux Server PKI sync [syncId=${pkiSync.id}]: skipped certificate removal because ${failedUploads.length} certificate(s) failed to deliver`- );- }- });+ },+ sshPinOptions(pkiSync)+ );const postSyncCommandPlan = buildPostSyncCommandPlan({command: options.postSyncCommand,@@ -583,13 +597,18 @@ export const linuxServerPkiSyncFactory = ({if (pathsToRemove.size > 0) {const sshConfig = await buildSshConfig(pkiSync, { gatewayV2Service, gatewayPoolService, keyStore });- await withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async (client) => {- const sftp = await openSftp(client);- for (const filePath of pathsToRemove) {- await unlinkIfExists(sftp, filePath);- logger.info(`Linux Server PKI sync [syncId=${pkiSync.id}]: removed "${filePath}"`);- }- });+ await withSshConnection(+ sshConfig,+ { gatewayV2Service, gatewayPoolService },+ async (client) => {+ const sftp = await openSftp(client);+ for (const filePath of pathsToRemove) {+ await unlinkIfExists(sftp, filePath);+ logger.info(`Linux Server PKI sync [syncId=${pkiSync.id}]: removed "${filePath}"`);+ }+ },+ sshPinOptions(pkiSync)+ );}// Untrack the removed certificates so they are no longer reported as synced and not re-delivered.@@ -612,7 +631,12 @@ export const linuxServerPkiSyncFactory = ({try {await withReachabilityDeadline(() =>- withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async () => undefined)+ withSshConnection(+ sshConfig,+ { gatewayV2Service, gatewayPoolService },+ async () => undefined,+ sshPinOptions(pkiSync)+ ));} catch (err) {const gatewayLabel = await resolveGatewayLabel(gatewayV2Service, sshConfig.gatewayId);diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.tsindex fc9ce8bfae..57f8172c36 100644--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts@@ -2,6 +2,10 @@ import RE2 from "re2";import { z } from "zod";import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import {+ assertKnownHostKeysAreNegotiable,+ parseKnownHostKeys+} from "@app/services/app-connection/ssh/ssh-host-key-fns";import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";@@ -31,7 +35,23 @@ export const LinuxServerPkiSyncConfigSchema = z.object({.refine((p) => p.startsWith("/"), { message: "Destination path must be absolute (start with /)" }).refine((p) => !PATH_TRAVERSAL.test(p), { message: "Destination path must not contain '..'" }),host: PkiSyncTargetHostSchema,- port: PkiSyncTargetPortSchema+ port: PkiSyncTargetPortSchema,+ sshHostKeys: z+ .string()+ .trim()+ .max(8192)+ .optional()+ .superRefine((value, ctx) => {+ if (!value) return;+ try {+ assertKnownHostKeysAreNegotiable(parseKnownHostKeys(value));+ } catch (err) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: (err as Error).message });+ }+ })+ .describe(+ "Trusted SSH host keys for the target, as produced by 'ssh-keyscan <host>'. When set, the sync refuses to authenticate if the host presents a different key."+ )});export const LinuxServerPkiSyncOptionsSchema = z.object({diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex f5968eb1ca..f57c47b634 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -240,7 +240,8 @@ export const pkiSyncServiceFactory = ({config?.port,config?.sslEnabled,config?.sslRejectUnauthorized,- config?.sslCertificate+ config?.sslCertificate,+ config?.sshHostKeys]);};diff --git a/backend/src/services/pki-sync/pki-sync-target-host-fns.ts b/backend/src/services/pki-sync/pki-sync-target-host-fns.tsindex 180de68a48..51e15d09f1 100644--- a/backend/src/services/pki-sync/pki-sync-target-host-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-target-host-fns.ts@@ -19,6 +19,7 @@ export type TPkiSyncDeliveryTarget = {sslEnabled?: boolean;sslRejectUnauthorized?: boolean;sslCertificate?: string;+ sshHostKeys?: string;};const LDAP_ONLY_TARGET_FIELDS = [@@ -26,7 +27,8 @@ const LDAP_ONLY_TARGET_FIELDS = ["port","sslEnabled","sslRejectUnauthorized",- "sslCertificate"+ "sslCertificate",+ "sshHostKeys"] as const satisfies readonly (keyof TPkiSyncDeliveryTarget)[];export const getPkiSyncTargetHost = (diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdxindex d80d00915b..9bc675cc83 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx@@ -37,6 +37,7 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi4. Configure the **Target Host**. This step appears only when the connection is an LDAP Connection, because that connection reaches a whole domain rather than one machine:- **Target Host**: The machine this sync delivers to. Servers found in the directory are offered as suggestions, and you can enter a host that is not listed. Enter a host name or an IPv4 address. Underscores, ports and IPv6 literals are not accepted.- **Port**: Leave empty to use 22. Set a value only if the SSH listener is on a non-standard port.+ - **Trusted Host Keys**: Optional. Paste the output of `ssh-keyscan <host>`. When set, the sync only connects if the host presents one of these keys.5. Configure the **Sync Options**:- **Export Format**: Choose **PEM** to write separate certificate, chain, and key files, or **PKCS#12** to write a single password-protected `.pfx` bundle.diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncTargetHostField.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncTargetHostField.tsxindex dcee519df7..453aa14f8e 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncTargetHostField.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncTargetHostField.tsx@@ -218,6 +218,34 @@ export const PkiSyncTargetHostField = ({ applicationId }: Props) => {)}</>)}+ {destination === PkiSync.LinuxServer && (+ <Controller+ name="destinationConfig.sshHostKeys"+ control={control}+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field className="mb-4">+ <FieldLabel>+ Trusted Host Keys <span className="text-muted">(optional)</span>+ </FieldLabel>+ <TextArea+ value={(value as string) ?? ""}+ onChange={(event) => onChange(event.target.value || undefined)}+ placeholder={"ssh-rsa AAAAB3NzaC1yc2E...\necdsa-sha2-nistp256 AAAAE2VjZHNh..."}+ disabled={!canSetTargetHost}+ isError={Boolean(error)}+ className="min-h-24 font-mono text-xs"+ />+ <FieldError errors={[error]} />+ {!error && (+ <FieldDescription>+ If set, the sync only connects when the host presents one of these keys. Paste the+ output of <code>ssh-keyscan <host></code>.+ </FieldDescription>+ )}+ </Field>+ )}+ />+ )}</>);};diff --git a/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.tsindex b10900232a..01941aa79d 100644--- a/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts+++ b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts@@ -10,6 +10,8 @@ import {PkiSyncTargetPortSchema} from "./base-pki-sync-schema";+const HOST_KEY_LINE = /(^|\s)(ssh-|ecdsa-)\S+\s+[A-Za-z0-9+/]+={0,2}/;+const compileNameSchema = (val: string) =>val.replace(/\{\{shortCertificateId\}\}/g, "0".repeat(22))@@ -96,7 +98,16 @@ export const LinuxServerPkiSyncDestinationSchema = BasePkiSyncSchema(destinationConfig: z.object({destinationPath: DestinationPathSchema,host: PkiSyncTargetHostSchema,- port: PkiSyncTargetPortSchema+ port: PkiSyncTargetPortSchema,+ sshHostKeys: z+ .string()+ .trim()+ .max(8192)+ .optional()+ .refine((value) => !value || HOST_KEY_LINE.test(value), {+ message:+ "Paste the output of 'ssh-keyscan <host>', for example: ssh-rsa AAAAB3NzaC1yc2E..."+ })}),credentials: z.object({