Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

9.4 KB
Raw Blame
import { execFile } from "child_process";
import { promises as fs } from "fs";
import os from "os";
import path from "path";
import { promisify } from "util";

import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
import { ms } from "@app/lib/ms";
import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
import { CERT_CLOCK_SKEW_MS } from "@app/services/certificate-common/certificate-constants";

const execFileAsync = promisify(execFile);

const EXEC_TIMEOUT_MS = 10000; // 10 seconds

const DEFAULT_CLOCK_SKEW_SECONDS = CERT_CLOCK_SKEW_MS / 1000;

export enum SshCertKeyAlgorithm {
  RSA_2048 = "RSA_2048",
  RSA_4096 = "RSA_4096",
  ECDSA_P256 = "EC_prime256v1",
  ECDSA_P384 = "EC_secp384r1",
  ED25519 = "ED25519"
}

export const SSH_CERT_KEY_ALGORITHMS = Object.values(SshCertKeyAlgorithm) as [
  SshCertKeyAlgorithm,
  ...SshCertKeyAlgorithm[]
];

export enum SshPublicKeyType {
  RSA = "ssh-rsa",
  ED25519 = "ssh-ed25519",
  ECDSA_P256 = "ecdsa-sha2-nistp256",
  ECDSA_P384 = "ecdsa-sha2-nistp384"
}

const SUPPORTED_SSH_PUBLIC_KEY_TYPES = new Set<string>(Object.values(SshPublicKeyType));

export enum SshCertType {
  USER = "user",
  HOST = "host"
}

export type TCreateSshCertDTO = {
  caPrivateKey: string;
  clientPublicKey: string;
  keyId: string;
  principals: string[];
  requestedTtl?: string;
  certType: SshCertType;
  // Widens the validity window by this many seconds at both ends, so a verifying host whose clock
  // runs behind or ahead of ours rejects the certificate as neither not-yet-valid nor expired.
  clockSkewSeconds?: number;
  // Set when the requested TTL is the only thing enforcing an access boundary, in which case the
  // expiry has to stay at issuance + ttl. The start is still backdated, since moving that end
  // cannot extend access past the boundary.
  enforceExactExpiry?: boolean;
};

/* eslint-disable no-bitwise */
const createSshCertSerialNumber = () => {
  const randomBytes = crypto.randomBytes(8); // 8 bytes = 64 bits
  randomBytes[0] &= 0x7f; // Ensure the most significant bit is 0 (to stay within unsigned range)
  return BigInt(`0x${randomBytes.toString("hex")}`).toString(10); // Convert to decimal
};

/**
 * Return a pair of SSH CA keys based on the specified key algorithm [keyAlgorithm].
 * We use this function because the key format generated by `ssh-keygen` is unique.
 */
export const createSshKeyPair = async (keyAlgorithm: SshCertKeyAlgorithm) => {
  const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ssh-key-"));
  const privateKeyFile = path.join(tempDir, "id_key");
  const publicKeyFile = `${privateKeyFile}.pub`;

  let keyType: string;
  let keyBits: string | null;

  switch (keyAlgorithm) {
    case SshCertKeyAlgorithm.RSA_2048:
      keyType = "rsa";
      keyBits = "2048";
      break;
    case SshCertKeyAlgorithm.RSA_4096:
      keyType = "rsa";
      keyBits = "4096";
      break;
    case SshCertKeyAlgorithm.ECDSA_P256:
      keyType = "ecdsa";
      keyBits = "256";
      break;
    case SshCertKeyAlgorithm.ECDSA_P384:
      keyType = "ecdsa";
      keyBits = "384";
      break;
    case SshCertKeyAlgorithm.ED25519:
      keyType = "ed25519";
      keyBits = null;
      break;
    default:
      throw new BadRequestError({
        message: "Failed to produce SSH CA key pair generation command due to unrecognized key algorithm"
      });
  }

  try {
    const args = ["-t", keyType];
    if (keyBits !== null) {
      args.push("-b", keyBits);
    }
    args.push("-f", privateKeyFile, "-N", "", "-C", "Infisical");

    // Generate the SSH key pair
    // The "-N ''" sets an empty passphrase
    // The keys are created in the temporary directory
    await execFileAsync("ssh-keygen", args, {
      timeout: EXEC_TIMEOUT_MS
    });

    // Read the generated keys
    const publicKey = await fs.readFile(publicKeyFile, "utf8");
    const privateKey = await fs.readFile(privateKeyFile, "utf8");

    return { publicKey, privateKey };
  } finally {
    // Cleanup the temporary directory and all its contents
    await fs.rm(tempDir, { recursive: true, force: true }).catch(() => {});
  }
};

export const inferSshCertKeyAlgorithm = (publicKey: string): SshPublicKeyType => {
  const space = publicKey.indexOf(" ");
  const type = space === -1 ? publicKey : publicKey.slice(0, space);
  if (!SUPPORTED_SSH_PUBLIC_KEY_TYPES.has(type)) {
    throw new BadRequestError({
      message: `Unsupported SSH key type '${type}'. Allowed types are RSA 2048, RSA 4096, ECDSA P256, ECDSA P384, and ED25519.`
    });
  }

  return type as SshPublicKeyType;
};

/**
 * Return the SSH public key for the given SSH private key.
 */
