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
feat(kms): add ML-DSA post-quantum signing algorithms (#6609)
Saif Ur Rahmanbf814916aee1
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.tsindex 3ac5621b0c..1be5e0520f 100644--- a/backend/src/ee/services/license/license-fns.ts+++ b/backend/src/ee/services/license/license-fns.ts@@ -102,6 +102,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({pkiAcme: true,pkiScep: false,pkiPqc: false,+ kmsPqc: false,enforceMfa: false,projectTemplates: false,kmip: false,diff --git a/backend/src/ee/services/license/license-types.ts b/backend/src/ee/services/license/license-types.tsindex 69b5e18c7f..5d2bb42730 100644--- a/backend/src/ee/services/license/license-types.ts+++ b/backend/src/ee/services/license/license-types.ts@@ -81,6 +81,7 @@ export type TFeatureSet = {pkiAcme: true;pkiScep: false;pkiPqc: false;+ kmsPqc: false;enforceMfa: false;projectTemplates: false;kmip: false;diff --git a/backend/src/lib/crypto/pqc/pqc-crypto.ts b/backend/src/lib/crypto/pqc/pqc-crypto.tsindex 4ac8c04dbf..3f8fcf8301 100644--- a/backend/src/lib/crypto/pqc/pqc-crypto.ts+++ b/backend/src/lib/crypto/pqc/pqc-crypto.ts@@ -345,4 +345,4 @@ const derivePublicKeyFromSecret = async (return { raw, spkiDer };};-export { derivePublicKeyFromSecret, isPqcCryptoKey, PqcCryptoKey };+export { derivePublicKeyFromSecret, detectPqcVariantFromDer, isPqcCryptoKey, PqcCryptoKey };diff --git a/backend/src/lib/crypto/pqc/pqc-openssl.ts b/backend/src/lib/crypto/pqc/pqc-openssl.tsindex 8db3d12c6b..7907f33d9b 100644--- a/backend/src/lib/crypto/pqc/pqc-openssl.ts+++ b/backend/src/lib/crypto/pqc/pqc-openssl.ts@@ -113,7 +113,11 @@ export const opensslVerify = async (publicDer: Buffer, signature: Buffer, data:writeFile(sigPath, signature, { mode: 0o600 }),writeFile(dataPath, data, { mode: 0o600 })]);- const { code, stderr } = await execOpenSSL([+ const {+ code,+ stderr,+ stdout: stdoutBuf+ } = await execOpenSSL(["pkeyutl","-verify","-pubin",@@ -128,7 +132,8 @@ export const opensslVerify = async (publicDer: Buffer, signature: Buffer, data:]);if (code === 0) return true;- if (stderr.includes("Signature Verification Failure")) return false;+ const output = `${stderr} ${String(stdoutBuf)}`;+ if (output.includes("Signature Verification Failure")) return false;throw new Error(`PQC OpenSSL verification failed (exit ${code}): ${stderr}`);});diff --git a/backend/src/lib/crypto/sign/index.ts b/backend/src/lib/crypto/sign/index.tsindex 5680cd27ae..25d631dbf4 100644--- a/backend/src/lib/crypto/sign/index.ts+++ b/backend/src/lib/crypto/sign/index.ts@@ -1,2 +1,2 @@-export { signingService } from "./signing";+export { isPqcKeyAlgorithm, KMS_TO_OPENSSL_NAME, signingService } from "./signing";export { AsymmetricKeyAlgorithm, SigningAlgorithm } from "./types";diff --git a/backend/src/lib/crypto/sign/signing.ts b/backend/src/lib/crypto/sign/signing.tsindex 28df6ec5e3..3b7c3c19de 100644--- a/backend/src/lib/crypto/sign/signing.ts+++ b/backend/src/lib/crypto/sign/signing.ts@@ -4,12 +4,15 @@ import path from "path";import { promisify } from "util";import { crypto } from "@app/lib/crypto/cryptography";+import { opensslDerivePublicKey, opensslGenpkey, opensslSign, opensslVerify } from "@app/lib/crypto/pqc/pqc-openssl";import { BadRequestError } from "@app/lib/errors";import { cleanTemporaryDirectory, createTemporaryDirectory, writeToTemporaryFile } from "@app/lib/files";import { logger } from "@app/lib/logger";import { AsymmetricKeyAlgorithm, SigningAlgorithm, TAsymmetricSignVerifyFns } from "./types";+export const isPqcKeyAlgorithm = (algo: string): boolean => algo.startsWith("ML_DSA");+const execFileAsync = promisify(execFile);interface SigningParams {@@ -30,6 +33,12 @@ const SHA256_DIGEST_LENGTH = 32;const SHA384_DIGEST_LENGTH = 48;const SHA512_DIGEST_LENGTH = 64;+export const KMS_TO_OPENSSL_NAME: Partial<Record<AsymmetricKeyAlgorithm, string>> = {+ [AsymmetricKeyAlgorithm.ML_DSA_44]: "ML-DSA-44",+ [AsymmetricKeyAlgorithm.ML_DSA_65]: "ML-DSA-65",+ [AsymmetricKeyAlgorithm.ML_DSA_87]: "ML-DSA-87"+};+/*** Service for cryptographic signing and verification operations using asymmetric keys*@@ -105,9 +114,11 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSiconst $validateAlgorithmWithKeyType = (signingAlgorithm: SigningAlgorithm) => {const isRsaKey = algorithm.startsWith("RSA");const isEccKey = algorithm.startsWith("ECC");+ const isPqcKey = isPqcKeyAlgorithm(algorithm);const isRsaAlgorithm = signingAlgorithm.startsWith("RSASSA");const isEccAlgorithm = signingAlgorithm.startsWith("ECDSA");+ const isPqcAlgorithm = isPqcKeyAlgorithm(signingAlgorithm);if (isRsaKey && !isRsaAlgorithm) {throw new BadRequestError({ message: `KMS RSA key cannot be used with ${signingAlgorithm}` });@@ -116,6 +127,14 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSiif (isEccKey && !isEccAlgorithm) {throw new BadRequestError({ message: `KMS ECC key cannot be used with ${signingAlgorithm}` });}++ if (isPqcKey) {+ if (!isPqcAlgorithm || (signingAlgorithm as string) !== (algorithm as string)) {+ throw new BadRequestError({+ message: `KMS ${algorithm} key can only be used with ${algorithm} signing algorithm`+ });+ }+ }};const $signRsaDigest = async (@@ -342,22 +361,26 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSi}};- const verifyDigestFunctionsMap: Record<- AsymmetricKeyAlgorithm,- (data: Buffer, signature: Buffer, publicKey: Buffer, hashAlgorithm: SupportedHashAlgorithm) => Promise<boolean>+ const verifyDigestFunctionsMap: Partial<+ Record<+ AsymmetricKeyAlgorithm,+ (data: Buffer, signature: Buffer, publicKey: Buffer, hashAlgorithm: SupportedHashAlgorithm) => Promise<boolean>+ >> = {[AsymmetricKeyAlgorithm.ECC_NIST_P256]: $verifyEccDigest,[AsymmetricKeyAlgorithm.RSA_4096]: $verifyRsaDigest};- const signDigestFunctionsMap: Record<- AsymmetricKeyAlgorithm,- (- data: Buffer,- privateKey: Buffer,- hashAlgorithm: SupportedHashAlgorithm,- signingAlgorithm: SigningAlgorithm- ) => Promise<Buffer>+ const signDigestFunctionsMap: Partial<+ Record<+ AsymmetricKeyAlgorithm,+ (+ data: Buffer,+ privateKey: Buffer,+ hashAlgorithm: SupportedHashAlgorithm,+ signingAlgorithm: SigningAlgorithm+ ) => Promise<Buffer>+ >> = {[AsymmetricKeyAlgorithm.ECC_NIST_P256]: $signEccDigest,[AsymmetricKeyAlgorithm.RSA_4096]: $signRsaDigest@@ -371,6 +394,14 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSi): Promise<Buffer> => {$validateAlgorithmWithKeyType(signingAlgorithm);+ if (isPqcKeyAlgorithm(algorithm)) {+ if (isDigest) {+ throw new BadRequestError({ message: "ML-DSA does not support digested input" });+ }+ const sig = await opensslSign(privateKey, data);+ return sig;+ }+const { hashAlgorithm, padding, saltLength } = $getSigningParams(signingAlgorithm);if (isDigest) {@@ -430,6 +461,14 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSisigningAlgorithm: SigningAlgorithm,isDigest: boolean): Promise<boolean> => {+ if (isPqcKeyAlgorithm(algorithm)) {+ $validateAlgorithmWithKeyType(signingAlgorithm);+ if (isDigest) {+ throw new BadRequestError({ message: "ML-DSA does not support digested input" });+ }+ return opensslVerify(publicKey, signature, data);+ }+try {$validateAlgorithmWithKeyType(signingAlgorithm);@@ -500,6 +539,14 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSi};const generateAsymmetricPrivateKey = async () => {+ if (isPqcKeyAlgorithm(algorithm)) {+ const opensslName = KMS_TO_OPENSSL_NAME[algorithm];+ if (!opensslName) {+ throw new Error(`Unsupported PQC algorithm: ${algorithm}`);+ }+ return opensslGenpkey(opensslName);+ }+const { privateKey } = await new Promise<{ privateKey: string }>((resolve, reject) => {if (algorithm.startsWith("RSA")) {crypto.nativeCrypto.generateKeyPair(@@ -543,7 +590,11 @@ export const signingService = (algorithm: AsymmetricKeyAlgorithm): TAsymmetricSireturn Buffer.from(privateKey);};- const getPublicKeyFromPrivateKey = (privateKey: Buffer) => {+ const getPublicKeyFromPrivateKey = async (privateKey: Buffer): Promise<Buffer> => {+ if (isPqcKeyAlgorithm(algorithm)) {+ return opensslDerivePublicKey(privateKey);+ }+const privateKeyObj = crypto.nativeCrypto.createPrivateKey({key: privateKey,format: "pem",diff --git a/backend/src/lib/crypto/sign/types.ts b/backend/src/lib/crypto/sign/types.tsindex aa81b40570..f483f6a464 100644--- a/backend/src/lib/crypto/sign/types.ts+++ b/backend/src/lib/crypto/sign/types.ts@@ -10,13 +10,16 @@ export type TAsymmetricSignVerifyFns = {isDigest: boolean) => Promise<boolean>;generateAsymmetricPrivateKey: () => Promise<Buffer>;- getPublicKeyFromPrivateKey: (privateKey: Buffer) => Buffer;+ getPublicKeyFromPrivateKey: (privateKey: Buffer) => Promise<Buffer>;};// Supported asymmetric key typesexport enum AsymmetricKeyAlgorithm {RSA_4096 = "RSA_4096",- ECC_NIST_P256 = "ECC_NIST_P256"+ ECC_NIST_P256 = "ECC_NIST_P256",+ ML_DSA_44 = "ML_DSA_44",+ ML_DSA_65 = "ML_DSA_65",+ ML_DSA_87 = "ML_DSA_87"}export const AsymmetricKeyAlgorithmEnum = z.enum(@@ -41,5 +44,10 @@ export enum SigningAlgorithm {// None of these are deterministic and include randomness like RSA PSS.ECDSA_SHA_512 = "ECDSA_SHA_512",ECDSA_SHA_384 = "ECDSA_SHA_384",- ECDSA_SHA_256 = "ECDSA_SHA_256"+ ECDSA_SHA_256 = "ECDSA_SHA_256",++ // ML-DSA (post-quantum) — signing algorithm equals key algorithm, no hash variant+ ML_DSA_44 = "ML_DSA_44",+ ML_DSA_65 = "ML_DSA_65",+ ML_DSA_87 = "ML_DSA_87"}diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 2c5ba47595..68dedbb4a1 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2406,7 +2406,8 @@ export const registerRoutes = async (const cmekService = cmekServiceFactory({kmsDAL,kmsService,- permissionService+ permissionService,+ licenseService});const externalMigrationQueue = externalMigrationQueueFactory({diff --git a/backend/src/server/routes/v1/cmek-router.ts b/backend/src/server/routes/v1/cmek-router.tsindex 4624a29479..6f23c5a82b 100644--- a/backend/src/server/routes/v1/cmek-router.ts+++ b/backend/src/server/routes/v1/cmek-router.ts@@ -39,6 +39,22 @@ const base64Schema = z.string().superRefine((val, ctx) => {}});+const signatureBase64Schema = z.string().superRefine((val, ctx) => {+ if (!isBase64(val)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "signature must be base64 encoded"+ });+ }++ if (getBase64SizeInBytes(val) > 8192) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "signature cannot exceed 8192 bytes"+ });+ }+});+export const registerCmekRouter = async (server: FastifyZodProvider) => {// create encryption keyserver.route({@@ -809,7 +825,7 @@ export const registerCmekRouter = async (server: FastifyZodProvider) => {body: z.object({isDigest: z.boolean().optional().default(false).describe(KMS.VERIFY.isDigest),data: base64Schema.describe(KMS.VERIFY.data),- signature: base64Schema.describe(KMS.VERIFY.signature),+ signature: signatureBase64Schema.describe(KMS.VERIFY.signature),signingAlgorithm: z.nativeEnum(SigningAlgorithm)}),response: {diff --git a/backend/src/services/cmek/cmek-service.ts b/backend/src/services/cmek/cmek-service.tsindex 53123c17e8..48a2b42640 100644--- a/backend/src/services/cmek/cmek-service.ts+++ b/backend/src/services/cmek/cmek-service.ts@@ -1,9 +1,10 @@import { ForbiddenError } from "@casl/ability";import { ActionProjectType } from "@app/db/schemas";+import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import { ProjectPermissionCmekActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";-import { AsymmetricKeyAlgorithm, SigningAlgorithm, signingService } from "@app/lib/crypto/sign";+import { AsymmetricKeyAlgorithm, isPqcKeyAlgorithm, SigningAlgorithm, signingService } from "@app/lib/crypto/sign";import { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";import { OrgServiceActor } from "@app/lib/types";@@ -32,11 +33,17 @@ type TCmekServiceFactoryDep = {kmsService: TKmsServiceFactory;kmsDAL: TKmsKeyDALFactory;permissionService: TPermissionServiceFactory;+ licenseService: Pick<TLicenseServiceFactory, "getPlan">;};export type TCmekServiceFactory = ReturnType<typeof cmekServiceFactory>;-export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TCmekServiceFactoryDep) => {+export const cmekServiceFactory = ({+ kmsService,+ kmsDAL,+ permissionService,+ licenseService+}: TCmekServiceFactoryDep) => {const createCmek = async ({ projectId, ...dto }: TCreateCmekDTO, actor: OrgServiceActor) => {const { permission } = await permissionService.getProjectPermission({actor: actor.type,@@ -48,6 +55,16 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TC});ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCmekActions.Create, ProjectPermissionSub.Cmek);+ if (isPqcKeyAlgorithm(dto.encryptionAlgorithm as string)) {+ const plan = await licenseService.getPlan(dto.orgId);+ if (!plan.kmsPqc) {+ throw new BadRequestError({+ message:+ "Your license does not include PQC algorithms. Please upgrade to the Enterprise plan to use a PQC algorithm."+ });+ }+ }+try {const cmek = await kmsService.generateKmsKey({...dto,@@ -245,18 +262,18 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TCconst encryptionAlgorithm = key.encryptionAlgorithm as TCmekKeyEncryptionAlgorithm;+ if (isPqcKeyAlgorithm(encryptionAlgorithm as string)) {+ return { signingAlgorithms: [encryptionAlgorithm as unknown as SigningAlgorithm], projectId: key.projectId };+ }+const algos = [{keyAlgorithm: "rsa",- signingAlgorithms: Object.values(SigningAlgorithm).filter((algorithm) =>- algorithm.toLowerCase().startsWith("rsa")- )+ signingAlgorithms: Object.values(SigningAlgorithm).filter((a) => a.toLowerCase().startsWith("rsa"))},{keyAlgorithm: "ecc",- signingAlgorithms: Object.values(SigningAlgorithm).filter((algorithm) =>- algorithm.toLowerCase().startsWith("ecdsa")- )+ signingAlgorithms: Object.values(SigningAlgorithm).filter((a) => a.toLowerCase().startsWith("ecdsa"))}];@@ -366,30 +383,32 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TCconst materialByKmsId = new Map(bulkMaterials.map((m) => [m.kmsId, m]));const asymmetricAlgorithms = new Set<string>(Object.values(AsymmetricKeyAlgorithm));- const result = keys.map((key) => {- const materialEntry = materialByKmsId.get(key.id);+ const result = await Promise.all(+ keys.map(async (key) => {+ const materialEntry = materialByKmsId.get(key.id);- if (!materialEntry) {- throw new NotFoundError({ message: `Key material not found for key ID "${key.id}"` });- }+ if (!materialEntry) {+ throw new NotFoundError({ message: `Key material not found for key ID "${key.id}"` });+ }- let publicKey: string | undefined;- if (asymmetricAlgorithms.has(key.encryptionAlgorithm)) {- const pubKeyBuffer = signingService(- key.encryptionAlgorithm as AsymmetricKeyAlgorithm- ).getPublicKeyFromPrivateKey(materialEntry.keyMaterial);- publicKey = pubKeyBuffer.toString("base64");- }+ let publicKey: string | undefined;+ if (asymmetricAlgorithms.has(key.encryptionAlgorithm)) {+ const pubKeyBuffer = await signingService(+ key.encryptionAlgorithm as AsymmetricKeyAlgorithm+ ).getPublicKeyFromPrivateKey(materialEntry.keyMaterial);+ publicKey = pubKeyBuffer.toString("base64");+ }- return {- keyId: key.id,- name: key.name,- keyUsage: key.keyUsage,- algorithm: key.encryptionAlgorithm,- privateKey: materialEntry.keyMaterial.toString("base64"),- ...(publicKey ? { publicKey } : {})- };- });+ return {+ keyId: key.id,+ name: key.name,+ keyUsage: key.keyUsage,+ algorithm: key.encryptionAlgorithm,+ privateKey: materialEntry.keyMaterial.toString("base64"),+ ...(publicKey ? { publicKey } : {})+ };+ })+ );return { keys: result, projectId };};@@ -414,6 +433,16 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TCForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCmekActions.Sign, ProjectPermissionSub.Cmek);+ if (isPqcKeyAlgorithm(key.encryptionAlgorithm)) {+ const plan = await licenseService.getPlan(key.orgId);+ if (!plan.kmsPqc) {+ throw new BadRequestError({+ message:+ "Your license does not include PQC algorithms. Please upgrade to the Enterprise plan to use a PQC algorithm."+ });+ }+ }+const sign = await kmsService.signWithKmsKey({ kmsId: keyId });const { signature, algorithm } = await sign({ data: Buffer.from(data, "base64"), signingAlgorithm, isDigest });@@ -449,6 +478,16 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TCForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCmekActions.Verify, ProjectPermissionSub.Cmek);+ if (isPqcKeyAlgorithm(key.encryptionAlgorithm)) {+ const plan = await licenseService.getPlan(key.orgId);+ if (!plan.kmsPqc) {+ throw new BadRequestError({+ message:+ "Your license does not include PQC algorithms. Please upgrade to the Enterprise plan to use a PQC algorithm."+ });+ }+ }+const verify = await kmsService.verifyWithKmsKey({ kmsId: keyId, signingAlgorithm });const { signatureValid, algorithm } = await verify({@@ -510,8 +549,21 @@ export const cmekServiceFactory = ({ kmsService, kmsDAL, permissionService }: TCForbiddenError.from(permission).throwUnlessCan(ProjectPermissionCmekActions.Create, ProjectPermissionSub.Cmek);+ const hasPqcKeys = keys.some((entry) => isPqcKeyAlgorithm(entry.algorithm as string));+ let pqcLicensed = true;+ if (hasPqcKeys) {+ const plan = await licenseService.getPlan(actor.orgId);+ pqcLicensed = !!plan.kmsPqc;+ }+const results = await Promise.allSettled(keys.map(async (entry): Promise<{ id: string; name: string }> => {+ if (isPqcKeyAlgorithm(entry.algorithm as string) && !pqcLicensed) {+ throw new BadRequestError({+ message:+ "Your license does not include PQC algorithms. Please upgrade to the Enterprise plan to use a PQC algorithm."+ });+ }const imported = await kmsService.importKeyMaterial({key: Buffer.from(entry.keyMaterial, "base64"),algorithm: entry.algorithm,diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.tsindex 3c232c2c79..7d640fbdf3 100644--- a/backend/src/services/kms/kms-service.ts+++ b/backend/src/services/kms/kms-service.ts@@ -17,7 +17,8 @@ import { PgSqlLock } from "@app/keystore/keystore";import { TEnvConfig } from "@app/lib/config/env";import { symmetricCipherService, SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";import { crypto } from "@app/lib/crypto/cryptography";-import { AsymmetricKeyAlgorithm, signingService } from "@app/lib/crypto/sign";+import { detectPqcVariantFromDer } from "@app/lib/crypto/pqc/pqc-crypto";+import { AsymmetricKeyAlgorithm, isPqcKeyAlgorithm, KMS_TO_OPENSSL_NAME, signingService } from "@app/lib/crypto/sign";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { alphaNumericNanoId } from "@app/lib/nanoid";@@ -70,6 +71,9 @@ export type TKmsServiceFactory = ReturnType<typeof kmsServiceFactory>;const KMS_VERSION = "v01";const KMS_VERSION_BLOB_LENGTH = 3;const KmsSanitizedSchema = KmsKeysSchema.extend({ isExternal: z.boolean() });+const OPENSSL_TO_KMS: Record<string, string> = Object.fromEntries(+ Object.entries(KMS_TO_OPENSSL_NAME).map(([k, v]) => [v, k])+);export const kmsServiceFactory = ({envConfig,@@ -112,7 +116,7 @@ export const kmsServiceFactory = ({kmsKeyMaterial = await generateAsymmetricPrivateKey();// daniel: safety check to ensure we're able to extract the public key from the private key before we proceed to key creation- getPublicKeyFromPrivateKey(kmsKeyMaterial);+ await getPublicKeyFromPrivateKey(kmsKeyMaterial);}if (!kmsKeyMaterial) {@@ -418,12 +422,45 @@ export const kmsServiceFactory = ({if (keyUsage === KmsKeyUsage.SIGN_VERIFY) {const { getPublicKeyFromPrivateKey } = signingService(algorithm as AsymmetricKeyAlgorithm);try {- getPublicKeyFromPrivateKey(key);+ await getPublicKeyFromPrivateKey(key);} catch {+ const expectedFormat = isPqcKeyAlgorithm(algorithm as string) ? "PKCS8 DER-encoded" : "PKCS8 PEM-encoded";throw new BadRequestError({- message: "Invalid private key material. Expected a PKCS8 PEM-encoded private key."+ message: `Invalid private key material. Expected a ${expectedFormat} private key.`});}++ if (isPqcKeyAlgorithm(algorithm as string)) {+ const detectedVariant = detectPqcVariantFromDer(key);+ const expectedVariant = KMS_TO_OPENSSL_NAME[algorithm as AsymmetricKeyAlgorithm];+ if (detectedVariant && expectedVariant && detectedVariant !== expectedVariant) {+ throw new BadRequestError({+ message: `Key material does not match the declared algorithm. Expected ${algorithm as string} but the key is ${OPENSSL_TO_KMS[detectedVariant] || detectedVariant}.`+ });+ }+ } else {+ const keyObj = crypto.nativeCrypto.createPrivateKey({+ key,+ format: "pem",+ type: "pkcs8"+ });+ const keyType = keyObj.asymmetricKeyType;+ const keyDetails = keyObj.asymmetricKeyDetails;++ if (algorithm === AsymmetricKeyAlgorithm.RSA_4096) {+ if (keyType !== "rsa" || keyDetails?.modulusLength !== 4096) {+ throw new BadRequestError({+ message: `Key material does not match the declared algorithm. Expected an RSA 4096-bit key.`+ });+ }+ } else if (algorithm === AsymmetricKeyAlgorithm.ECC_NIST_P256) {+ if (keyType !== "ec" || keyDetails?.namedCurve !== "prime256v1") {+ throw new BadRequestError({+ message: `Key material does not match the declared algorithm. Expected an EC P-256 key.`+ });+ }+ }+ }}const cipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);@@ -521,7 +558,7 @@ export const kmsServiceFactory = ({return async ({ data, signature, isDigest }: Pick<TVerifyWithKmsDTO, "data" | "signature" | "isDigest">) => {const kmsKey = keyCipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);- const publicKey = getPublicKeyFromPrivateKey(kmsKey);+ const publicKey = await getPublicKeyFromPrivateKey(kmsKey);const signatureValid = await verify(data, signature, publicKey, signingAlgorithm, isDigest);return Promise.resolve({ signatureValid, algorithm: signingAlgorithm });};diff --git a/docs/documentation/platform/kms/overview.mdx b/docs/documentation/platform/kms/overview.mdxindex feba08131f..98106f4543 100644--- a/docs/documentation/platform/kms/overview.mdx+++ b/docs/documentation/platform/kms/overview.mdx@@ -242,6 +242,17 @@ In the following steps, we explore how to generate a key and use it to sign data- `ECDSA SHA 384`: Not deterministic, and includes randomness.- `ECDSA SHA 256`: Not deterministic, and includes randomness.+ **For ML-DSA keys (post-quantum):**+ - `ML_DSA_44`: The signing algorithm is the same as the key algorithm.+ - `ML_DSA_65`: The signing algorithm is the same as the key algorithm.+ - `ML_DSA_87`: The signing algorithm is the same as the key algorithm.++ ML-DSA is a NIST-standardized post-quantum digital signature algorithm. Unlike RSA and ECC, each ML-DSA key variant has exactly one signing algorithm (itself), and does not use a separate hash algorithm.++ <Info>+ ML-DSA algorithms are an enterprise feature. Self-hosted users can contact [[email protected]](mailto:[email protected]) to purchase an enterprise license.+ </Info>+In this example, we'll use the `RSASSA PSS SHA 512` signing algorithm.<Note>@@ -417,15 +428,22 @@ The exported file is a JSON array where each entry is one of the following shapeexternal sources.</Accordion><Accordion title="What algorithms does Infisical KMS support?">- Currently Infisical supports 4 different key algorithms with different purposes:-- - `RSA_4096`: For signing and verifying data.- - `ECC_NIST_P256`: For signing and verifying data.-- - `AES-256-GCM`: For encryption and decryption operations.- - `AES-128-GCM`: For encryption and decryption operations.-- We anticipate to further expand our supported algorithms and support cryptographic operations in the future.+ Infisical supports the following key algorithms:++ **Signing and verification:**+ - `RSA_4096`+ - `ECC_NIST_P256`+ - `ML_DSA_44` (post-quantum)+ - `ML_DSA_65` (post-quantum)+ - `ML_DSA_87` (post-quantum)++ **Encryption and decryption:**+ - `AES-256-GCM`+ - `AES-128-GCM`++ <Info>+ ML-DSA algorithms are an enterprise feature. Self-hosted users can contact [[email protected]](mailto:[email protected]) to purchase an enterprise license.+ </Info></Accordion><Accordion title="How do I sign and verify a digest using the Infisical KMS?">To sign and verify a digest using the Infisical KMS, you can use the `Sign` and `Verify` endpoints respectively.@@ -486,7 +504,7 @@ The exported file is a JSON array where each entry is one of the following shape```<Note>- Please note that `RSA PSS` signing algorithms are not supported for digest signing and verification. Please use `RSA PKCS1 V1.5` signing algorithms for digest signing and verification, or `ECDSA` if you're using an ECC key.+ Please note that `RSA PSS` signing algorithms are not supported for digest signing and verification. Please use `RSA PKCS1 V1.5` signing algorithms for digest signing and verification, or `ECDSA` if you're using an ECC key. ML-DSA keys also do not support digest signing and verification, as ML-DSA handles hashing internally.</Note></Accordion></AccordionGroup>diff --git a/frontend/src/helpers/kms.ts b/frontend/src/helpers/kms.tsindex 64b85dc2cb..11fd74fef1 100644--- a/frontend/src/helpers/kms.ts+++ b/frontend/src/helpers/kms.ts@@ -1,4 +1,10 @@-import { AsymmetricKeyAlgorithm, KmsKeyUsage, SymmetricKeyAlgorithm } from "@app/hooks/api/cmeks";+import {+ AsymmetricKeyAlgorithm,+ KmsKeyUsage,+ SigningAlgorithm,+ SymmetricKeyAlgorithm,+ TCmek+} from "@app/hooks/api/cmeks";export const kmsKeyUsageOptions: Record<KmsKeyUsage,@@ -25,3 +31,13 @@ export const keyUsageDefaultOption: Record<[KmsKeyUsage.ENCRYPT_DECRYPT]: SymmetricKeyAlgorithm.AES_GCM_256,[KmsKeyUsage.SIGN_VERIFY]: AsymmetricKeyAlgorithm.RSA_4096};++export const getDefaultSigningAlgorithm = (cmek: TCmek): SigningAlgorithm => {+ if (cmek?.encryptionAlgorithm?.startsWith("ML_DSA")) {+ return cmek.encryptionAlgorithm as unknown as SigningAlgorithm;+ }+ if (cmek?.encryptionAlgorithm?.startsWith("RSA")) {+ return SigningAlgorithm.RSASSA_PSS_SHA_512;+ }+ return SigningAlgorithm.ECDSA_SHA_256;+};diff --git a/frontend/src/hooks/api/cmeks/types.ts b/frontend/src/hooks/api/cmeks/types.tsindex ff18e9fd56..a1063db64b 100644--- a/frontend/src/hooks/api/cmeks/types.ts+++ b/frontend/src/hooks/api/cmeks/types.ts@@ -132,7 +132,10 @@ export enum CmekOrderBy {export enum AsymmetricKeyAlgorithm {RSA_4096 = "RSA_4096",- ECC_NIST_P256 = "ECC_NIST_P256"+ ECC_NIST_P256 = "ECC_NIST_P256",+ ML_DSA_44 = "ML_DSA_44",+ ML_DSA_65 = "ML_DSA_65",+ ML_DSA_87 = "ML_DSA_87"}// Supported symmetric encrypt/decrypt algorithms@@ -160,5 +163,10 @@ export enum SigningAlgorithm {// ECDSA algorithmsECDSA_SHA_256 = "ECDSA_SHA_256",ECDSA_SHA_384 = "ECDSA_SHA_384",- ECDSA_SHA_512 = "ECDSA_SHA_512"+ ECDSA_SHA_512 = "ECDSA_SHA_512",++ // ML-DSA (post-quantum) — signing algorithm equals key algorithm+ ML_DSA_44 = "ML_DSA_44",+ ML_DSA_65 = "ML_DSA_65",+ ML_DSA_87 = "ML_DSA_87"}diff --git a/frontend/src/hooks/api/subscriptions/types.ts b/frontend/src/hooks/api/subscriptions/types.tsindex f50cc94785..4d73a7d354 100644--- a/frontend/src/hooks/api/subscriptions/types.ts+++ b/frontend/src/hooks/api/subscriptions/types.ts@@ -63,6 +63,7 @@ export type SubscriptionPlan = {pkiAcme: boolean;pkiLegacyTemplates: boolean;pkiPqc: boolean;+ kmsPqc: boolean;enforceMfa: boolean;enforceGoogleSSO: boolean;projectTemplates: boolean;diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsxindex e79d91e151..ececf5ccee 100644--- a/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx+++ b/frontend/src/pages/kms/OverviewPage/components/CmekModal.tsx@@ -14,7 +14,8 @@ import {SelectItem,TextArea} from "@app/components/v2";-import { useProject } from "@app/context";+import { Badge } from "@app/components/v3";+import { useProject, useSubscription } from "@app/context";import { keyUsageDefaultOption, kmsKeyUsageOptions } from "@app/helpers/kms";import {AllowedEncryptionKeyAlgorithms,@@ -52,6 +53,7 @@ const CmekForm = ({ onComplete, cmek }: FormProps) => {const { currentProject } = useProject();const projectId = currentProject.id;const isUpdate = !!cmek;+ const { subscription } = useSubscription();const {control,@@ -185,11 +187,22 @@ const CmekForm = ({ onComplete, cmek }: FormProps) => {return false;})// eslint-disable-next-line @typescript-eslint/no-unused-vars- .map(([_, value]) => (- <SelectItem value={value} key={`encryption-algorithm-${value}`}>- <span className="uppercase">{value.replaceAll("-", " ")}</span>- </SelectItem>- ))}+ .map(([_, value]) => {+ const isPqc = value.startsWith("ML_DSA");+ const isDisabled = isPqc && !subscription?.kmsPqc;+ return (+ <SelectItem+ value={value}+ key={`encryption-algorithm-${value}`}+ isDisabled={isDisabled}+ >+ <div className="flex items-center gap-2">+ <span className="uppercase">{value.replaceAll("-", " ")}</span>+ {isDisabled && <Badge variant="info">Enterprise</Badge>}+ </div>+ </SelectItem>+ );+ })}</Select></FormControl>)}diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekSignModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekSignModal.tsxindex e52c03dbe6..69c10b8f0a 100644--- a/frontend/src/pages/kms/OverviewPage/components/CmekSignModal.tsx+++ b/frontend/src/pages/kms/OverviewPage/components/CmekSignModal.tsx@@ -17,6 +17,7 @@ import {TextArea,Tooltip} from "@app/components/v2";+import { getDefaultSigningAlgorithm } from "@app/helpers/kms";import { useTimedReset } from "@app/hooks";import { SigningAlgorithm, TCmek, useCmekSign } from "@app/hooks/api/cmeks";@@ -47,9 +48,7 @@ const SignForm = ({ cmek }: FormProps) => {} = useForm<FormData>({resolver: zodResolver(formSchema),defaultValues: {- signingAlgorithm: cmek?.encryptionAlgorithm?.startsWith("RSA")- ? SigningAlgorithm.RSASSA_PSS_SHA_512- : SigningAlgorithm.ECDSA_SHA_256,+ signingAlgorithm: getDefaultSigningAlgorithm(cmek),isBase64Encoded: false}});@@ -74,11 +73,12 @@ const SignForm = ({ cmek }: FormProps) => {setCopySignature("Copied to Clipboard");};- const allowedSigningAlgorithms = Object.values(SigningAlgorithm).filter((a) =>- cmek?.encryptionAlgorithm?.startsWith("RSA")- ? a.toLowerCase().startsWith("rsa")- : a.toLowerCase().startsWith("ecdsa")- );+ const allowedSigningAlgorithms = Object.values(SigningAlgorithm).filter((a) => {+ if (cmek?.encryptionAlgorithm?.startsWith("ML_DSA"))+ return (a as string) === (cmek.encryptionAlgorithm as string);+ if (cmek?.encryptionAlgorithm?.startsWith("RSA")) return a.toLowerCase().startsWith("rsa");+ return a.toLowerCase().startsWith("ecdsa");+ });return (<form onSubmit={handleSubmit(handleSignData)}>diff --git a/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx b/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsxindex d8203e373d..4edc4a7171 100644--- a/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx+++ b/frontend/src/pages/kms/OverviewPage/components/CmekVerifyModal.tsx@@ -19,6 +19,7 @@ import {Tooltip} from "@app/components/v2";import { Badge } from "@app/components/v3";+import { getDefaultSigningAlgorithm } from "@app/helpers/kms";import { SigningAlgorithm, TCmek, useCmekVerify } from "@app/hooks/api/cmeks";import { isBase64 } from "@app/lib/fn/base64";@@ -61,9 +62,7 @@ const VerifyForm = ({ cmek }: FormProps) => {} = useForm<FormData>({resolver: zodResolver(formSchema),defaultValues: {- signingAlgorithm: cmek?.encryptionAlgorithm?.startsWith("RSA")- ? SigningAlgorithm.RSASSA_PSS_SHA_512- : SigningAlgorithm.ECDSA_SHA_256,+ signingAlgorithm: getDefaultSigningAlgorithm(cmek),isBase64Encoded: false}});@@ -92,11 +91,12 @@ const VerifyForm = ({ cmek }: FormProps) => {const signatureValid = cmekVerify.data?.signatureValid;const signingAlgorithm = cmekVerify.data?.signingAlgorithm;- const allowedSigningAlgorithms = Object.values(SigningAlgorithm).filter((a) =>- cmek?.encryptionAlgorithm?.startsWith("RSA")- ? a.toLowerCase().startsWith("rsa")- : a.toLowerCase().startsWith("ecdsa")- );+ const allowedSigningAlgorithms = Object.values(SigningAlgorithm).filter((a) => {+ if (cmek?.encryptionAlgorithm?.startsWith("ML_DSA"))+ return (a as string) === (cmek.encryptionAlgorithm as string);+ if (cmek?.encryptionAlgorithm?.startsWith("RSA")) return a.toLowerCase().startsWith("rsa");+ return a.toLowerCase().startsWith("ecdsa");+ });return (<form onSubmit={handleSubmit(handleVerifyData)}>