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
PKI PQC algorithms improvement
Carlos Monastyrski6574c7cec9ef
diff --git a/Dockerfile.fips.standalone-infisical b/Dockerfile.fips.standalone-infisicalindex 731c4725c3..eb1eeb9d31 100644--- a/Dockerfile.fips.standalone-infisical+++ b/Dockerfile.fips.standalone-infisical@@ -124,6 +124,7 @@ RUN apt-get update && apt-get install -y \automake \libtool \wget \+ perl \libssl-dev \ca-certificates \curl \@@ -185,6 +186,18 @@ RUN wget https://www.openssl.org/source/openssl-3.1.2.tar.gz \# Install smbclient for Windows SMB operationsRUN apt-get update && apt-get install -y smbclient && rm -rf /var/lib/apt/lists/*+# Build OpenSSL 3.5.6 for PQC (ML-DSA / SLH-DSA) certificate support.+# Installed to /opt/openssl-pqc so it does not conflict with the FIPS OpenSSL above.+WORKDIR /tmp/openssl-pqc-build+RUN wget -q https://github.com/openssl/openssl/releases/download/openssl-3.5.6/openssl-3.5.6.tar.gz \+ && tar -xf openssl-3.5.6.tar.gz \+ && cd openssl-3.5.6 \+ && ./Configure --prefix=/opt/openssl-pqc --openssldir=/opt/openssl-pqc/ssl no-docs \+ && make -j"$(nproc)" \+ && make install_sw \+ && cd / \+ && rm -rf /tmp/openssl-pqc-build+# Install Infisical CLIRUN curl -1sLf 'https://artifacts-cli.infisical.com/setup.deb.sh' | bash \&& apt-get update && apt-get install -y infisical=0.43.47 \diff --git a/Dockerfile.standalone-infisical b/Dockerfile.standalone-infisicalindex e8d7af0295..d15de26a28 100644--- a/Dockerfile.standalone-infisical+++ b/Dockerfile.standalone-infisical@@ -137,6 +137,7 @@ RUN apt-get update && apt-get install -y \libc-dev \freetds-dev \wget \+ perl \openssh-client \&& rm -rf /var/lib/apt/lists/*@@ -170,6 +171,18 @@ RUN ARCH=$(dpkg --print-architecture) && \# Install smbclient for Windows SMB operationsRUN apt-get update && apt-get install -y smbclient && rm -rf /var/lib/apt/lists/*+# Build OpenSSL 3.5.6 for PQC (ML-DSA / SLH-DSA) certificate support.+# Installed to /opt/openssl-pqc so it does not conflict with the system OpenSSL.+WORKDIR /tmp/openssl-build+RUN wget -q https://github.com/openssl/openssl/releases/download/openssl-3.5.6/openssl-3.5.6.tar.gz \+ && tar -xf openssl-3.5.6.tar.gz \+ && cd openssl-3.5.6 \+ && ./Configure --prefix=/opt/openssl-pqc --openssldir=/opt/openssl-pqc/ssl no-docs \+ && make -j"$(nproc)" \+ && make install_sw \+ && cd / \+ && rm -rf /tmp/openssl-build+# Install Infisical CLIRUN curl -1sLf 'https://artifacts-cli.infisical.com/setup.deb.sh' | bash \&& apt-get update && apt-get install -y infisical=0.43.47 \diff --git a/backend/Dockerfile.dev b/backend/Dockerfile.devindex 1a83888fe7..943284aaf7 100644--- a/backend/Dockerfile.dev+++ b/backend/Dockerfile.dev@@ -21,6 +21,8 @@ RUN apt-get update && apt-get install -y \openssh-client \openssl \curl \+ wget \+ perl \pkg-config \unzip@@ -76,6 +78,17 @@ RUN mkdir -p /opt/oracle && \echo /opt/oracle/instantclient_23_26 > /etc/ld.so.conf.d/oracle-instantclient.conf && \ldconfig+# Build OpenSSL 3.5.6 for PQC (ML-DSA / SLH-DSA) certificate support.+WORKDIR /tmp/openssl-pqc-build+RUN wget -q https://github.com/openssl/openssl/releases/download/openssl-3.5.6/openssl-3.5.6.tar.gz \+ && tar -xf openssl-3.5.6.tar.gz \+ && cd openssl-3.5.6 \+ && ./Configure --prefix=/opt/openssl-pqc --openssldir=/opt/openssl-pqc/ssl no-docs \+ && make -j"$(nproc)" \+ && make install_sw \+ && cd / \+ && rm -rf /tmp/openssl-pqc-build+# ? App setup# Install smbclient for Windows SMB operationsdiff --git a/backend/Dockerfile.dev.fips b/backend/Dockerfile.dev.fipsindex 94180aab34..573e109ceb 100644--- a/backend/Dockerfile.dev.fips+++ b/backend/Dockerfile.dev.fips@@ -89,6 +89,17 @@ RUN wget https://www.openssl.org/source/openssl-3.1.2.tar.gz \&& apt-get clean \&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*+# Build OpenSSL 3.5.6 for PQC (ML-DSA / SLH-DSA) certificate support.+WORKDIR /tmp/openssl-pqc-build+RUN wget -q https://github.com/openssl/openssl/releases/download/openssl-3.5.6/openssl-3.5.6.tar.gz \+ && tar -xf openssl-3.5.6.tar.gz \+ && cd openssl-3.5.6 \+ && ./Configure --prefix=/opt/openssl-pqc --openssldir=/opt/openssl-pqc/ssl no-docs \+ && make -j"$(nproc)" \+ && make install_sw \+ && cd / \+ && rm -rf /tmp/openssl-pqc-build+# ? App setup# Install smbclient for Windows SMB operationsdiff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.tsindex 00a1107eb9..63ad119b5d 100644--- a/backend/src/lib/config/env.ts+++ b/backend/src/lib/config/env.ts@@ -572,7 +572,7 @@ export const initEnvConfig = async (if (superAdminDAL) {const fipsEnabled = await crypto.initialize(superAdminDAL, hsmService, kmsRootConfigDAL);- initializePqcSupport();+ await initializePqcSupport();if (fipsEnabled) {const newEnvCfg = {diff --git a/backend/src/lib/crypto/pqc/index.ts b/backend/src/lib/crypto/pqc/index.tsindex 8601aabdcb..171125b2c2 100644--- a/backend/src/lib/crypto/pqc/index.ts+++ b/backend/src/lib/crypto/pqc/index.ts@@ -2,13 +2,19 @@ import * as x509 from "@peculiar/x509";import { registerPqcAlgorithms } from "./pqc-algorithm";import { createPqcCrypto, isPqcCryptoKey } from "./pqc-crypto";+import { verifyPqcOpenSSLAvailability } from "./pqc-openssl";export { derivePublicKeyFromSecret, isPqcCryptoKey, PqcCryptoKey } from "./pqc-crypto";export { isPqcAlgorithm } from "./pqc-utils";let pqcCryptoInstance: Crypto | null = null;-export const initializePqcSupport = () => {+export const initializePqcSupport = async () => {+ const available = await verifyPqcOpenSSLAvailability();+ if (!available) {+ return;+ }+registerPqcAlgorithms();pqcCryptoInstance = createPqcCrypto();x509.cryptoProvider.set(pqcCryptoInstance);diff --git a/backend/src/lib/crypto/pqc/pqc-crypto.test.ts b/backend/src/lib/crypto/pqc/pqc-crypto.test.tsindex 3914ff57d7..ad0ddd9018 100644--- a/backend/src/lib/crypto/pqc/pqc-crypto.test.ts+++ b/backend/src/lib/crypto/pqc/pqc-crypto.test.ts@@ -1,16 +1,23 @@import { beforeAll, describe, expect, it } from "vitest";import { createPqcCrypto, isPqcCryptoKey, PqcCryptoKey } from "./pqc-crypto";+import { verifyPqcOpenSSLAvailability } from "./pqc-openssl";+// These tests require the PQC OpenSSL 3.5+ binarydescribe("ML-DSA PQC Crypto Provider", () => {let pqcCrypto: Crypto;+ let pqcAvailable = false;- beforeAll(() => {- pqcCrypto = createPqcCrypto();+ beforeAll(async () => {+ pqcAvailable = await verifyPqcOpenSSLAvailability();+ if (pqcAvailable) {+ pqcCrypto = createPqcCrypto();+ }});describe.each(["ML-DSA-44", "ML-DSA-65", "ML-DSA-87"])("%s", (algName) => {- it("should generate a key pair", async () => {+ it("should generate a key pair", async ({ skip }) => {+ if (!pqcAvailable) skip();const keys = (await pqcCrypto.subtle.generateKey({ name: algName }, true, ["sign", "verify"])) as CryptoKeyPair;expect(keys.privateKey).toBeDefined();@@ -23,7 +30,8 @@ describe("ML-DSA PQC Crypto Provider", () => {expect(keys.publicKey.algorithm.name).toBe(algName);});- it("should sign and verify", async () => {+ it("should sign and verify", async ({ skip }) => {+ if (!pqcAvailable) skip();const keys = (await pqcCrypto.subtle.generateKey({ name: algName }, true, ["sign", "verify"])) as CryptoKeyPair;const message = new TextEncoder().encode("Hello, post-quantum world!");@@ -36,7 +44,8 @@ describe("ML-DSA PQC Crypto Provider", () => {expect(isValid).toBe(true);});- it("should fail verification with wrong message", async () => {+ it("should fail verification with wrong message", async ({ skip }) => {+ if (!pqcAvailable) skip();const keys = (await pqcCrypto.subtle.generateKey({ name: algName }, true, ["sign", "verify"])) as CryptoKeyPair;const message = new TextEncoder().encode("Original message");@@ -47,7 +56,8 @@ describe("ML-DSA PQC Crypto Provider", () => {expect(isValid).toBe(false);});- it("should export and import private key via PKCS#8 DER roundtrip", async () => {+ it("should export and import private key via PKCS#8 DER roundtrip", async ({ skip }) => {+ if (!pqcAvailable) skip();const keys = (await pqcCrypto.subtle.generateKey({ name: algName }, true, ["sign", "verify"])) as CryptoKeyPair;// Export private key as PKCS#8 DER@@ -67,7 +77,8 @@ describe("ML-DSA PQC Crypto Provider", () => {expect(isValid).toBe(true);});- it("should export and import public key via SPKI DER roundtrip", async () => {+ it("should export and import public key via SPKI DER roundtrip", async ({ skip }) => {+ if (!pqcAvailable) skip();const keys = (await pqcCrypto.subtle.generateKey({ name: algName }, true, ["sign", "verify"])) as CryptoKeyPair;// Export public key as SPKI DER@@ -87,7 +98,8 @@ describe("ML-DSA PQC Crypto Provider", () => {expect(isValid).toBe(true);});- it("should produce correct key sizes", async () => {+ it("should produce correct key sizes", async ({ skip }) => {+ if (!pqcAvailable) skip();const keys = (await pqcCrypto.subtle.generateKey({ name: algName }, true, ["sign", "verify"])) as CryptoKeyPair;const privKey = keys.privateKey as PqcCryptoKey;@@ -106,7 +118,8 @@ describe("ML-DSA PQC Crypto Provider", () => {it("should delegate classical algorithms to default subtle", async () => {// RSA key generation should still work through the provider- const keys = await pqcCrypto.subtle.generateKey(+ const crypto = createPqcCrypto();+ const keys = await crypto.subtle.generateKey({name: "RSASSA-PKCS1-v1_5",modulusLength: 2048,diff --git a/backend/src/lib/crypto/pqc/pqc-crypto.ts b/backend/src/lib/crypto/pqc/pqc-crypto.tsindex 6ff9ced46f..39b3465103 100644--- a/backend/src/lib/crypto/pqc/pqc-crypto.ts+++ b/backend/src/lib/crypto/pqc/pqc-crypto.ts@@ -1,18 +1,3 @@-import { ml_dsa44, ml_dsa65, ml_dsa87 } from "@noble/post-quantum/ml-dsa.js";-import {- slh_dsa_sha2_128f,- slh_dsa_sha2_128s,- slh_dsa_sha2_192f,- slh_dsa_sha2_192s,- slh_dsa_sha2_256f,- slh_dsa_sha2_256s,- slh_dsa_shake_128f,- slh_dsa_shake_128s,- slh_dsa_shake_192f,- slh_dsa_shake_192s,- slh_dsa_shake_256f,- slh_dsa_shake_256s-} from "@noble/post-quantum/slh-dsa.js";// eslint-disable-next-line import/no-extraneous-dependencies -- transitive deps of @peculiar/x509import { PrivateKeyInfo } from "@peculiar/asn1-pkcs8";// eslint-disable-next-line import/no-extraneous-dependencies -- transitive dep of @peculiar/x509@@ -22,39 +7,9 @@ import { AlgorithmIdentifier, SubjectPublicKeyInfo } from "@peculiar/asn1-x509";import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";+import { opensslDerivePublicKey, opensslGenpkey, opensslSign, opensslVerify } from "./pqc-openssl";import { isPqcAlgorithm, pqcNameToOid, pqcOidToName } from "./pqc-utils";-type PqcSignImpl = {- keygen: () => { publicKey: Uint8Array; secretKey: Uint8Array };- sign: (msg: Uint8Array, sk: Uint8Array) => Uint8Array;- verify: (sig: Uint8Array, msg: Uint8Array, pk: Uint8Array) => boolean;- getPublicKey: (sk: Uint8Array) => Uint8Array;-};--const PQC_IMPLS: Record<string, PqcSignImpl> = {- [CertKeyAlgorithm.ML_DSA_44]: ml_dsa44,- [CertKeyAlgorithm.ML_DSA_65]: ml_dsa65,- [CertKeyAlgorithm.ML_DSA_87]: ml_dsa87,- [CertKeyAlgorithm.SLH_DSA_SHA2_128F]: slh_dsa_sha2_128f,- [CertKeyAlgorithm.SLH_DSA_SHA2_128S]: slh_dsa_sha2_128s,- [CertKeyAlgorithm.SLH_DSA_SHA2_192F]: slh_dsa_sha2_192f,- [CertKeyAlgorithm.SLH_DSA_SHA2_192S]: slh_dsa_sha2_192s,- [CertKeyAlgorithm.SLH_DSA_SHA2_256F]: slh_dsa_sha2_256f,- [CertKeyAlgorithm.SLH_DSA_SHA2_256S]: slh_dsa_sha2_256s,- [CertKeyAlgorithm.SLH_DSA_SHAKE_128F]: slh_dsa_shake_128f,- [CertKeyAlgorithm.SLH_DSA_SHAKE_128S]: slh_dsa_shake_128s,- [CertKeyAlgorithm.SLH_DSA_SHAKE_192F]: slh_dsa_shake_192f,- [CertKeyAlgorithm.SLH_DSA_SHAKE_192S]: slh_dsa_shake_192s,- [CertKeyAlgorithm.SLH_DSA_SHAKE_256F]: slh_dsa_shake_256f,- [CertKeyAlgorithm.SLH_DSA_SHAKE_256S]: slh_dsa_shake_256s-};--const getImpl = (name: string): PqcSignImpl => {- const impl = PQC_IMPLS[name];- if (!impl) throw new Error(`Unknown PQC algorithm variant: ${name}`);- return impl;-};-const encodePkcs8 = (oid: string, rawPrivateKey: Uint8Array): Buffer => {const pkcs8 = new PrivateKeyInfo({version: 0,@@ -75,7 +30,8 @@ const encodeSpki = (oid: string, rawPublicKey: Uint8Array): Buffer => {const extractRawKeyFromPkcs8 = (der: Buffer): Buffer => {const parsed = AsnConvert.parse(der, PrivateKeyInfo);const raw = Buffer.from(parsed.privateKey.buffer);- // Handle keys stored with double OCTET STRING wrapping (legacy encoding)+ // Handle keys stored with double OCTET STRING wrapping (legacy encoding).+ // Guarded with try/catch because a raw key can naturally start with 0x04.if (raw[0] === 0x04) {try {return Buffer.from(AsnConvert.parse(raw, OctetString).buffer);@@ -125,16 +81,28 @@ class PqcCryptoKey implements CryptoKey {public readonly usages: KeyUsage[];+ // DER-encoded key bytes (PKCS#8 for private, SPKI for public)+ public readonly derKey: Buffer;+constructor(public readonly rawKey: Uint8Array,algorithmName: string,keyType: KeyType,- usages: KeyUsage[]+ usages: KeyUsage[],+ derKey?: Buffer) {this.algorithm = { name: algorithmName };this.extractable = true;this.type = keyType;this.usages = usages;++ if (derKey) {+ this.derKey = derKey;+ } else {+ const oid = pqcNameToOid(algorithmName);+ if (!oid) throw new Error(`Unknown PQC OID for ${algorithmName}`);+ this.derKey = keyType === "private" ? encodePkcs8(oid, rawKey) : encodeSpki(oid, rawKey);+ }}}@@ -183,21 +151,26 @@ const resolveAlgName = (algorithm: any): string =>// eslint-disable-next-line @typescript-eslint/no-unsafe-member-accesstypeof algorithm === "string" ? algorithm : (algorithm.name as string);-const pqcGenerateKey = (algName: string): CryptoKeyPair => {- const kp = getImpl(algName).keygen();+const pqcGenerateKey = async (algName: string): Promise<CryptoKeyPair> => {+ const privateDer = await opensslGenpkey(algName);+ const rawPrivateKey = extractRawKeyFromPkcs8(privateDer);++ const publicDer = await opensslDerivePublicKey(privateDer);+ const rawPublicKey = extractRawKeyFromSpki(publicDer);+return {- publicKey: new PqcCryptoKey(kp.publicKey, algName, "public", ["verify"]),- privateKey: new PqcCryptoKey(kp.secretKey, algName, "private", ["sign"])+ publicKey: new PqcCryptoKey(rawPublicKey, algName, "public", ["verify"], publicDer),+ privateKey: new PqcCryptoKey(rawPrivateKey, algName, "private", ["sign"], privateDer)} as CryptoKeyPair;};-const pqcSign = (key: PqcCryptoKey, data: BufferSource): ArrayBuffer => {- const sig = getImpl(key.algorithm.name).sign(toUint8Array(data), key.rawKey);+const pqcSign = async (key: PqcCryptoKey, data: BufferSource): Promise<ArrayBuffer> => {+ const sig = await opensslSign(key.derKey, Buffer.from(toUint8Array(data)));return sig.buffer.slice(sig.byteOffset, sig.byteOffset + sig.byteLength);};-const pqcVerify = (key: PqcCryptoKey, signature: BufferSource, data: BufferSource): boolean => {- return getImpl(key.algorithm.name).verify(toUint8Array(signature), toUint8Array(data), key.rawKey);+const pqcVerify = async (key: PqcCryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean> => {+ return opensslVerify(key.derKey, Buffer.from(toUint8Array(signature)), Buffer.from(toUint8Array(data)));};const pqcImportKey = (@@ -213,14 +186,14 @@ const pqcImportKey = (const rawKey = extractRawKeyFromPkcs8(derBuf);const actualAlg =detectPqcVariantFromDer(derBuf) || detectPqcVariantFromKeySize(rawKey.length, "private") || algName;- return new PqcCryptoKey(rawKey, actualAlg, "private", keyUsages);+ return new PqcCryptoKey(rawKey, actualAlg, "private", keyUsages, derBuf);}if (format === "spki" && !isPrivate) {const rawKey = extractRawKeyFromSpki(derBuf);const actualAlg =detectPqcVariantFromDer(derBuf) || detectPqcVariantFromKeySize(rawKey.length, "public") || algName;- return new PqcCryptoKey(rawKey, actualAlg, "public", keyUsages);+ return new PqcCryptoKey(rawKey, actualAlg, "public", keyUsages, derBuf);}throw new Error(`Unsupported PQC import format: ${format}`);@@ -281,16 +254,11 @@ export const createPqcCrypto = (): Crypto => {async exportKey(format: "pkcs8" | "spki" | "raw" | "jwk", key: CryptoKey) {if (isPqcCryptoKey(key)) {- const oid = pqcNameToOid(key.algorithm.name);- if (!oid) throw new Error(`Unknown PQC OID for ${key.algorithm.name}`);-if (format === "pkcs8" && key.type === "private") {- const der = encodePkcs8(oid, key.rawKey);- return der.buffer.slice(der.byteOffset, der.byteOffset + der.byteLength);+ return key.derKey.buffer.slice(key.derKey.byteOffset, key.derKey.byteOffset + key.derKey.byteLength);}if (format === "spki" && key.type === "public") {- const der = encodeSpki(oid, key.rawKey);- return der.buffer.slice(der.byteOffset, der.byteOffset + der.byteLength);+ return key.derKey.buffer.slice(key.derKey.byteOffset, key.derKey.byteOffset + key.derKey.byteLength);}throw new Error(`Unsupported PQC export: format=${format}, keyType=${key.type}`);}@@ -362,8 +330,17 @@ export const createPqcCrypto = (): Crypto => {} as Crypto;};-const derivePublicKeyFromSecret = (algName: string, secretKey: Uint8Array): Uint8Array => {- return getImpl(algName).getPublicKey(secretKey);+const derivePublicKeyFromSecret = async (+ algName: string,+ secretKey: Uint8Array+): Promise<{ raw: Uint8Array; spkiDer: Buffer }> => {+ const oid = pqcNameToOid(algName);+ if (!oid) throw new Error(`Unknown PQC algorithm: ${algName}`);++ const pkcs8Der = encodePkcs8(oid, secretKey);+ const spkiDer = await opensslDerivePublicKey(pkcs8Der);+ const raw = extractRawKeyFromSpki(spkiDer);+ return { raw, spkiDer };};export { derivePublicKeyFromSecret, isPqcCryptoKey, PqcCryptoKey };diff --git a/backend/src/lib/crypto/pqc/pqc-openssl.ts b/backend/src/lib/crypto/pqc/pqc-openssl.tsnew file mode 100644index 0000000000..aeb62df083--- /dev/null+++ b/backend/src/lib/crypto/pqc/pqc-openssl.ts@@ -0,0 +1,158 @@+import { spawn } from "child_process";+import { mkdtemp, rm, writeFile } from "fs/promises";+import { tmpdir } from "os";+import { join } from "path";++import { logger } from "@app/lib/logger";++const DEFAULT_BIN_PATH = "/opt/openssl-pqc/bin/openssl";+const DEFAULT_LIB_PATH = "/opt/openssl-pqc/lib64:/opt/openssl-pqc/lib";++let resolvedBinPath: string | null = null;+let resolvedLibPath: string | null = null;++const getPqcOpenSSLBinPath = (): string => {+ if (!resolvedBinPath) {+ resolvedBinPath = process.env.PQC_OPENSSL_BIN_PATH || DEFAULT_BIN_PATH;+ }+ return resolvedBinPath;+};++const getPqcOpenSSLLibPath = (): string => {+ if (!resolvedLibPath) {+ resolvedLibPath = process.env.PQC_OPENSSL_LIB_PATH || DEFAULT_LIB_PATH;+ }+ return resolvedLibPath;+};++const buildPqcEnv = (): NodeJS.ProcessEnv => {+ const { OPENSSL_CONF, OPENSSL_MODULES, ...rest } = process.env;+ return {+ ...rest,+ LD_LIBRARY_PATH: [getPqcOpenSSLLibPath(), process.env.LD_LIBRARY_PATH].filter(Boolean).join(":")+ };+};++const execOpenSSL = (args: string[], stdin?: Buffer): Promise<{ stdout: Buffer; stderr: string; code: number }> => {+ return new Promise((resolve, reject) => {+ const proc = spawn(getPqcOpenSSLBinPath(), args, {+ stdio: ["pipe", "pipe", "pipe"],+ env: buildPqcEnv()+ });++ const stdoutChunks: Buffer[] = [];+ const stderrChunks: Buffer[] = [];++ proc.stdout.on("data", (chunk: Buffer) => stdoutChunks.push(chunk));+ proc.stderr.on("data", (chunk: Buffer) => stderrChunks.push(chunk));++ proc.on("error", (err) => {+ reject(new Error(`Failed to spawn PQC OpenSSL at '${getPqcOpenSSLBinPath()}': ${err.message}`));+ });++ proc.on("close", (code) => {+ resolve({+ stdout: Buffer.concat(stdoutChunks),+ stderr: Buffer.concat(stderrChunks).toString(),+ code: code ?? 1+ });+ });++ if (stdin) {+ proc.stdin.write(stdin);+ }+ proc.stdin.end();+ });+};++const execOpenSSLOrThrow = async (args: string[], stdin?: Buffer): Promise<Buffer> => {+ const { stdout, stderr, code } = await execOpenSSL(args, stdin);+ if (code !== 0) {+ throw new Error(`PQC OpenSSL command failed (exit ${code}): ${stderr}`);+ }+ return stdout;+};++const withTempDir = async <T>(fn: (dir: string) => Promise<T>): Promise<T> => {+ const dir = await mkdtemp(join(tmpdir(), "pqc-"));+ try {+ return await fn(dir);+ } finally {+ await rm(dir, { recursive: true, force: true }).catch(() => {});+ }+};++export const opensslGenpkey = async (algorithm: string): Promise<Buffer> => {+ return execOpenSSLOrThrow(["genpkey", "-algorithm", algorithm, "-outform", "DER"]);+};++export const opensslDerivePublicKey = async (privateDer: Buffer): Promise<Buffer> => {+ return withTempDir(async (dir) => {+ const keyPath = join(dir, "key.der");+ await writeFile(keyPath, privateDer, { mode: 0o600 });+ return execOpenSSLOrThrow(["pkey", "-in", keyPath, "-inform", "DER", "-outform", "DER", "-pubout"]);+ });+};++export const opensslSign = async (privateDer: Buffer, data: Buffer): Promise<Buffer> => {+ return withTempDir(async (dir) => {+ const keyPath = join(dir, "key.der");+ const dataPath = join(dir, "data.bin");+ await Promise.all([writeFile(keyPath, privateDer, { mode: 0o600 }), writeFile(dataPath, data, { mode: 0o600 })]);+ return execOpenSSLOrThrow(["pkeyutl", "-sign", "-inkey", keyPath, "-keyform", "DER", "-in", dataPath]);+ });+};++export const opensslVerify = async (publicDer: Buffer, signature: Buffer, data: Buffer): Promise<boolean> => {+ return withTempDir(async (dir) => {+ const keyPath = join(dir, "pub.der");+ const sigPath = join(dir, "sig.bin");+ const dataPath = join(dir, "data.bin");+ await Promise.all([+ writeFile(keyPath, publicDer, { mode: 0o600 }),+ writeFile(sigPath, signature, { mode: 0o600 }),+ writeFile(dataPath, data, { mode: 0o600 })+ ]);+ const { code } = await execOpenSSL([+ "pkeyutl",+ "-verify",+ "-pubin",+ "-inkey",+ keyPath,+ "-keyform",+ "DER",+ "-sigfile",+ sigPath,+ "-in",+ dataPath+ ]);+ return code === 0;+ });+};++export const verifyPqcOpenSSLAvailability = async (): Promise<boolean> => {+ try {+ const { stdout, code } = await execOpenSSL(["version"]);+ if (code !== 0) {+ logger?.warn(+ "PQC OpenSSL binary not found or failed to execute. PQC certificate operations will not be available."+ );+ return false;+ }++ const version = stdout.toString().trim();+ logger?.info(`PQC OpenSSL detected: ${version}`);++ // Quick check: try to generate a throwaway ML-DSA-44 key (smallest/fastest variant)+ const { code: genCode } = await execOpenSSL(["genpkey", "-algorithm", "ML-DSA-44", "-outform", "DER"]);+ if (genCode !== 0) {+ logger?.warn(`PQC OpenSSL (${version}) does not support ML-DSA. PQC operations will not be available.`);+ return false;+ }++ return true;+ } catch {+ logger?.warn("PQC OpenSSL binary not available. PQC certificate operations will not be available.");+ return false;+ }+};diff --git a/backend/src/lib/crypto/pqc/pqc-x509.test.ts b/backend/src/lib/crypto/pqc/pqc-x509.test.tsindex 7edb0482f8..9ba27ef342 100644--- a/backend/src/lib/crypto/pqc/pqc-x509.test.ts+++ b/backend/src/lib/crypto/pqc/pqc-x509.test.ts@@ -3,13 +3,21 @@ import * as x509 from "@peculiar/x509";import { beforeAll, describe, expect, it } from "vitest";import { getPqcCrypto, initializePqcSupport } from "./index";+import { verifyPqcOpenSSLAvailability } from "./pqc-openssl";+// These tests require the PQC OpenSSL 3.5+ binarydescribe("ML-DSA X.509 Certificate Operations", () => {- beforeAll(() => {- initializePqcSupport();+ let pqcAvailable = false;++ beforeAll(async () => {+ pqcAvailable = await verifyPqcOpenSSLAvailability();+ if (pqcAvailable) {+ await initializePqcSupport();+ }});- it("should create and verify self-signed cert directly", async () => {+ it("should create and verify self-signed cert directly", async ({ skip }) => {+ if (!pqcAvailable) skip();const pqcCrypto = getPqcCrypto();const alg = { name: "ML-DSA-87" };const keys = (await pqcCrypto.subtle.generateKey(alg, true, ["sign", "verify"])) as CryptoKeyPair;@@ -43,7 +51,8 @@ describe("ML-DSA X.509 Certificate Operations", () => {expect(isSelfSigned).toBe(true);});- it("should create a self-signed root CA cert with ML-DSA-87", async () => {+ it("should create a self-signed root CA cert with ML-DSA-87", async ({ skip }) => {+ if (!pqcAvailable) skip();const pqcCrypto = getPqcCrypto();const alg = { name: "ML-DSA-87" };const keys = (await pqcCrypto.subtle.generateKey(alg, true, ["sign", "verify"])) as CryptoKeyPair;@@ -68,7 +77,8 @@ describe("ML-DSA X.509 Certificate Operations", () => {expect(pem).toContain("-----BEGIN CERTIFICATE-----");});- it("should sign an intermediate CA cert with an ML-DSA-87 root", async () => {+ it("should sign an intermediate CA cert with an ML-DSA-87 root", async ({ skip }) => {+ if (!pqcAvailable) skip();const pqcCrypto = getPqcCrypto();const alg = { name: "ML-DSA-87" };@@ -143,7 +153,8 @@ describe("ML-DSA X.509 Certificate Operations", () => {expect(chainItems.length).toBe(2); // intermediate + root});- it("should sign an ML-DSA-65 intermediate cert with an ML-DSA-87 root", async () => {+ it("should sign an ML-DSA-65 intermediate cert with an ML-DSA-87 root", async ({ skip }) => {+ if (!pqcAvailable) skip();const pqcCrypto = getPqcCrypto();// ML-DSA-87 rootdiff --git a/backend/src/services/certificate-authority/certificate-authority-fns.ts b/backend/src/services/certificate-authority/certificate-authority-fns.tsindex 37fdaf6cd5..9c6c4ce792 100644--- a/backend/src/services/certificate-authority/certificate-authority-fns.ts+++ b/backend/src/services/certificate-authority/certificate-authority-fns.ts@@ -308,11 +308,11 @@ export const getCaCredentials = async ({const caKeyAlg = keyAlgorithmToAlgCfg(ca.internalCa.keyAlgorithm as CertKeyAlgorithm);const pqcCrypto = getPqcCrypto();const caPrivateKey = await pqcCrypto.subtle.importKey("pkcs8", decryptedPrivateKey, caKeyAlg, true, ["sign"]);- const pubKeyRaw = derivePublicKeyFromSecret(+ const { raw: pubKeyRaw, spkiDer } = await derivePublicKeyFromSecret(ca.internalCa.keyAlgorithm,(caPrivateKey as InstanceType<typeof PqcCryptoKey>).rawKey);- const caPublicKey = new PqcCryptoKey(pubKeyRaw, ca.internalCa.keyAlgorithm, "public", ["verify"]);+ const caPublicKey = new PqcCryptoKey(pubKeyRaw, ca.internalCa.keyAlgorithm, "public", ["verify"], spkiDer);return { caSecret, caPrivateKey, caPublicKey };}diff --git a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.tsindex 3594eb999c..570da52b55 100644--- a/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts+++ b/backend/src/services/certificate-authority/internal/internal-certificate-authority-service.ts@@ -163,11 +163,17 @@ export const internalCertificateAuthorityServiceFactory = ({? "SLH-DSA": "unknown";- const isRequestValid =- (requestedKeyType === "RSA" && isRsaCa) ||- (requestedKeyType === "ECDSA" && isEcdsaCa) ||- (requestedKeyType === "ML-DSA" && isMlDsaCa) ||- (requestedKeyType === "SLH-DSA" && isSlhDsaCa);+ // PQC: exact variant match required (ML-DSA-44 CA can only sign with ML-DSA-44)+ if ((isMlDsaCa || isSlhDsaCa) && signatureAlgorithm) {+ if (signatureAlgorithm !== caKeyAlg) {+ throw new BadRequestError({+ message: `Requested signature algorithm ${signatureAlgorithm} does not match CA key algorithm ${caKeyAlg}. PQC CAs require an exact algorithm match.`+ });+ }+ return;+ }++ const isRequestValid = (requestedKeyType === "RSA" && isRsaCa) || (requestedKeyType === "ECDSA" && isEcdsaCa);if (!isRequestValid) {throw new BadRequestError({@@ -1486,8 +1492,11 @@ export const internalCertificateAuthorityServiceFactory = ({"sign"]);- const pubRaw = derivePublicKeyFromSecret(caKeyAlg, (privateKey as InstanceType<typeof PqcCryptoKey>).rawKey);- publicKey = new PqcCryptoKey(pubRaw, caKeyAlg, "public", ["verify"]);+ const { raw: pubRaw, spkiDer } = await derivePublicKeyFromSecret(+ caKeyAlg,+ (privateKey as InstanceType<typeof PqcCryptoKey>).rawKey+ );+ publicKey = new PqcCryptoKey(pubRaw, caKeyAlg, "public", ["verify"], spkiDer);} else {const skObj = crypto.nativeCrypto.createPrivateKey({ key: caPrivateKey, format: "der", type: "pkcs8" });const pkObj = crypto.nativeCrypto.createPublicKey(skObj);@@ -2575,11 +2584,11 @@ export const internalCertificateAuthorityServiceFactory = ({"sign"]);- const pubKeyRaw = derivePublicKeyFromSecret(+ const { raw: pubKeyRaw, spkiDer } = await derivePublicKeyFromSecret(rootKeyAlg,(actualPrivateKey as InstanceType<typeof PqcCryptoKey>).rawKey);- actualPublicKey = new PqcCryptoKey(pubKeyRaw, rootKeyAlg, "public", ["verify"]);+ actualPublicKey = new PqcCryptoKey(pubKeyRaw, rootKeyAlg, "public", ["verify"], spkiDer);} else {const skObj = crypto.nativeCrypto.createPrivateKey({ key: privateKeyBlob, format: "der", type: "pkcs8" });const pkObj = crypto.nativeCrypto.createPublicKey(skObj);