export const getSshPublicKey = async (privateKey: string) => {
  const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ssh-key-"));
  const privateKeyFile = path.join(tempDir, "id_key");
  try {
    await fs.writeFile(privateKeyFile, privateKey, { mode: 0o600 });

    // Run ssh-keygen to extract the public key
    const { stdout } = await execFileAsync("ssh-keygen", ["-y", "-f", privateKeyFile], {
      encoding: "utf8",
      timeout: EXEC_TIMEOUT_MS
    });
    return stdout.trim();
  } finally {
    // Ensure that files and the temporary directory are cleaned up
    await fs.rm(tempDir, { recursive: true, force: true }).catch(() => {});
  }
};

/**
 * Validate the requested SSH certificate key ID to ensure
 * that it only contains alphanumeric characters with no spaces.
 */
const validateSshCertificateKeyId = (keyId: string) => {
  const regex = characterValidator([
    CharacterType.AlphaNumeric,
    CharacterType.Hyphen,
    CharacterType.Colon,
    CharacterType.Period
  ]);
  if (!regex(keyId)) {
    throw new BadRequestError({
      message:
        "Failed to validate Key ID because it can only contain alphanumeric characters and hyphens, with no spaces."
    });
  }

  if (keyId.length > 50) {
    throw new BadRequestError({
      message: "keyId can only be up to 50 characters long."
    });
  }
};

/**
 * Validate the format of the SSH public key
 */
const validateSshPublicKey = async (publicKey: string) => {
  inferSshCertKeyAlgorithm(publicKey);

  // write the key to a temp file and run `ssh-keygen -l -f`
  // check to see if OpenSSH can read/interpret the public key
  const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ssh-pubkey-"));
  const pubKeyFile = path.join(tempDir, "key.pub");

  try {
    await fs.writeFile(pubKeyFile, publicKey, { mode: 0o600 });
    await execFileAsync("ssh-keygen", ["-l", "-f", pubKeyFile], { timeout: EXEC_TIMEOUT_MS });
  } catch (error) {
    throw new BadRequestError({
      message: "Failed to validate SSH public key format: could not be parsed."
    });
  } finally {
    await fs.rm(tempDir, { recursive: true, force: true }).catch(() => {});
  }
};

/**
 * Create an SSH certificate for a user or host.
 */
export const createSshCert = async ({
  caPrivateKey,
  clientPublicKey,
  keyId,
  principals,
  requestedTtl, // in ms lib format
  certType,
  clockSkewSeconds = DEFAULT_CLOCK_SKEW_SECONDS,
  enforceExactExpiry = false
}: TCreateSshCertDTO) => {
  let ttl: number | undefined;

  if (requestedTtl) {
    const parsedTtl = Math.ceil(ms(requestedTtl) / 1000);
    if (parsedTtl > 0) ttl = parsedTtl;
  }

  if (!ttl) {
    throw new BadRequestError({
      message: "Failed to create SSH certificate due to missing TTL"
    });
  }

  // the skew is interpolated into ssh-keygen's -V argument, where a negative value reads as another
  // flag and a fractional one is rejected outright, both surfacing as an opaque non-zero exit
  if (!Number.isInteger(clockSkewSeconds) || clockSkewSeconds <= 0) {
    throw new BadRequestError({
      message: "Failed to create SSH certificate due to a clock skew that is not a whole number of seconds above zero"
    });
  }

  validateSshCertificateKeyId(keyId);
  await validateSshPublicKey(clientPublicKey);

  const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "ssh-cert-"));

  const publicKeyFile = path.join(tempDir, "user_key.pub");
  const privateKeyFile = path.join(tempDir, "ca_key");
  const signedPublicKeyFile = path.join(tempDir, "user_key-cert.pub");

  const serialNumber = createSshCertSerialNumber();
  const validitySeconds = enforceExactExpiry ? ttl : ttl + clockSkewSeconds;

  // Build `ssh-keygen` arguments for signing
  // Using an array avoids shell injection issues
  const sshKeygenArgs = [
    certType === "host" ? "-h" : null, // host certificate if needed
    "-s",
    privateKeyFile, // path to SSH CA private key
    "-I",
    keyId, // identity (key ID)
    "-n",
    principals.join(","), // principals
    "-V",
    `-${clockSkewSeconds}s:+${validitySeconds}s`, // validity, widened for clock skew at both ends
    "-z",
    serialNumber, // serial number
    publicKeyFile // public key file to sign
  ].filter(Boolean) as string[];

  try {
    // Write public and private keys to the temp directory
    await fs.writeFile(publicKeyFile, clientPublicKey, { mode: 0o600 });
    await fs.writeFile(privateKeyFile, caPrivateKey, { mode: 0o600 });

    // Execute the signing process
    await execFileAsync("ssh-keygen", sshKeygenArgs, { encoding: "utf8", timeout: EXEC_TIMEOUT_MS });

    // Read the signed public key from the generated cert file
    const signedPublicKey = await fs.readFile(signedPublicKeyFile, "utf8");

    return { serialNumber, signedPublicKey, ttl };
  } finally {
    // Cleanup the temporary directory and all its contents
    await fs.rm(tempDir, { recursive: true, force: true }).catch(() => {});
  }
};