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
import { Client, ConnectConfig } from "ssh2";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { BadRequestError, InternalServerError } from "@app/lib/errors";
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
import { callSshExec, SshExecAuthMethod, SshExecCredentials, SshExecResult } from "@app/lib/gateway-v2/ssh-rpc";
import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
import { logger } from "@app/lib/logger";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { 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;
const SSH_MAX_RETRIES = 2;
const delay = (ms: number): Promise<void> =>
new Promise((resolve) => {
setTimeout(resolve, ms);
});
export type TSshConnectionOptions = {
expectedHostKeys?: string;
maxRetries?: number;
retryDelay?: number;
};
export const getSshConnectionListItem = () => {
return {
name: "SSH" as const,
app: AppConnection.SSH as const,
methods: Object.values(SshConnectionMethod) as [SshConnectionMethod.Password, SshConnectionMethod.SshKey]
};
};
const attemptSshConnection = (
credentials: TSshConnectionConfig,
targetHost: string,
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: 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") ||
err.message.includes("All configured authentication methods failed") ||
err.message.includes("publickey")
) {
reject(new Error("SSH Error: Account credentials invalid."));
return;
}
if (err.message === "Connection timeout") {
reject(new Error("SSH Error: Connection timeout. Verify that the SSH server is reachable"));
return;
}
}
reject(new Error(`SSH Error: ${err.message}`));
});
client.on("ready", () => {
resolve(client);
});
client.on("timeout", () => {
client.destroy();
reject(new Error("SSH Connection Timeout"));
});
switch (credentials.method) {
case SshConnectionMethod.Password: {
const { credentials: inputCredentials } = credentials;
connectConfig.username = inputCredentials.username;
connectConfig.password = inputCredentials.password;
break;
}
case SshConnectionMethod.SshKey: {
const { credentials: inputCredentials } = credentials;
connectConfig.username = inputCredentials.username;
connectConfig.privateKey = inputCredentials.privateKey;
if (inputCredentials.passphrase) {
connectConfig.passphrase = inputCredentials.passphrase;
}
break;
}
default: {
throw new InternalServerError({
message: `Unhandled connection method: ${(credentials as { method: string }).method}`
});
}
}
client.connect(connectConfig);
});
};
const isRetryableError = (errorMessage: string): boolean => {
const lowerMessage = errorMessage.toLowerCase();
return lowerMessage.includes("timeout") || lowerMessage.includes("timed out");
};
export const getSshConnectionClient = async (
credentials: TSshConnectionConfig,
targetHost: string,
targetPort: number,
options?: TSshConnectionOptions
): Promise<Client> => {
const maxRetries = options?.maxRetries ?? SSH_MAX_RETRIES;
const retryDelay = options?.retryDelay ?? SSH_RETRY_DELAY;
let lastError: Error | null = null;
// eslint-disable-next-line no-await-in-loop -- Intentional sequential retry logic
for (let attempt = 1; attempt <= maxRetries; attempt += 1) {
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, options?.expectedHostKeys);
if (attempt > 1) {
logger.info(`[host=${targetHost}] [port=${targetPort}] SSH connection succeeded on attempt ${attempt}`);
}
return client;
} catch (error) {
lastError = error as Error;
const errorMessage = lastError.message ?? "";
logger.info(
`[host=${targetHost}] [port=${targetPort}] SSH connection attempt ${attempt} failed: ${errorMessage}`
);
if (!isRetryableError(errorMessage)) {
throw lastError;
}
if (attempt < maxRetries) {
logger.info(`[host=${targetHost}] [port=${targetPort}] Retrying SSH connection in ${retryDelay}ms`);
// eslint-disable-next-line no-await-in-loop
await delay(retryDelay);
}
}
}
throw lastError ?? new Error("SSH connection failed after all retries");
};
export const executeWithPotentialGateway = async <T>(
config: TSshConnectionConfig,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId"> | undefined,
operation: (targetHost: string, targetPort: number) => Promise<T>,
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">
): Promise<T> => {
const { gatewayId: directGatewayId, gatewayPoolId, credentials } = config;
if (gatewayPoolId && !gatewayPoolService) {
throw new InternalServerError({
message: "Pool-backed connections require gatewayPoolService at the call site"
});
}
const gatewayId =
gatewayPoolId && gatewayPoolService
? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })
: directGatewayId;
if (gatewayId) {
if (!gatewayV2Service) {
throw new InternalServerError({
message: "Gateway-backed connections require gatewayV2Service at the call site"
});
}
await blockLocalAndPrivateIpAddresses(`ssh://${credentials.host}:${credentials.port}`, true);
const platformConnectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId,
targetHost: credentials.host,
targetPort: credentials.port
});
if (!platformConnectionDetails) {
throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
}
return withGatewayV2Proxy(
async (proxyPort) => {
return operation("localhost", proxyPort);
},
{
protocol: GatewayProxyProtocol.Tcp,
...platformConnectionDetails
}
);
}
// Non-gateway path - direct connection
await blockLocalAndPrivateIpAddresses(`ssh://${credentials.host}:${credentials.port}`, false);
return operation(credentials.host, credentials.port);
};
export const withSshConnection = async <T>(
config: TSshConnectionConfig,
gatewayServices: {
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
},
operation: (client: Client) => Promise<T>,
options?: TSshConnectionOptions
): Promise<T> =>
executeWithPotentialGateway(
config,
gatewayServices.gatewayV2Service,
async (targetHost, targetPort) => {
const client = await getSshConnectionClient(config, targetHost, targetPort, options);
try {
return await operation(client);
} finally {
client.destroy();
}
},
gatewayServices.gatewayPoolService
);
type TSshGatewayServices = {
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
export const toSshExecCredentials = (config: TSshConnectionConfig): SshExecCredentials => {
switch (config.method) {
case SshConnectionMethod.Password:
return {
authMethod: SshExecAuthMethod.Password,
username: config.credentials.username,
password: config.credentials.password
};
case SshConnectionMethod.SshKey:
return {
authMethod: SshExecAuthMethod.PublicKey,
username: config.credentials.username,
privateKey: config.credentials.privateKey,
passphrase: config.credentials.passphrase
};
default:
throw new InternalServerError({
message: `Unhandled connection method: ${(config as { method: string }).method}`
});
}
};
export const executeSshCommandViaGateway = async (
config: TSshConnectionConfig,
gatewayServices: TSshGatewayServices,
args: { command: string; timeoutMs: number }
): Promise<SshExecResult> => {
const { gatewayV2Service, gatewayPoolService } = gatewayServices;
const { gatewayId: directGatewayId, gatewayPoolId, credentials } = config;
if (gatewayPoolId && !gatewayPoolService) {
throw new InternalServerError({
message: "Pool-backed connections require gatewayPoolService at the call site"
});
}
const gatewayId =
gatewayPoolId && gatewayPoolService
? await gatewayPoolService.resolveEffectiveGatewayId({ gatewayId: directGatewayId, gatewayPoolId })
: directGatewayId;
if (!gatewayId) {
throw new BadRequestError({
message: "Running a command on the host requires the SSH connection to use a gateway."
});
}
if (!gatewayV2Service) {
throw new InternalServerError({ message: "Gateway-backed commands require gatewayV2Service at the call site" });
}
await blockLocalAndPrivateIpAddresses(`ssh://${credentials.host}:${credentials.port}`, true);
const connectionDetails = await gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
gatewayId,
targetHost: credentials.host,
targetPort: credentials.port
});
if (!connectionDetails) {
throw new BadRequestError({ message: "Unable to connect to gateway, no platform connection details found" });
}
const response = await withGatewayV2Proxy(
async (proxyPort) =>
callSshExec({
port: proxyPort,
command: args.command,
credentials: toSshExecCredentials(config),
timeoutMs: args.timeoutMs
}),
{
protocol: GatewayProxyProtocol.Discovery,
...connectionDetails
}
);
if (!response.ok) {
throw new BadRequestError({ message: response.errorMessage });
}
return response.result;
};
const MAX_SSH_COMMAND_OUTPUT_BYTES = 16 * 1024 * 1024;
export const execOverSshClient = (client: Client, command: string, timeoutMs: number): Promise<SshExecResult> =>
new Promise((resolve, reject) => {
let settled = false;
let timer: NodeJS.Timeout;
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timer);
fn();
};
timer = setTimeout(
() => finish(() => reject(new Error(`Command did not finish within ${Math.round(timeoutMs / 1000)}s`))),
timeoutMs
);
client.exec(command, (err, stream) => {
if (err) {
finish(() => reject(err));
return;
}
let stdout = "";
let stderr = "";
let exitCode = 0;
const append = (current: string, chunk: Buffer) =>
current.length >= MAX_SSH_COMMAND_OUTPUT_BYTES ? current : current + chunk.toString("utf8");
stream.on("data", (chunk: Buffer) => {
stdout = append(stdout, chunk);
});
stream.stderr.on("data", (chunk: Buffer) => {
stderr = append(stderr, chunk);
});
stream.on("exit", (code: number | null) => {
exitCode = typeof code === "number" ? code : 1;
});
stream.on("close", () => finish(() => resolve({ stdout, stderr, exitCode })));
});
});
export const executeSshCommand = async (
config: TSshConnectionConfig,
gatewayServices: TSshGatewayServices,
args: { command: string; timeoutMs: number },
options?: TSshConnectionOptions
): Promise<SshExecResult> => {
if (!options?.expectedHostKeys) return executeSshCommandViaGateway(config, gatewayServices, args);
return withSshConnection(
config,
gatewayServices,
(client) => execOverSshClient(client, args.command, args.timeoutMs),
options
);
};
export const validateSshConnectionCredentials = async (
config: TSshConnectionConfig,
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">
) => {
const { credentials } = config;
logger.info(`[host=${credentials.host}] [port=${credentials.port}] SSH connection validation: Attempting connection`);
try {
await executeWithPotentialGateway(config, gatewayV2Service, async (targetHost, targetPort) => {
logger.info(`[host=${targetHost}] [port=${targetPort}] SSH connection validation: Connecting`);
const client = await getSshConnectionClient(config, targetHost, targetPort);
logger.info(`[host=${targetHost}] [port=${targetPort}] SSH connection validation: Connection successful`);
client.destroy();
});
return config.credentials;
} catch (error) {
const errorMessage = (error as Error)?.message ?? "";
logger.info(
`[host=${credentials.host}] [port=${credentials.port}] SSH connection validation failed: ${errorMessage}`
);
throw new BadRequestError({
message: `Unable to validate connection: ${errorMessage || "verify credentials"}`
});
}
};