Skip to content

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

15.9 KB
Raw Blame
import * as x509 from "@peculiar/x509";

import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";

import {
  createDistinguishedName,
  extractDnParts,
  keyAlgorithmToAlgCfg
} from "../certificate-authority/certificate-authority-fns";
import { validateAndMapAltNameType } from "../certificate-authority/certificate-authority-validators";
import { TCertificateRequest } from "../certificate-policy/certificate-policy-types";
import {
  CertExtendedKeyUsageOIDToName,
  CertKeyAlgorithm,
  CertKeyUsage,
  CertSignatureAlgorithm,
  mapLegacyAltNameType,
  TAltNameMapping,
  TAltNameType
} from "../certificate/certificate-types";
import {
  GENERAL_NAME_TYPES_WITH_OTHER_NAME,
  mapLegacyExtendedKeyUsageToStandard,
  mapLegacyKeyUsageToStandard,
  SUPPORTED_GENERAL_NAME_TYPES
} from "./certificate-constants";
import {
  appendCustomExtensions,
  describeCustomExtensionValue,
  isIssuerGeneratedExtensionOid,
  isReservedExtensionOid,
  TIssuedCustomExtension
} from "./certificate-extension-fns";

/**
 * Extracts certificate request data from a CSR string
 * @param csr - The CSR in PEM format
 * @returns TCertificateRequest object with parsed CSR data
 *
 * Note: Only includes keys for fields that are actually present in the CSR.
 * This allows applyProfileDefaults to correctly apply defaults for missing fields
 * (e.g., ACME clients like CertBot often omit CN, putting domain only in SAN).
 */
export const parseCsr = (csr: string): x509.Pkcs10CertificateRequest => {
  try {
    return new x509.Pkcs10CertificateRequest(csr);
  } catch {
    throw new BadRequestError({
      message: "The certificate signing request could not be parsed. Supply a PEM-encoded PKCS#10 request."
    });
  }
};

export const extractCertificateRequestFromCSR = (csr: string): TCertificateRequest => {
  const csrObj = parseCsr(csr);
  const subject = extractDnParts(csrObj.subjectName);

  // Only include keys for fields that have values, so applyProfileDefaults
  // can distinguish "absent" (use default) from "explicitly set".
  const certificateRequest: TCertificateRequest = {};
  if (subject.commonName) certificateRequest.commonName = subject.commonName;
  if (subject.domainComponents?.length) certificateRequest.domainComponents = subject.domainComponents;
  if (subject.organization) certificateRequest.organization = subject.organization;
  if (subject.ou) certificateRequest.organizationalUnit = subject.ou;
  if (subject.locality) certificateRequest.locality = subject.locality;
  if (subject.province) certificateRequest.state = subject.province;
  if (subject.country) certificateRequest.country = subject.country;

  const csrKeyUsageExtension = csrObj.getExtension("2.5.29.15") as x509.KeyUsagesExtension;
  if (csrKeyUsageExtension) {
    const csrKeyUsages = Object.values(CertKeyUsage).filter(
      // eslint-disable-next-line no-bitwise
      (keyUsage) => (x509.KeyUsageFlags[keyUsage] & csrKeyUsageExtension.usages) !== 0
    );
    const mapped = csrKeyUsages.map(mapLegacyKeyUsageToStandard);
    if (mapped.length > 0) {
      certificateRequest.keyUsages = mapped;
    }
  }

  const csrExtendedKeyUsageExtension = csrObj.getExtension("2.5.29.37") as x509.ExtendedKeyUsageExtension;
  if (csrExtendedKeyUsageExtension) {
    const mapped = csrExtendedKeyUsageExtension.usages.map((ekuOid) => {
      const name = CertExtendedKeyUsageOIDToName[ekuOid as string];
      if (!name) {
        throw new BadRequestError({ message: `Unsupported extended key usage in CSR: ${ekuOid as string}` });
      }
      return mapLegacyExtendedKeyUsageToStandard(name);
    });
    if (mapped.length > 0) {
      certificateRequest.extendedKeyUsages = mapped;
    }
  }

  const sanExtension = csrObj.extensions.find((ext) => ext.type === "2.5.29.17");
  if (sanExtension) {
    const sanNames = new x509.GeneralNames(sanExtension.value);
    const altNamesArray: TAltNameMapping[] = sanNames.items
      .filter((value) => SUPPORTED_GENERAL_NAME_TYPES.has(value.type))
      .map((name): TAltNameMapping => {
        if (GENERAL_NAME_TYPES_WITH_OTHER_NAME.has(name.type)) {
          return { type: name.type as TAltNameType, value: name.value };
        }

        const altNameType = validateAndMapAltNameType(name.value);
        if (!altNameType) {
          throw new BadRequestError({ message: `Invalid altName from CSR: ${name.value}` });
        }
        return altNameType;
      });

    certificateRequest.subjectAlternativeNames = altNamesArray.map((altName) => ({
      type: mapLegacyAltNameType(altName.type),
      value: altName.value
    }));
  }

  const basicConstraintsExtension = csrObj.getExtension("2.5.29.19") as x509.BasicConstraintsExtension;
  if (basicConstraintsExtension) {
    const parsedPathLength = basicConstraintsExtension.pathLength;
    certificateRequest.basicConstraints = {
      isCA: basicConstraintsExtension.ca,
      pathLength: parsedPathLength !== undefined && parsedPathLength >= 0 ? parsedPathLength : undefined
    };
  }

  // openssl x509 -x509toreq copies the old issuer's extensions in. Asking a new CA to repeat them
  // gets the request rejected or produces a certificate that fails validation.
  const csrCustomExtensions = csrObj.extensions
    .filter((extension) => !isReservedExtensionOid(extension.type) && !isIssuerGeneratedExtensionOid(extension.type))
    .map((extension) => ({
      oid: extension.type,
      value:
        describeCustomExtensionValue(extension.type, Buffer.from(new Uint8Array(extension.value)).toString("base64")) ??
        undefined,
      critical: extension.critical
    }));

  if (csrCustomExtensions.length) {
    certificateRequest.customExtensions = csrCustomExtensions;
  }

  return certificateRequest;
};

