Skip to content

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

Enforce RFC 5280 on chain validation

Thiago Araujo da Silvad2de4ab8e5d8
diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.test.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.test.ts
index cc8030ea53..4d58a1193d 100644
--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.test.ts
+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.test.ts
@@ -1,6 +1,7 @@
import crypto from "node:crypto";
import * as x509 from "@peculiar/x509";
+import { GeneralName, GeneralSubtree, NameConstraints } from "pkijs";
import { beforeAll, describe, expect, test } from "vitest";
import {
@@ -270,10 +271,14 @@ describe("verifyClientCertificateChain", () => {
return { cert, keys };
};
- const makeIntermediate = async (name: string, issuer: TIssued, opts?: { notAfter?: Date }): Promise<TIssued> => {
+ const makeIntermediate = async (
+ name: string,
+ issuer: TIssued,
+ opts?: { notAfter?: Date; serialNumber?: string; pathLength?: number; extraExtensions?: x509.Extension[] }
+ ): Promise<TIssued> => {
const keys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
const cert = await x509.X509CertificateGenerator.create({
- serialNumber: "02",
+ serialNumber: opts?.serialNumber ?? "02",
subject: `CN=${name}`,
issuer: issuer.cert.subject,
notBefore: NOT_BEFORE,
@@ -281,12 +286,29 @@ describe("verifyClientCertificateChain", () => {
signingKey: issuer.keys.privateKey,
publicKey: keys.publicKey,
signingAlgorithm: alg,
- extensions: [new x509.BasicConstraintsExtension(true, undefined, true)]
+ extensions: [new x509.BasicConstraintsExtension(true, opts?.pathLength, true), ...(opts?.extraExtensions ?? [])]
});
return { cert, keys };
};
- const makeLeaf = async (name: string, issuer: TIssued, opts?: { notBefore?: Date; notAfter?: Date }) => {
+ const permittedDnsConstraint = (permitted: string[]) =>
+ new x509.Extension(
+ "2.5.29.30",
+ true,
+ new NameConstraints({
+ permittedSubtrees: permitted.map(
+ (dns) => new GeneralSubtree({ base: new GeneralName({ type: 2, value: dns }) })
+ )
+ })
+ .toSchema()
+ .toBER(false)
+ );
+
+ const makeLeaf = async (
+ name: string,
+ issuer: TIssued,
+ opts?: { notBefore?: Date; notAfter?: Date; dnsName?: string }
+ ) => {
const keys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
const cert = await x509.X509CertificateGenerator.create({
serialNumber: "03",
@@ -297,7 +319,10 @@ describe("verifyClientCertificateChain", () => {
signingKey: issuer.keys.privateKey,
publicKey: keys.publicKey,
signingAlgorithm: alg,
- extensions: [new x509.BasicConstraintsExtension(false)]
+ extensions: [
+ new x509.BasicConstraintsExtension(false),
+ ...(opts?.dnsName ? [new x509.SubjectAlternativeNameExtension([{ type: "dns", value: opts.dnsName }])] : [])
+ ]
});
return { cert, keys };
};
@@ -314,7 +339,7 @@ describe("verifyClientCertificateChain", () => {
test("accepts a leaf whose presented intermediate chains to the configured root", async () => {
const leaf = await makeLeaf("workload", intermediate);
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [toNative(intermediate.cert)],
trustAnchor: toNative(root.cert),
@@ -325,7 +350,7 @@ describe("verifyClientCertificateChain", () => {
test("accepts a leaf issued directly by the configured anchor (single intermediate as anchor)", async () => {
const leaf = await makeLeaf("workload", intermediate);
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [],
trustAnchor: toNative(intermediate.cert),
@@ -336,7 +361,7 @@ describe("verifyClientCertificateChain", () => {
test("rejects when the intermediate is missing (cannot reach the anchor)", async () => {
const leaf = await makeLeaf("workload", intermediate);
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [],
trustAnchor: toNative(root.cert),
@@ -347,7 +372,7 @@ describe("verifyClientCertificateChain", () => {
test("rejects a chain that does not lead to the configured anchor", async () => {
const leaf = await makeLeaf("workload", intermediate);
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [toNative(intermediate.cert)],
trustAnchor: toNative(otherRoot.cert),
@@ -359,7 +384,7 @@ describe("verifyClientCertificateChain", () => {
test("ignores an unrelated forged intermediate presented alongside the valid one", async () => {
const forged = await makeIntermediate("Forged Intermediate", otherRoot);
const leaf = await makeLeaf("workload", intermediate);
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [toNative(forged.cert), toNative(intermediate.cert)],
trustAnchor: toNative(root.cert),
@@ -368,40 +393,87 @@ describe("verifyClientCertificateChain", () => {
expect(result).toEqual({ ok: true });
});
- test("does not re-explore shared dead-end issuer paths", () => {
- let verificationCount = 0;
- const validFrom = NOT_BEFORE.toString();
- const validTo = FAR_FUTURE.toString();
- const toMockNative = (id: string, subject: string, issuer: string, ca: boolean) =>
- ({
- raw: Buffer.from(id),
+ test("does not re-explore shared dead-end issuer paths", async () => {
+ // Every maze certificate carries and is signed by one shared key, so any certificate at a level
+ // verifies against any certificate at the level above it. That is what creates the
+ // combinatorial path explosion the walk cache exists to bound.
+ const mazeKeys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
+ const anchorKeys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
+
+ let serial = 0x100;
+ const mazeCert = async (subject: string, issuer: string, signingKey: CryptoKey, publicKey: CryptoKey) => {
+ serial += 1;
+ return x509.X509CertificateGenerator.create({
+ serialNumber: serial.toString(16),
subject,
issuer,
- ca,
- validFrom,
- validTo,
- publicKey: id,
- verify: () => {
+ notBefore: NOT_BEFORE,
+ notAfter: FAR_FUTURE,
+ signingKey,
+ publicKey,
+ signingAlgorithm: alg,
+ extensions: [new x509.BasicConstraintsExtension(true, undefined, true)]
+ });
+ };
+
+ let verificationCount = 0;
+ const counted = (cert: x509.X509Certificate) => {
+ const native = toNative(cert);
+ return {
+ raw: native.raw,
+ subject: native.subject,
+ issuer: native.issuer,
+ ca: native.ca,
+ validFrom: native.validFrom,
+ validTo: native.validTo,
+ publicKey: native.publicKey,
+ verify: (key: Parameters<typeof native.verify>[0]) => {
verificationCount += 1;
- return true;
+ return native.verify(key);
}
- }) as unknown as InstanceType<typeof crypto.X509Certificate>;
+ } as unknown as InstanceType<typeof crypto.X509Certificate>;
+ };
const width = 4;
const levels = 4;
- const deadEndChain = Array.from({ length: levels }, (__, level) =>
- Array.from({ length: width }, (_, index) =>
- toMockNative(`dead-${level}-${index}`, `CN=level-${level}`, `CN=level-${level + 1}`, true)
+ const deadEnds = await Promise.all(
+ Array.from({ length: levels }, (__, level) =>
+ Promise.all(
+ Array.from({ length: width }, () =>
+ mazeCert(`CN=level-${level}`, `CN=level-${level + 1}`, mazeKeys.privateKey, mazeKeys.publicKey)
+ )
+ )
)
);
- const leaf = toMockNative("leaf", "CN=leaf", "CN=level-0", false);
- const successfulIssuer = toMockNative("success", "CN=level-0", "CN=anchor", true);
- const trustAnchor = toMockNative("anchor", "CN=anchor", "CN=anchor", true);
-
- const result = verifyClientCertificateChain({
- leaf,
- presentedChain: [...deadEndChain.flat(), successfulIssuer],
- trustAnchor,
+
+ const anchor = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "0f",
+ name: "CN=anchor",
+ notBefore: NOT_BEFORE,
+ notAfter: FAR_FUTURE,
+ keys: anchorKeys,
+ extensions: [new x509.BasicConstraintsExtension(true, undefined, true)]
+ });
+ // Shares the maze public key, so the leaf verifies against it as well as against every dead end.
+ const successfulIssuer = await mazeCert("CN=level-0", "CN=anchor", anchorKeys.privateKey, mazeKeys.publicKey);
+
+ const leafKeys = await crypto.webcrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
+ const leaf = await x509.X509CertificateGenerator.create({
+ serialNumber: "0e",
+ subject: "CN=leaf",
+ issuer: "CN=level-0",
+ notBefore: NOT_BEFORE,
+ notAfter: FAR_FUTURE,
+ signingKey: mazeKeys.privateKey,
+ publicKey: leafKeys.publicKey,
+ signingAlgorithm: alg,
+ extensions: [new x509.BasicConstraintsExtension(false)]
+ });
+
+ const result = await verifyClientCertificateChain({
+ leaf: counted(leaf),
+ presentedChain: [...deadEnds.flat(), successfulIssuer].map(counted),
+ trustAnchor: counted(anchor),
now: NOW
});
@@ -414,7 +486,7 @@ describe("verifyClientCertificateChain", () => {
notBefore: NOT_BEFORE,
notAfter: new Date("2026-06-10T00:00:00Z")
});
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [toNative(intermediate.cert)],
trustAnchor: toNative(root.cert),
@@ -428,7 +500,7 @@ describe("verifyClientCertificateChain", () => {
notBefore: new Date("2026-07-01T00:00:00Z"),
notAfter: FAR_FUTURE
});
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [toNative(intermediate.cert)],
trustAnchor: toNative(root.cert),
@@ -451,7 +523,7 @@ describe("verifyClientCertificateChain", () => {
extensions: [new x509.BasicConstraintsExtension(false)]
});
const leaf = await makeLeaf("workload", { cert: nonCaAnchor, keys: nonCaAnchorKeys });
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [],
trustAnchor: toNative(nonCaAnchor),
@@ -460,12 +532,90 @@ describe("verifyClientCertificateChain", () => {
expect(result).toEqual({ ok: false, reasonCode: "ca_verification_failed" });
});
+ test("rejects a leaf minted outside the permitted namespace of its issuing CA", async () => {
+ // The delegated sub-CA is constrained to team-a, but mints a leaf naming a workload it was
+ // never authorised to certify. Without name constraint enforcement the holder of any
+ // constrained sub-CA under the pinned anchor could impersonate any identity on that anchor.
+ const constrained = await makeIntermediate("Constrained Intermediate CA", root, {
+ serialNumber: "20",
+ extraExtensions: [permittedDnsConstraint(["team-a.example.com"])]
+ });
+ const leaf = await makeLeaf("victim.example.com", constrained, { dnsName: "victim.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(constrained.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+
+ test("accepts a leaf inside the permitted namespace of its issuing CA", async () => {
+ const constrained = await makeIntermediate("Constrained Intermediate CA", root, {
+ serialNumber: "21",
+ extraExtensions: [permittedDnsConstraint(["team-a.example.com"])]
+ });
+ const leaf = await makeLeaf("team-a.example.com", constrained, { dnsName: "team-a.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(constrained.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: true });
+ });
+
+ test("enforces name constraints carried by the configured anchor itself", async () => {
+ const constrained = await makeIntermediate("Constrained Anchor CA", root, {
+ serialNumber: "22",
+ extraExtensions: [permittedDnsConstraint(["team-a.example.com"])]
+ });
+ const leaf = await makeLeaf("victim.example.com", constrained, { dnsName: "victim.example.com" });
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [],
+ trustAnchor: toNative(constrained.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "name_constraint_violation" });
+ });
+
+ test("rejects a chain deeper than a CA's pathLenConstraint permits", async () => {
+ const limited = await makeIntermediate("PathLen Zero CA", root, { serialNumber: "30", pathLength: 0 });
+ const extra = await makeIntermediate("Extra Intermediate CA", limited, { serialNumber: "31" });
+ const leaf = await makeLeaf("workload", extra);
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(limited.cert), toNative(extra.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: false, reasonCode: "path_length_exceeded" });
+ });
+
+ test("accepts a leaf issued directly by a pathLen:0 CA", async () => {
+ const limited = await makeIntermediate("PathLen Zero CA", root, { serialNumber: "32", pathLength: 0 });
+ const leaf = await makeLeaf("workload", limited);
+
+ const result = await verifyClientCertificateChain({
+ leaf: toNative(leaf.cert),
+ presentedChain: [toNative(limited.cert)],
+ trustAnchor: toNative(root.cert),
+ now: NOW
+ });
+ expect(result).toEqual({ ok: true });
+ });
+
test("rejects when the intermediate has expired", async () => {
const expiredIntermediate = await makeIntermediate("Expired Intermediate", root, {
notAfter: new Date("2026-06-10T00:00:00Z")
});
const leaf = await makeLeaf("workload", expiredIntermediate);
- const result = verifyClientCertificateChain({
+ const result = await verifyClientCertificateChain({
leaf: toNative(leaf.cert),
presentedChain: [toNative(expiredIntermediate.cert)],
trustAnchor: toNative(root.cert),
diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.ts
index 0168542bd1..561a35bad5 100644
--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.ts
+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-fns.ts
@@ -1,14 +1,110 @@
+import { webcrypto } from "node:crypto";
+
+import * as x509 from "@peculiar/x509";
+import { Certificate, CertificateChainValidationEngine, CryptoEngine, NameConstraints } from "pkijs";
+
import { crypto } from "@app/lib/crypto/cryptography";
type TNativeX509 = InstanceType<typeof crypto.nativeCrypto.X509Certificate>;
export type TVerifyClientCertificateChainResult =
| { ok: true }
- | { ok: false; reasonCode: "ca_verification_failed" | "certificate_expired" | "certificate_not_yet_valid" };
+ | {
+ ok: false;
+ reasonCode:
+ | "ca_verification_failed"
+ | "certificate_expired"
+ | "certificate_not_yet_valid"
+ | "name_constraint_violation"
+ | "path_length_exceeded";
+ };
+
+type TVerificationFailure = Extract<TVerifyClientCertificateChainResult, { ok: false }>;
+
+const NAME_CONSTRAINTS_EXTENSION_OID = "2.5.29.30";
+
+const PERMITTED_SUBTREE_VIOLATION_CODE = 41;
+const EXCLUDED_SUBTREE_VIOLATION_CODE = 42;
+
+const pkiCryptoEngine = new CryptoEngine({ name: "identity-tls-cert-auth", crypto: webcrypto as Crypto });
const isWithinValidityWindow = (cert: TNativeX509, at: Date): boolean =>
new Date(cert.validFrom) <= at && at <= new Date(cert.validTo);
+const isSelfIssued = (cert: TNativeX509): boolean => cert.subject === cert.issuer;
+
+const basicConstraintsPathLength = (cert: TNativeX509): number | undefined =>
+ new x509.X509Certificate(cert.raw).getExtension(x509.BasicConstraintsExtension)?.pathLength;
+
+/**
+ * RFC 5280 6.1.4 (l)/(m): a CA's `pathLenConstraint` caps how many non-self-issued CA certificates
+ * may follow it on the path, not counting the end-entity certificate. A CA that omits the field is
+ * unconstrained.
+ *
+ * @param orderedPath leaf first, then each issuer in turn, trust anchor last
+ */
+const enforcePathLength = (orderedPath: TNativeX509[]): TVerificationFailure | null => {
+ const issuers = orderedPath.slice(1);
+
+ const exceeded = issuers.some((issuer, idx) => {
+ const pathLength = basicConstraintsPathLength(issuer);
+ if (pathLength === undefined) return false;
+ return issuers.slice(0, idx).filter((below) => !isSelfIssued(below)).length > pathLength;
+ });
+
+ return exceeded ? { ok: false, reasonCode: "path_length_exceeded" } : null;
+};
+
+const nameConstraintsOf = (cert: Certificate): NameConstraints | null => {
+ const extension = cert.extensions?.find((ext) => ext.extnID === NAME_CONSTRAINTS_EXTENSION_OID);
+ return extension?.parsedValue instanceof NameConstraints ? extension.parsedValue : null;
+};
+
+/**
+ * RFC 5280 6.1.4 (g): a CA may restrict the namespace its subordinates can certify. Without this,
+ * the holder of a constrained sub-CA under the configured anchor could mint a leaf for any name and
+ * authenticate as any identity pinned to that anchor.
+ *
+ * Subtree matching (DNS/IP/email/URI/directory-name semantics, permitted and excluded) is delegated
+ * to pkijs rather than reimplemented. pkijs applies constraints carried by certificates on the path
+ * but not by the trust anchor itself, so the anchor's own constraints are supplied separately as the
+ * RFC's initial-permitted/excluded-subtrees inputs. That matters because operators may pin a
+ * constrained sub-CA directly rather than the root above it.
+ *
+ * Only runs when some certificate on the path actually asserts constraints, so a chain that has
+ * none is validated exactly as before.
+ */
+const enforceNameConstraints = async (orderedPath: TNativeX509[], now: Date): Promise<TVerificationFailure | null> => {
+ if (orderedPath.length < 2) return null;
+
+ const parsedPath = orderedPath.map((cert) => Certificate.fromBER(cert.raw));
+ if (!parsedPath.some((cert) => nameConstraintsOf(cert))) return null;
+
+ const anchor = parsedPath[parsedPath.length - 1];
+ const anchorConstraints = nameConstraintsOf(anchor);
+
+ const engine = new CertificateChainValidationEngine({
+ trustedCerts: [anchor],
+ // pkijs takes the chain end-entity last.
+ certs: parsedPath.slice(0, -1).reverse(),
+ checkDate: now
+ });
+
+ const { result, resultCode } = await engine.verify(
+ {
+ initialPermittedSubtreesSet: anchorConstraints?.permittedSubtrees ?? [],
+ initialExcludedSubtreesSet: anchorConstraints?.excludedSubtrees ?? []
+ },
+ pkiCryptoEngine
+ );
+
+ if (result) return null;
+ if (resultCode === PERMITTED_SUBTREE_VIOLATION_CODE || resultCode === EXCLUDED_SUBTREE_VIOLATION_CODE) {
+ return { ok: false, reasonCode: "name_constraint_violation" };
+ }
+ return { ok: false, reasonCode: "ca_verification_failed" };
+};
+
/**
* Validate the presented client certificate chain against a configured trust anchor.
*
@@ -16,7 +112,8 @@ const isWithinValidityWindow = (cert: TNativeX509, at: Date): boolean =>
* path from the leaf through the presented intermediates up to the configured trust anchor and
* verifies, at every hop: the issuer relationship (subject/issuer match + signature), that each
* issuer is a CA (including the trust anchor itself), and that every certificate on the path is
- * within its validity window.
+ * within its validity window. The resulting path is then checked against the RFC 5280 delegation
+ * constraints its CAs assert: `pathLenConstraint` and name constraints.
*
* The trust anchor is the only trusted input. Presented intermediates are untrusted: a forged or
* unrelated intermediate cannot create a path to the anchor, so it is rejected. This mirrors how
@@ -31,7 +128,7 @@ const isWithinValidityWindow = (cert: TNativeX509, at: Date): boolean =>
* @param presentedChain intermediates presented by the client (chain[1..n]); order-independent
* @param trustAnchor the configured CA certificate to anchor the path on
*/
-export const verifyClientCertificateChain = ({
+export const verifyClientCertificateChain = async ({
leaf,
presentedChain,
trustAnchor,
@@ -41,7 +138,7 @@ export const verifyClientCertificateChain = ({
presentedChain: TNativeX509[];
trustAnchor: TNativeX509;
now?: Date;
-}): TVerifyClientCertificateChainResult => {
+}): Promise<TVerifyClientCertificateChainResult> => {
// Candidate issuers the builder may walk through. The trust anchor is always available; the
// presented intermediates are untrusted candidates that only matter if they help reach the anchor.
const anchorRaw = trustAnchor.raw;
@@ -72,21 +169,23 @@ export const verifyClientCertificateChain = ({
}
};
+ type TPathSearchResult = { ok: true; issuers: TNativeX509[] } | TVerificationFailure;
+
// Cache results by DER bytes, so a shared issuer is explored once regardless of how many paths
// reach it. This bounds signature verification to O(n^2) and avoids factorial work for crafted
// chains with many overlapping paths.
- const results = new Map<string, TVerifyClientCertificateChainResult>();
+ const results = new Map<string, TPathSearchResult>();
const inProgress = new Set<string>();
const certificateId = (cert: TNativeX509) => cert.raw.toString("base64");
- const walk = (current: TNativeX509): TVerifyClientCertificateChainResult => {
+ const walk = (current: TNativeX509): TPathSearchResult => {
const currentId = certificateId(current);
const cachedResult = results.get(currentId);
if (cachedResult) return cachedResult;
if (inProgress.has(currentId)) return { ok: false, reasonCode: "ca_verification_failed" };
inProgress.add(currentId);
- let result: TVerifyClientCertificateChainResult;
+ let result: TPathSearchResult;
if (!isWithinValidityWindow(current, now)) {
result = {
@@ -95,7 +194,7 @@ export const verifyClientCertificateChain = ({
};
} else if (isAnchor(current)) {
// Reached the trust anchor: the path is complete and valid.
- result = { ok: true };
+ result = { ok: true, issuers: [] };
} else if (trustAnchor.ca && issuedBy(current, trustAnchor)) {
// The configured anchor directly issued the current certificate. The anchor must itself be a
// CA to sign certificates: presented intermediates are gated on `candidate.ca` below, and the
@@ -107,7 +206,7 @@ export const verifyClientCertificateChain = ({
reasonCode: now < new Date(trustAnchor.validFrom) ? "certificate_not_yet_valid" : "certificate_expired"
};
} else {
- result = { ok: true };
+ result = { ok: true, issuers: [trustAnchor] };
}
} else {
// No path to the anchor was found through this node. Default to the generic reason, but
@@ -120,7 +219,7 @@ export const verifyClientCertificateChain = ({
if (candidate.ca && issuedBy(current, candidate)) {
const candidateResult = walk(candidate);
if (candidateResult.ok) {
- result = candidateResult;
+ result = { ok: true, issuers: [candidate, ...candidateResult.issuers] };
break;
}
if (candidateResult.reasonCode !== "ca_verification_failed") {
@@ -135,7 +234,18 @@ export const verifyClientCertificateChain = ({
return result;
};
- return walk(leaf);
+ const pathResult = walk(leaf);
+ if (!pathResult.ok) return pathResult;
+
+ const orderedPath = [leaf, ...pathResult.issuers];
+
+ try {
+ const pathLengthFailure = enforcePathLength(orderedPath);
+ if (pathLengthFailure) return pathLengthFailure;
+ return (await enforceNameConstraints(orderedPath, now)) ?? { ok: true };
+ } catch {
+ return { ok: false, reasonCode: "ca_verification_failed" };
+ }
};
export const parseSubjectDetails = (data?: string | null) => {
diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
index ddcaa6b318..ea0dc760e1 100644
--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
@@ -49,10 +49,23 @@ import {
parseAllowedSubjectAltNames,
parseSubjectDetails,
serializeAllowedSubjectAltNames,
+ TVerifyClientCertificateChainResult,
verifyClientCertificateChain
} from "./identity-tls-cert-auth-fns";
import { TIdentityTlsCertAuthServiceFactory } from "./identity-tls-cert-auth-types";
+const CHAIN_FAILURE_MESSAGES: Record<
+ Extract<TVerifyClientCertificateChainResult, { ok: false }>["reasonCode"],
+ string
+> = {
+ ca_verification_failed: "Access denied: Certificate chain could not be validated against the provided CA.",
+ certificate_expired: "Access denied: A certificate in the chain is outside its validity period.",
+ certificate_not_yet_valid: "Access denied: A certificate in the chain is outside its validity period.",
+ name_constraint_violation:
+ "Access denied: The client certificate's name is outside the namespace its issuing CA is permitted to certify.",
+ path_length_exceeded: "Access denied: The certificate chain has more intermediate CAs than a CA in it permits."
+};
+
type TIdentityTlsCertAuthServiceFactoryDep = {
identityDAL: Pick<TIdentityDALFactory, "findById">;
identityAccessTokenDAL: Pick<TIdentityAccessTokenDALFactory, "delete">;
@@ -143,17 +156,14 @@ export const identityTlsCertAuthServiceFactory = ({
.slice(1)
.map((pem) => new crypto.nativeCrypto.X509Certificate(pem));
- const chainResult = verifyClientCertificateChain({
+ const chainResult = await verifyClientCertificateChain({
leaf: clientCertificateX509,
presentedChain,
trustAnchor: caCertificateX509
});
if (!chainResult.ok) {
- const message =
- chainResult.reasonCode === "ca_verification_failed"
- ? "Access denied: Certificate chain could not be validated against the provided CA."
- : "Access denied: A certificate in the chain is outside its validity period.";
+ const message = CHAIN_FAILURE_MESSAGES[chainResult.reasonCode];
throw new UnauthorizedError({
message,
detail: {
diff --git a/docs/documentation/platform/identities/tls-cert-auth.mdx b/docs/documentation/platform/identities/tls-cert-auth.mdx
index 4f5ff63631..82b89eeb5a 100644
--- a/docs/documentation/platform/identities/tls-cert-auth.mdx
+++ b/docs/documentation/platform/identities/tls-cert-auth.mdx
@@ -94,7 +94,7 @@ Now create a new TLS Certificate Auth Method.
Here's some information about each field:
- **CA Certificate:** A PEM encoded CA Certificate used to validate incoming TLS request client certificate.
-- **Verify Client Certificate Chain (default is disabled):** By default, the CA Certificate must be the **direct issuer** of the client's leaf certificate. Enable this to instead treat the CA Certificate as a **trust anchor** and accept any client whose presented chain (leaf followed by intermediates) builds a valid path up to it. This is helpful when the issuing intermediate rotates beneath a long-lived root, such as a **SPIRE X.509-SVID**: you can pin the stable root here once and let the workload present its current intermediate alongside its leaf, rather than updating the CA Certificate on every rotation. Either way the trust anchor is the only certificate trusted, the client certificate must still be an end-entity certificate, and the Common Name and Subject Alternative Name checks below still apply to the leaf.
+- **Verify Client Certificate Chain (default is disabled):** By default, the CA Certificate must be the **direct issuer** of the client's leaf certificate. Enable this to instead treat the CA Certificate as a **trust anchor** and accept any client whose presented chain (leaf followed by intermediates) builds a valid path up to it. This is helpful when the issuing intermediate rotates beneath a long-lived root, such as a **SPIRE X.509-SVID**: you can pin the stable root here once and let the workload present its current intermediate alongside its leaf, rather than updating the CA Certificate on every rotation. Either way the trust anchor is the only certificate trusted, the client certificate must still be an end-entity certificate, and the Common Name and Subject Alternative Name checks below still apply to the leaf. Restrictions that the CAs on the path place on their subordinates are honored: a client certificate whose name falls outside an issuing CA's name constraints is rejected, as is a chain with more intermediates than a CA's path length permits.
- **Allowed Common Names:** A comma separated list of client certificate common names allowed.
- **Allowed Subject Alternative Names:** A comma separated list of client certificate subject alternative names (SANs) allowed. This is useful when the client certificate carries its identity in a SAN rather than the Subject Common Name, such as a SPIFFE X.509-SVID whose identity is a URI SAN (`spiffe://trust-domain/path`) with an empty Subject. Matching is type-aware, so an entry only matches a SAN of the same type:
- **Type-prefixed entries** are matched against the corresponding SAN type, e.g. `URI:spiffe://example.org/svc`, `IP:10.0.0.1`, `EMAIL:[email protected]`.