Skip to content

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

improvement(pki): refuse an expensive keystore up front instead of timing it out

Saifc97fc36ce748
diff --git a/backend/src/services/certificate/certificate-pkcs12-fns.test.ts b/backend/src/services/certificate/certificate-pkcs12-fns.test.ts
index eb502c8b7f..66c1504458 100644
--- a/backend/src/services/certificate/certificate-pkcs12-fns.test.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-fns.test.ts
@@ -200,6 +200,10 @@ describe("extractPkcs12Entries failures", () => {
await expectFailure(fixtures.noMac, "not-the-password", Pkcs12ErrorCode.BadPassword);
});
+ test("refuses a keystore that declares an absurd key-derivation cost", async () => {
+ await expectFailure(fixtures.hostileIterations, "test", Pkcs12ErrorCode.TooExpensive);
+ });
+
test("reports a file that is not a keystore", async () => {
await expectFailure(Buffer.from("this is not a keystore").toString("base64"), "test", Pkcs12ErrorCode.NotAKeystore);
});
diff --git a/backend/src/services/certificate/certificate-pkcs12-fns.ts b/backend/src/services/certificate/certificate-pkcs12-fns.ts
index d507eb2a06..53f5268d03 100644
--- a/backend/src/services/certificate/certificate-pkcs12-fns.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-fns.ts
@@ -11,6 +11,7 @@ export const Pkcs12ErrorCode = {
BadPassword: "bad_password",
UnsupportedEntries: "unsupported_entries",
TooManyBags: "too_many_bags",
+ TooExpensive: "too_expensive",
NoEntries: "no_entries",
NoPairs: "no_pairs"
} as const;
@@ -49,7 +50,7 @@ export type TExtractPkcs12Result = {
entries: TPkcs12Entry[];
};
-const MAX_KEY_BAGS = 20;
+const MAX_KEY_BAGS = 8;
const MAX_CERT_BAGS = 100;
const MAX_CHAIN_DEPTH = 10;
@@ -261,6 +262,61 @@ const buildChain = async (leaf: TParsedCert, certs: TParsedCert[]) => {
return { chain, truncated };
};
+// A keystore states its own key-derivation cost in the clear, so an expensive one is refused before
+// any decryption happens rather than by running out of time. PBKDF2 and the PKCS#12 PBE algorithms
+// all carry the count as the first integer of their parameters.
+const ITERATION_PARAM_OIDS = new Set([
+ "1.2.840.113549.1.5.12",
+ "1.2.840.113549.1.12.1.1",
+ "1.2.840.113549.1.12.1.2",
+ "1.2.840.113549.1.12.1.3",
+ "1.2.840.113549.1.12.1.4",
+ "1.2.840.113549.1.12.1.5",
+ "1.2.840.113549.1.12.1.6"
+]);
+
+const MAX_KDF_ITERATIONS = 1_000_000;
+
+const asn1Integer = (node: forge.asn1.Asn1) => {
+ if (typeof node.value !== "string") return 0;
+ try {
+ return forge.asn1.derToInteger(node.value);
+ } catch {
+ // Wider than an iteration count ever is, so it is not one.
+ return 0;
+ }
+};
+
+const declaredIterations = (node: forge.asn1.Asn1): number => {
+ if (!Array.isArray(node.value)) return 0;
+ const children = node.value;
+ let max = 0;
+
+ const [first, second, third] = children;
+ if (first?.type === forge.asn1.Type.OID && typeof first.value === "string" && Array.isArray(second?.value)) {
+ if (ITERATION_PARAM_OIDS.has(forge.asn1.derToOid(first.value))) {
+ const count = second.value.find((param) => param.type === forge.asn1.Type.INTEGER);
+ if (count) max = Math.max(max, asn1Integer(count));
+ }
+ }
+
+ // MacData: the digest, its salt, then the count.
+ if (
+ children.length === 3 &&
+ Array.isArray(first?.value) &&
+ second?.type === forge.asn1.Type.OCTETSTRING &&
+ third?.type === forge.asn1.Type.INTEGER
+ ) {
+ max = Math.max(max, asn1Integer(third));
+ }
+
+ children.forEach((child) => {
+ max = Math.max(max, declaredIterations(child));
+ });
+
+ return max;
+};
+
export const extractPkcs12Entries = async ({
pkcs12,
password
@@ -275,6 +331,10 @@ export const extractPkcs12Entries = async ({
throw new Pkcs12ExtractionError(Pkcs12ErrorCode.NotAKeystore);
}
+ if (declaredIterations(asn1) > MAX_KDF_ITERATIONS) {
+ throw new Pkcs12ExtractionError(Pkcs12ErrorCode.TooExpensive);
+ }
+
let p12: forge.pkcs12.Pkcs12Pfx;
try {
p12 = forge.pkcs12.pkcs12FromAsn1(asn1, password);
diff --git a/backend/src/services/certificate/certificate-pkcs12-runner.test.ts b/backend/src/services/certificate/certificate-pkcs12-runner.test.ts
index 3c738d741e..bafe32384e 100644
--- a/backend/src/services/certificate/certificate-pkcs12-runner.test.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-runner.test.ts
@@ -13,13 +13,13 @@ describe("runPkcs12Extraction", () => {
expect(entries).toHaveLength(2);
});
- test("gives up on a keystore built to be expensive to open", async () => {
+ test("refuses a keystore built to be expensive to open, without decrypting it", async () => {
// 2.6KB with five million key-derivation rounds, which parsed inline blocks the event loop for
- // over a minute.
+ // over a minute. The count is read from the file, so this costs nothing.
const started = Date.now();
- await expect(run(fixtures.hostileIterations, "test")).rejects.toThrow(/takes too long to open/);
+ await expect(run(fixtures.hostileIterations, "test")).rejects.toThrow(/key-derivation rounds/);
- expect(Date.now() - started).toBeLessThan(6_000);
+ expect(Date.now() - started).toBeLessThan(3_000);
}, 15_000);
});
diff --git a/backend/src/services/certificate/certificate-pkcs12-runner.ts b/backend/src/services/certificate/certificate-pkcs12-runner.ts
index 7d347fcac6..23de368e0f 100644
--- a/backend/src/services/certificate/certificate-pkcs12-runner.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-runner.ts
@@ -6,39 +6,24 @@ import { logger } from "@app/lib/logger";
import { Pkcs12ErrorCode, TExtractPkcs12Result, TPkcs12ErrorCode } from "./certificate-pkcs12-fns";
-// The uploaded file picks its own decryption cost through its key-derivation round count, and
-// node-forge decrypts synchronously, so extraction runs in a worker under a wall clock. Only
-// decryption gets the tight budget: charging thread startup to the file failed ordinary keystores.
-const DECRYPTION_TIMEOUT_MS = 3_000;
-const STARTUP_TIMEOUT_MS = 30_000;
+// Cost is refused up front by the extraction itself, so this is only a backstop for anything that
+// check cannot see, and node-forge decrypts synchronously so it has to run off the event loop.
+const EXTRACTION_TIMEOUT_MS = 15_000;
const MAX_CONCURRENT_EXTRACTIONS = 2;
-// Each waiter holds its keystore in memory for the whole wait.
-const MAX_QUEUED_EXTRACTIONS = 8;
let inFlight = 0;
-const waiting: (() => void)[] = [];
-const acquireSlot = async () => {
- if (inFlight < MAX_CONCURRENT_EXTRACTIONS) {
- inFlight += 1;
- return;
- }
-
- if (waiting.length >= MAX_QUEUED_EXTRACTIONS) {
+const acquireSlot = () => {
+ if (inFlight >= MAX_CONCURRENT_EXTRACTIONS) {
throw new BadRequestError({
message: "Too many keystores are being read right now. Try again in a moment."
});
}
-
- await new Promise<void>((resolve) => {
- waiting.push(resolve);
- });
inFlight += 1;
};
const releaseSlot = () => {
inFlight -= 1;
- waiting.shift()?.();
};
// Dev runs the TypeScript sources, production the ESM build; anchor on this module's own extension.
@@ -51,7 +36,6 @@ const extractionModulePath = path.join(__dirname, `certificate-pkcs12-fns${modul
const workerExecArgv = isRunningFromSource ? ["--no-warnings"] : undefined;
type TWorkerResponse =
- | { ready: true }
| { ok: true; result: TExtractPkcs12Result }
| { ok: false; code?: TPkcs12ErrorCode; count?: number; unexpected?: string };
@@ -65,6 +49,8 @@ const errorMessage = (code: TPkcs12ErrorCode, count?: number) => {
return `This keystore contains ${count ?? "too many"} entries, which is more than we can import at once.`;
case Pkcs12ErrorCode.NoEntries:
return "This keystore contains no certificates or private keys.";
+ case Pkcs12ErrorCode.TooExpensive:
+ return "This keystore asks for an unusually high number of key-derivation rounds, so we will not open it.";
case Pkcs12ErrorCode.NoPairs:
return `This keystore contains ${count ?? "some"} private key${count === 1 ? "" : "s"}, but none of them match a certificate in the file.`;
case Pkcs12ErrorCode.BadPassword:
@@ -80,7 +66,7 @@ export const runPkcs12Extraction = async ({
pkcs12: Buffer;
password: string;
}): Promise<TExtractPkcs12Result> => {
- await acquireSlot();
+ acquireSlot();
try {
return await new Promise<TExtractPkcs12Result>((resolve, reject) => {
@@ -90,31 +76,21 @@ export const runPkcs12Extraction = async ({
});
let settled = false;
- let timer: NodeJS.Timeout | undefined;
+ let timer: NodeJS.Timeout;
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
- if (timer) clearTimeout(timer);
+ clearTimeout(timer);
void worker.terminate();
fn();
};
- const startClock = (ms: number, message: string) => {
- if (timer) clearTimeout(timer);
- timer = setTimeout(() => finish(() => reject(new BadRequestError({ message }))), ms);
- };
-
- startClock(STARTUP_TIMEOUT_MS, "Could not read this keystore.");
+ timer = setTimeout(
+ () => finish(() => reject(new BadRequestError({ message: "Could not read this keystore." }))),
+ EXTRACTION_TIMEOUT_MS
+ );
worker.on("message", (message: TWorkerResponse) => {
- if ("ready" in message) {
- startClock(
- DECRYPTION_TIMEOUT_MS,
- "This keystore takes too long to open. It may use an unusually high number of key-derivation rounds."
- );
- return;
- }
-
finish(() => {
if (message.ok) {
resolve(message.result);
diff --git a/backend/src/services/certificate/certificate-pkcs12-worker.ts b/backend/src/services/certificate/certificate-pkcs12-worker.ts
index 3514199f9a..4bbaa45b1e 100644
--- a/backend/src/services/certificate/certificate-pkcs12-worker.ts
+++ b/backend/src/services/certificate/certificate-pkcs12-worker.ts
@@ -17,9 +17,6 @@ type TExtractionModule = {
const run = async () => {
const mod = (await import(modulePath)) as TExtractionModule;
- // Starts the parent's decryption clock, so thread startup is not charged to the file.
- parentPort?.postMessage({ ready: true });
-
try {
const result = await mod.extractPkcs12Entries({ pkcs12: Buffer.from(pkcs12, "base64"), password });
parentPort?.postMessage({ ok: true, result });