export const buildSubjectOverrideForCsr = (
  csr: string,
  request: Pick<
    TCertificateRequest,
    "commonName" | "organization" | "organizationalUnit" | "country" | "state" | "locality" | "domainComponents"
  >
): string => {
  const csrSubject = extractDnParts(parseCsr(csr).subjectName);

  return createDistinguishedName({
    commonName: csrSubject.commonName ?? request.commonName,
    organization: csrSubject.organization ?? request.organization,
    ou: csrSubject.ou ?? request.organizationalUnit,
    country: csrSubject.country ?? request.country,
    province: csrSubject.province ?? request.state,
    locality: csrSubject.locality ?? request.locality,
    domainComponents: csrSubject.domainComponents ?? request.domainComponents
  });
};

/**
 * Extracts the key algorithm and signature algorithm from a CSR
 * @param csr - The CSR in PEM format
 * @returns Object containing keyAlgorithm and signatureAlgorithm
 */
export const extractAlgorithmsFromCSR = (csr: string) => {
  const csrObj = parseCsr(csr);

  // Extract key algorithm from public key
  const { publicKey } = csrObj;
  let keyAlgorithm: CertKeyAlgorithm;

  if (publicKey.algorithm.name === "RSASSA-PKCS1-v1_5") {
    const rsaPublicKey = publicKey as unknown as { algorithm: { modulusLength: number } };
    const keySize = rsaPublicKey.algorithm.modulusLength;
    switch (keySize) {
      case 2048:
        keyAlgorithm = CertKeyAlgorithm.RSA_2048;
        break;
      case 3072:
        keyAlgorithm = CertKeyAlgorithm.RSA_3072;
        break;
      case 4096:
        keyAlgorithm = CertKeyAlgorithm.RSA_4096;
        break;
      default:
        throw new BadRequestError({
          message: `Unsupported RSA key size in CSR: ${keySize}. Supported: 2048, 3072, 4096`
        });
    }
  } else if (publicKey.algorithm.name === "ECDSA") {
    const ecPublicKey = publicKey as unknown as { algorithm: { namedCurve: string } };
    const { namedCurve } = ecPublicKey.algorithm;
    switch (namedCurve) {
      case "P-256":
        keyAlgorithm = CertKeyAlgorithm.ECDSA_P256;
        break;
      case "P-384":
        keyAlgorithm = CertKeyAlgorithm.ECDSA_P384;
        break;
      case "P-521":
        keyAlgorithm = CertKeyAlgorithm.ECDSA_P521;
        break;
      default:
        throw new BadRequestError({
          message: `Unsupported ECDSA curve in CSR: ${namedCurve}. Supported: P-256, P-384, P-521`
        });
    }
  } else if (publicKey.algorithm.name.startsWith("ML-DSA")) {
    switch (publicKey.algorithm.name) {
      case "ML-DSA-44":
        keyAlgorithm = CertKeyAlgorithm.ML_DSA_44;
        break;
      case "ML-DSA-65":
        keyAlgorithm = CertKeyAlgorithm.ML_DSA_65;
        break;
      case "ML-DSA-87":
        keyAlgorithm = CertKeyAlgorithm.ML_DSA_87;
        break;
      default:
        throw new BadRequestError({
          message: `Unsupported ML-DSA variant in CSR: ${publicKey.algorithm.name}. Supported: ML-DSA-44, ML-DSA-65, ML-DSA-87`
        });
    }
  } else if (publicKey.algorithm.name.startsWith("SLH-DSA")) {
    switch (publicKey.algorithm.name) {
      case "SLH-DSA-SHA2-128f":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHA2_128F;
        break;
      case "SLH-DSA-SHA2-128s":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHA2_128S;
        break;
      case "SLH-DSA-SHA2-192f":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHA2_192F;
        break;
      case "SLH-DSA-SHA2-192s":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHA2_192S;
        break;
      case "SLH-DSA-SHA2-256f":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHA2_256F;
        break;
      case "SLH-DSA-SHA2-256s":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHA2_256S;
        break;
      case "SLH-DSA-SHAKE-128f":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHAKE_128F;
        break;
      case "SLH-DSA-SHAKE-128s":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHAKE_128S;
        break;
      case "SLH-DSA-SHAKE-192f":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHAKE_192F;
        break;
      case "SLH-DSA-SHAKE-192s":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHAKE_192S;
        break;
      case "SLH-DSA-SHAKE-256f":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHAKE_256F;
        break;
      case "SLH-DSA-SHAKE-256s":
        keyAlgorithm = CertKeyAlgorithm.SLH_DSA_SHAKE_256S;
        break;
      default:
        throw new BadRequestError({
          message: `Unsupported SLH-DSA variant in CSR: ${publicKey.algorithm.name}. Supported: SLH-DSA-SHA2-128f/s, SLH-DSA-SHA2-192f/s, SLH-DSA-SHA2-256f/s, SLH-DSA-SHAKE-128f/s, SLH-DSA-SHAKE-192f/s, SLH-DSA-SHAKE-256f/s`
        });
    }
  } else {
    throw new BadRequestError({
      message: `Unsupported key algorithm in CSR: ${publicKey.algorithm.name}. Supported: RSASSA-PKCS1-v1_5, ECDSA, ML-DSA, SLH-DSA`
    });
  }

  const signatureAlgorithm = csrObj.signatureAlgorithm.name;
  const hashName = (csrObj.signatureAlgorithm as unknown as { hash?: { name: string } }).hash?.name;

  let normalizedSignatureAlg: CertSignatureAlgorithm;

  if (signatureAlgorithm === "RSASSA-PKCS1-v1_5") {
    switch (hashName) {
      case "SHA-256":
        normalizedSignatureAlg = CertSignatureAlgorithm.RSA_SHA256;
        break;
      case "SHA-384":
        normalizedSignatureAlg = CertSignatureAlgorithm.RSA_SHA384;
        break;
      case "SHA-512":
        normalizedSignatureAlg = CertSignatureAlgorithm.RSA_SHA512;
        break;
      default:
        throw new BadRequestError({
          message: `Unsupported RSA hash algorithm in CSR: ${hashName}. Supported: SHA-256, SHA-384, SHA-512`
        });
    }
  } else if (signatureAlgorithm === "ECDSA") {
    switch (hashName) {
      case "SHA-256":
        normalizedSignatureAlg = CertSignatureAlgorithm.ECDSA_SHA256;
        break;
      case "SHA-384":
        normalizedSignatureAlg = CertSignatureAlgorithm.ECDSA_SHA384;
        break;
      case "SHA-512":
        normalizedSignatureAlg = CertSignatureAlgorithm.ECDSA_SHA512;
        break;
      default:
        throw new BadRequestError({
          message: `Unsupported ECDSA hash algorithm in CSR: ${hashName}. Supported: SHA-256, SHA-384, SHA-512`
        });
    }
  } else if (signatureAlgorithm.startsWith("ML-DSA")) {
    switch (signatureAlgorithm) {
      case "ML-DSA-44":
        normalizedSignatureAlg = CertSignatureAlgorithm.ML_DSA_44;
        break;
      case "ML-DSA-65":
        normalizedSignatureAlg = CertSignatureAlgorithm.ML_DSA_65;
        break;
      case "ML-DSA-87":
        normalizedSignatureAlg = CertSignatureAlgorithm.ML_DSA_87;
        break;
      default:
        throw new BadRequestError({
          message: `Unsupported ML-DSA variant in CSR: ${signatureAlgorithm}. Supported: ML-DSA-44, ML-DSA-65, ML-DSA-87`
        });
    }
  } else if (signatureAlgorithm.startsWith("SLH-DSA")) {
    switch (signatureAlgorithm) {
      case "SLH-DSA-SHA2-128f":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHA2_128F;
        break;
      case "SLH-DSA-SHA2-128s":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHA2_128S;
        break;
      case "SLH-DSA-SHA2-192f":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHA2_192F;
        break;
      case "SLH-DSA-SHA2-192s":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHA2_192S;
        break;
      case "SLH-DSA-SHA2-256f":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHA2_256F;
        break;
      case "SLH-DSA-SHA2-256s":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHA2_256S;
        break;
      case "SLH-DSA-SHAKE-128f":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHAKE_128F;
        break;
      case "SLH-DSA-SHAKE-128s":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHAKE_128S;
        break;
      case "SLH-DSA-SHAKE-192f":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHAKE_192F;
        break;
      case "SLH-DSA-SHAKE-192s":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHAKE_192S;
        break;
      case "SLH-DSA-SHAKE-256f":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHAKE_256F;
        break;
      case "SLH-DSA-SHAKE-256s":
        normalizedSignatureAlg = CertSignatureAlgorithm.SLH_DSA_SHAKE_256S;
        break;
      default:
        throw new BadRequestError({
          message: `Unsupported SLH-DSA variant in CSR: ${signatureAlgorithm}. Supported: SLH-DSA-SHA2-128f/s, SLH-DSA-SHA2-192f/s, SLH-DSA-SHA2-256f/s, SLH-DSA-SHAKE-128f/s, SLH-DSA-SHAKE-192f/s, SLH-DSA-SHAKE-256f/s`
        });
    }
  } else {
    throw new BadRequestError({
      message: `Unsupported signature algorithm in CSR: ${signatureAlgorithm}. Supported: RSASSA-PKCS1-v1_5, ECDSA, ML-DSA, SLH-DSA`
    });
  }

  return {
    keyAlgorithm,
    signatureAlgorithm: normalizedSignatureAlg
  };
};

/**
 * Generates a leaf keypair and builds a PKCS#10 CSR for it. Callers pass the subject DN and the
 * WebCrypto algorithm config (from keyAlgorithmToAlgCfg); DNS SANs are optional.
 * Returns the private key (PKCS#8 PEM) plus the CSR in both PEM and base64-DER form.
 */
export const generateLeafKeypairAndCsr = async ({
  subjectName,
  algorithm,
  altNames = [],
  customExtensions = []
}: {
  subjectName: string;
  algorithm: ReturnType<typeof keyAlgorithmToAlgCfg>;
  altNames?: string[];
  customExtensions?: TIssuedCustomExtension[];
}): Promise<{ privateKeyPem: string; csrPem: string; csrDerBase64: string }> => {
  const leafKeys = await crypto.nativeCrypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
  const skLeafObj = crypto.nativeCrypto.KeyObject.from(leafKeys.privateKey);
  const privateKeyPem = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;

  const csrExtensions: x509.Extension[] = [];
  if (altNames.length > 0) {
    csrExtensions.push(
      new x509.SubjectAlternativeNameExtension(
        altNames.map((value) => ({ type: "dns" as TAltNameType, value })),
        false
      )
    );
  }
  appendCustomExtensions(csrExtensions, customExtensions);

  const csrObj = await x509.Pkcs10CertificateRequestGenerator.create({
    name: subjectName,
    keys: leafKeys,
    signingAlgorithm: algorithm,
    ...(csrExtensions.length > 0 && { extensions: csrExtensions })
  });

  return {
    privateKeyPem,
    csrPem: csrObj.toString("pem"),
    csrDerBase64: Buffer.from(new Uint8Array(csrObj.rawData)).toString("base64")
  };
};