Skip to content

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

fix(scep): prevent renewal identity bypass via ambiguous DN comparison

Carlos Monastyrski657d85280564
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 190a0d4d43..28a1cc7816 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -7214,6 +7214,7 @@ interface ScepRenewalEvent {
transactionId: string;
csrSubject: string;
existingCertificateSerial?: string;
+ existingCertificateSubject?: string;
status: ScepEnrollmentStatus;
failReason?: string;
issuedCertificateId?: string;
diff --git a/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts b/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts
index b2cfb70fe3..09e2b49746 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts
@@ -1,10 +1,17 @@
/* eslint-disable no-bitwise */
import { webcrypto } from "node:crypto";
+import { AsnConvert } from "@peculiar/asn1-schema";
+import * as asn1x509 from "@peculiar/asn1-x509";
import * as x509 from "@peculiar/x509";
import { beforeAll, describe, expect, test } from "vitest";
-import { decodeAsn1ChallengePasswordValue, extractScepChallengePassword } from "./pki-scep-fns";
+import {
+ decodeAsn1ChallengePasswordValue,
+ evaluateScepRenewalAuthorization,
+ extractScepChallengePassword,
+ ScepRenewalDenyReason
+} from "./pki-scep-fns";
// Builds a DER-encoded ASN.1 string (tag + length + value) like @peculiar/x509 surfaces the attribute value.
const derString = (tag: number, value: string): Uint8Array => {
@@ -85,3 +92,343 @@ describe("extractScepChallengePassword", () => {
expect(extractScepChallengePassword(csr)).toBe("");
});
});
+
+describe("evaluateScepRenewalAuthorization", () => {
+ const PROFILE_ID = "8d0f3a1e-2f4b-4c6d-9e10-5a7b3c9d1e42";
+
+ const authorize = ({
+ csrSubject,
+ signerSubject,
+ csrSans,
+ signerSans,
+ csrSanExt,
+ signerSanExt,
+ csrForwardedToCa
+ }: {
+ csrSubject: string;
+ signerSubject: string;
+ csrSans?: x509.JsonGeneralName[];
+ signerSans?: x509.JsonGeneralName[];
+ csrSanExt?: x509.Extension | null;
+ signerSanExt?: x509.Extension | null;
+ csrForwardedToCa?: boolean;
+ }) =>
+ evaluateScepRenewalAuthorization({
+ isValidSigner: true,
+ storedSignerCert: { profileId: PROFILE_ID },
+ profileId: PROFILE_ID,
+ csrForwardedToCa: csrForwardedToCa ?? false,
+ csrSubjectName: new x509.Name(csrSubject),
+ signerCertSubjectName: new x509.Name(signerSubject),
+ csrSubjectAltNames: csrSanExt ?? (csrSans ? new x509.SubjectAlternativeNameExtension(csrSans) : null),
+ signerCertSubjectAltNames:
+ signerSanExt ?? (signerSans ? new x509.SubjectAlternativeNameExtension(signerSans) : null)
+ });
+
+ test("authorizes a renewal whose CSR identity matches the signer certificate", () => {
+ expect(authorize({ csrSubject: "CN=device-01,OU=eng", signerSubject: "CN=device-01,OU=eng" })).toEqual({
+ authorized: true
+ });
+ });
+
+ test("still authorizes when the two subjects differ only by case and whitespace", () => {
+ expect(authorize({ csrSubject: "CN=Device-01, OU=Eng", signerSubject: "CN=device-01,OU=eng" })).toEqual({
+ authorized: true
+ });
+ });
+
+ test("denies a CSR whose single RDN flattens onto the victim's multi-RDN subject", () => {
+ expect(authorize({ csrSubject: "CN=device-01,OU=eng", signerSubject: "CN=device-01\\,ou\\=eng" })).toEqual({
+ authorized: false,
+ reason: ScepRenewalDenyReason.SubjectMismatch
+ });
+ });
+
+ test("denies the same flattening in the other direction", () => {
+ expect(authorize({ csrSubject: "CN=device-01\\,ou\\=eng", signerSubject: "CN=device-01,OU=eng" })).toEqual({
+ authorized: false,
+ reason: ScepRenewalDenyReason.SubjectMismatch
+ });
+ });
+
+ test("denies a CSR that flattens a multi-valued RDN into one attribute value", () => {
+ expect(authorize({ csrSubject: "CN=a+OU=b", signerSubject: "CN=a\\+ou\\=b" })).toEqual({
+ authorized: false,
+ reason: ScepRenewalDenyReason.SubjectMismatch
+ });
+ });
+
+ test("denies a CSR that shifts an RDN boundary inside a domain-component chain", () => {
+ expect(authorize({ csrSubject: "CN=alice,DC=corp,DC=com", signerSubject: "CN=alice\\,dc\\=corp,DC=com" })).toEqual({
+ authorized: false,
+ reason: ScepRenewalDenyReason.SubjectMismatch
+ });
+ });
+
+ test("denies a CSR whose single SAN entry flattens onto two signer SAN entries", () => {
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSans: [{ type: "url", value: "https://a,url:https://b" }],
+ signerSans: [
+ { type: "url", value: "https://a" },
+ { type: "url", value: "https://b" }
+ ]
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.SubjectAltNameMismatch });
+ });
+
+ test("authorizes matching SAN sets regardless of entry order", () => {
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSans: [
+ { type: "dns", value: "b.example.com" },
+ { type: "dns", value: "a.example.com" }
+ ],
+ signerSans: [
+ { type: "dns", value: "a.example.com" },
+ { type: "dns", value: "B.example.com" }
+ ]
+ })
+ ).toEqual({ authorized: true });
+ });
+
+ const sanExtensionFromGeneralNames = (names: asn1x509.GeneralName[]): x509.Extension => {
+ const generalNames = new asn1x509.GeneralNames();
+ generalNames.push(...names);
+ return new x509.Extension("2.5.29.17", false, AsnConvert.serialize(generalNames));
+ };
+
+ const dnsGeneralName = (value: string): asn1x509.GeneralName => {
+ const name = new asn1x509.GeneralName();
+ name.dNSName = value;
+ return name;
+ };
+
+ const kerberosPrincipalGeneralName = (principal: string): asn1x509.GeneralName => {
+ const name = new asn1x509.GeneralName();
+ name.otherName = new asn1x509.OtherName({
+ typeId: "1.3.6.1.5.2.2",
+ value: AsnConvert.serialize(new asn1x509.DirectoryString({ utf8String: principal }))
+ });
+ return name;
+ };
+
+ const upnGeneralName = (directoryString: asn1x509.DirectoryString): asn1x509.GeneralName => {
+ const name = new asn1x509.GeneralName();
+ name.otherName = new asn1x509.OtherName({
+ typeId: "1.3.6.1.4.1.311.20.2.3",
+ value: AsnConvert.serialize(directoryString)
+ });
+ return name;
+ };
+
+ test("authorizes a UPN renewal when the CSR and the certificate encode it differently", () => {
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSanExt: sanExtensionFromGeneralNames([
+ dnsGeneralName("d.example.com"),
+ upnGeneralName(new asn1x509.DirectoryString({ printableString: "[email protected]" }))
+ ]),
+ signerSanExt: sanExtensionFromGeneralNames([
+ dnsGeneralName("d.example.com"),
+ upnGeneralName(new asn1x509.DirectoryString({ utf8String: "[email protected]" }))
+ ])
+ })
+ ).toEqual({ authorized: true });
+ });
+
+ test("authorizes an internal-CA renewal whose CSR keeps a SAN entry issuance strips", () => {
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSanExt: sanExtensionFromGeneralNames([
+ dnsGeneralName("d.example.com"),
+ kerberosPrincipalGeneralName("[email protected]")
+ ]),
+ signerSanExt: sanExtensionFromGeneralNames([dnsGeneralName("d.example.com")])
+ })
+ ).toEqual({ authorized: true });
+ });
+
+ test("denies the same CSR when the CA receives it verbatim", () => {
+ const csrSanExt = sanExtensionFromGeneralNames([
+ dnsGeneralName("d.example.com"),
+ kerberosPrincipalGeneralName("[email protected]")
+ ]);
+ const signerSanExt = sanExtensionFromGeneralNames([dnsGeneralName("d.example.com")]);
+
+ expect(new x509.SubjectAlternativeNameExtension(csrSanExt.rawData).names.items).toHaveLength(1);
+
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSanExt,
+ signerSanExt,
+ csrForwardedToCa: true
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.SubjectAltNameMismatch });
+ });
+
+ test("authorizes a forwarded renewal when both sides carry the same stripped-type entry", () => {
+ const names = [dnsGeneralName("d.example.com"), kerberosPrincipalGeneralName("[email protected]")];
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSanExt: sanExtensionFromGeneralNames(names),
+ signerSanExt: sanExtensionFromGeneralNames(names),
+ csrForwardedToCa: true
+ })
+ ).toEqual({ authorized: true });
+ });
+
+ test("denies a renewal that adds a supported SAN the certificate does not have", () => {
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSans: [
+ { type: "dns", value: "d.example.com" },
+ { type: "dns", value: "extra.example.com" }
+ ],
+ signerSans: [{ type: "dns", value: "d.example.com" }]
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.SubjectAltNameMismatch });
+ });
+
+ // A UPN OID whose value is not a DirectoryString: the library cannot model it, so it must be
+ // treated as an entry issuance strips rather than assumed preserved from its OID alone.
+ const malformedUpnGeneralName = (principal: string): asn1x509.GeneralName => {
+ const name = new asn1x509.GeneralName();
+ const ia5 = Uint8Array.from([0x16, principal.length, ...Buffer.from(principal)]);
+ name.otherName = new asn1x509.OtherName({ typeId: "1.3.6.1.4.1.311.20.2.3", value: ia5.buffer });
+ return name;
+ };
+
+ test("denies a forwarded CSR that adds a UPN OID carrying a non-DirectoryString value", () => {
+ const csrSanExt = sanExtensionFromGeneralNames([
+ dnsGeneralName("w.example.com"),
+ malformedUpnGeneralName("[email protected]")
+ ]);
+ const signerSanExt = sanExtensionFromGeneralNames([dnsGeneralName("w.example.com")]);
+
+ expect(new x509.SubjectAlternativeNameExtension(csrSanExt.rawData).names.items).toHaveLength(1);
+
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSanExt,
+ signerSanExt,
+ csrForwardedToCa: true
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.SubjectAltNameMismatch });
+ });
+
+ test("authorizes that same CSR against an internal CA, which strips the entry at issuance", () => {
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSanExt: sanExtensionFromGeneralNames([
+ dnsGeneralName("w.example.com"),
+ malformedUpnGeneralName("[email protected]")
+ ]),
+ signerSanExt: sanExtensionFromGeneralNames([dnsGeneralName("w.example.com")])
+ })
+ ).toEqual({ authorized: true });
+ });
+
+ // An external CA may add names of its own (ADCS stamps a GUID otherName); that must not
+ // permanently lock the device out of renewing.
+ test("authorizes a forwarded renewal when the certificate carries an entry the CSR does not", () => {
+ expect(
+ authorize({
+ csrSubject: "CN=device-01",
+ signerSubject: "CN=device-01",
+ csrSanExt: sanExtensionFromGeneralNames([dnsGeneralName("w.example.com")]),
+ signerSanExt: sanExtensionFromGeneralNames([
+ dnsGeneralName("w.example.com"),
+ kerberosPrincipalGeneralName("[email protected]")
+ ]),
+ csrForwardedToCa: true
+ })
+ ).toEqual({ authorized: true });
+ });
+
+ test("denies a certificate issued under a different application", () => {
+ expect(
+ evaluateScepRenewalAuthorization({
+ isValidSigner: true,
+ storedSignerCert: { profileId: PROFILE_ID, applicationId: "1b9f0c2d-3e4a-4b5c-8d6e-7f8a9b0c1d2e" },
+ profileId: PROFILE_ID,
+ applicationId: "c4d5e6f7-a8b9-4c0d-9e1f-2a3b4c5d6e7f",
+ csrForwardedToCa: false,
+ csrSubjectName: new x509.Name("CN=device-01"),
+ signerCertSubjectName: new x509.Name("CN=device-01")
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.WrongApplication });
+ });
+
+ test("denies an application certificate renewing through the bare profile endpoint", () => {
+ expect(
+ evaluateScepRenewalAuthorization({
+ isValidSigner: true,
+ storedSignerCert: { profileId: PROFILE_ID, applicationId: "1b9f0c2d-3e4a-4b5c-8d6e-7f8a9b0c1d2e" },
+ profileId: PROFILE_ID,
+ csrForwardedToCa: false,
+ csrSubjectName: new x509.Name("CN=device-01"),
+ signerCertSubjectName: new x509.Name("CN=device-01")
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.WrongApplication });
+ });
+
+ test("authorizes a renewal through the application that issued the certificate", () => {
+ const applicationId = "c4d5e6f7-a8b9-4c0d-9e1f-2a3b4c5d6e7f";
+ expect(
+ evaluateScepRenewalAuthorization({
+ isValidSigner: true,
+ storedSignerCert: { profileId: PROFILE_ID, applicationId },
+ profileId: PROFILE_ID,
+ applicationId,
+ csrForwardedToCa: false,
+ csrSubjectName: new x509.Name("CN=device-01"),
+ signerCertSubjectName: new x509.Name("CN=device-01")
+ })
+ ).toEqual({ authorized: true });
+ });
+
+ test("denies when the signer certificate belongs to another profile", () => {
+ expect(
+ evaluateScepRenewalAuthorization({
+ isValidSigner: true,
+ storedSignerCert: { profileId: "0f2c6b58-9a3d-4e71-b0c5-1d8e2f7a4b60" },
+ profileId: PROFILE_ID,
+ csrForwardedToCa: false,
+ csrSubjectName: new x509.Name("CN=device-01"),
+ signerCertSubjectName: new x509.Name("CN=device-01")
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.WrongProfile });
+ });
+
+ test("denies when the signer certificate did not validate", () => {
+ expect(
+ evaluateScepRenewalAuthorization({
+ isValidSigner: false,
+ storedSignerCert: { profileId: PROFILE_ID },
+ profileId: PROFILE_ID,
+ csrForwardedToCa: false,
+ csrSubjectName: new x509.Name("CN=device-01"),
+ signerCertSubjectName: new x509.Name("CN=device-01")
+ })
+ ).toEqual({ authorized: false, reason: ScepRenewalDenyReason.InvalidSigner });
+ });
+});
diff --git a/backend/src/ee/services/pki-scep/pki-scep-fns.ts b/backend/src/ee/services/pki-scep/pki-scep-fns.ts
index d3adb52082..d917e88caf 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-fns.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.ts
@@ -1,3 +1,5 @@
+import { AsnConvert } from "@peculiar/asn1-schema";
+import { GeneralName, GeneralNames } from "@peculiar/asn1-x509";
import * as x509 from "@peculiar/x509";
import RE2 from "re2";
@@ -13,6 +15,7 @@ import { TCertificateAuthorityDALFactory } from "@app/services/certificate-autho
import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
import { getCaCertChains, getCaSigner } from "@app/services/certificate-authority/certificate-authority-fns";
import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
+import { SUPPORTED_GENERAL_NAME_TYPES } from "@app/services/certificate-common/certificate-constants";
import { THsmConnectorServiceFactory } from "@app/services/hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -323,60 +326,109 @@ export const isSignerCertIssuedByCa = async ({
export enum ScepRenewalDenyReason {
InvalidSigner = "invalid-signer",
WrongProfile = "wrong-profile",
- IdentityMismatch = "identity-mismatch"
+ WrongApplication = "wrong-application",
+ SubjectMismatch = "subject-mismatch",
+ SubjectAltNameMismatch = "subject-alt-name-mismatch"
}
export type TScepRenewalAuthResult = { authorized: true } | { authorized: false; reason: ScepRenewalDenyReason };
const DN_WHITESPACE_RE = new RE2("\\s+", "g");
-const normalizeX500Name = (name: x509.Name): string => {
- const rdns = name.toJSON();
+type TCanonicalAttribute = [type: string, value: string];
+
+const compareCanonicalAttributes = (a: TCanonicalAttribute, b: TCanonicalAttribute): number => {
+ if (a[0] !== b[0]) return a[0] < b[0] ? -1 : 1;
+ if (a[1] === b[1]) return 0;
+ return a[1] < b[1] ? -1 : 1;
+};
- const canonicalRdns = rdns.map((rdn) => {
- const pairs: string[] = [];
+const normalizeX500Name = (name: x509.Name): string => {
+ const canonicalRdns = name.toJSON().map((rdn) => {
+ const attributes: TCanonicalAttribute[] = [];
for (const [type, values] of Object.entries(rdn)) {
const normalizedType = type.toLowerCase();
for (const value of values) {
const normalizedValue = value.normalize("NFC").replace(DN_WHITESPACE_RE, " ").trim().toLowerCase();
- pairs.push(`${normalizedType}=${normalizedValue}`);
+ attributes.push([normalizedType, normalizedValue]);
}
}
- return pairs.sort().join("+");
+ return attributes.sort(compareCanonicalAttributes);
});
- return canonicalRdns.join(",");
+ return JSON.stringify(canonicalRdns);
+};
+
+const toHex = (data: ArrayBuffer): string => Buffer.from(data).toString("hex");
+
+const survivesIssuance = (name: GeneralName): boolean => {
+ try {
+ const single = new GeneralNames();
+ single.push(name);
+ const modelled = new x509.GeneralNames(AsnConvert.serialize(single)).items;
+ return modelled.length === 1 && SUPPORTED_GENERAL_NAME_TYPES.has(modelled[0].type);
+ } catch {
+ return false;
+ }
+};
+
+const normalizeIssuedSubjectAltNames = (ext: x509.Extension | null | undefined): string => {
+ if (!ext) return JSON.stringify([]);
+
+ let items: readonly x509.GeneralName[] = [];
+ try {
+ items = new x509.SubjectAlternativeNameExtension(ext.rawData).names.items;
+ } catch {
+ items = [];
+ }
+
+ const entries: TCanonicalAttribute[] = items
+ .filter((item) => SUPPORTED_GENERAL_NAME_TYPES.has(item.type))
+ .map((item) => {
+ const type = String(item.type).toLowerCase();
+ const raw = String(item.value).normalize("NFC").trim();
+ return [type, type === "dns" ? raw.toLowerCase() : raw];
+ });
+
+ return JSON.stringify(entries.sort(compareCanonicalAttributes));
};
-// SANs are an unordered set in RFC 5280; normalize each entry and sort for comparison.
-const normalizeSubjectAltNames = (ext: x509.SubjectAlternativeNameExtension | null | undefined): string => {
- if (!ext) return "";
- const pairs: string[] = [];
- for (const item of ext.names.items) {
- const type = String(item.type).toLowerCase();
- const raw = String(item.value).normalize("NFC").trim();
- const value = type === "dns" ? raw.toLowerCase() : raw;
- pairs.push(`${type}:${value}`);
+const collectStrippedSubjectAltNames = (ext: x509.Extension | null | undefined): string[] => {
+ if (!ext) return [];
+
+ let generalNames: GeneralNames;
+ try {
+ generalNames = AsnConvert.parse(ext.value, GeneralNames);
+ } catch {
+ return [`unparsed:${toHex(ext.value)}`];
}
- return pairs.sort().join(",");
+
+ return generalNames
+ .filter((name) => !survivesIssuance(name))
+ .map((name) => toHex(AsnConvert.serialize(name)))
+ .sort();
};
export const evaluateScepRenewalAuthorization = ({
isValidSigner,
storedSignerCert,
profileId,
+ applicationId,
+ csrForwardedToCa,
csrSubjectName,
signerCertSubjectName,
csrSubjectAltNames,
signerCertSubjectAltNames
}: {
isValidSigner: boolean;
- storedSignerCert?: { profileId?: string | null } | null;
+ storedSignerCert?: { profileId?: string | null; applicationId?: string | null } | null;
profileId: string;
+ applicationId?: string | null;
+ csrForwardedToCa: boolean;
csrSubjectName: x509.Name;
signerCertSubjectName: x509.Name;
- csrSubjectAltNames?: x509.SubjectAlternativeNameExtension | null;
- signerCertSubjectAltNames?: x509.SubjectAlternativeNameExtension | null;
+ csrSubjectAltNames?: x509.Extension | null;
+ signerCertSubjectAltNames?: x509.Extension | null;
}): TScepRenewalAuthResult => {
if (!isValidSigner) {
return { authorized: false, reason: ScepRenewalDenyReason.InvalidSigner };
@@ -386,11 +438,28 @@ export const evaluateScepRenewalAuthorization = ({
return { authorized: false, reason: ScepRenewalDenyReason.WrongProfile };
}
+ if ((storedSignerCert.applicationId ?? null) !== (applicationId ?? null)) {
+ return { authorized: false, reason: ScepRenewalDenyReason.WrongApplication };
+ }
+
+ if (normalizeX500Name(csrSubjectName) !== normalizeX500Name(signerCertSubjectName)) {
+ return { authorized: false, reason: ScepRenewalDenyReason.SubjectMismatch };
+ }
+
if (
- normalizeX500Name(csrSubjectName) !== normalizeX500Name(signerCertSubjectName) ||
- normalizeSubjectAltNames(csrSubjectAltNames) !== normalizeSubjectAltNames(signerCertSubjectAltNames)
+ normalizeIssuedSubjectAltNames(csrSubjectAltNames) !== normalizeIssuedSubjectAltNames(signerCertSubjectAltNames)
) {
- return { authorized: false, reason: ScepRenewalDenyReason.IdentityMismatch };
+ return { authorized: false, reason: ScepRenewalDenyReason.SubjectAltNameMismatch };
+ }
+
+ if (csrForwardedToCa) {
+ const signerStrippedNames = collectStrippedSubjectAltNames(signerCertSubjectAltNames);
+ const csrIntroducesStrippedName = collectStrippedSubjectAltNames(csrSubjectAltNames).some(
+ (name) => !signerStrippedNames.includes(name)
+ );
+ if (csrIntroducesStrippedName) {
+ return { authorized: false, reason: ScepRenewalDenyReason.SubjectAltNameMismatch };
+ }
}
return { authorized: true };
diff --git a/backend/src/ee/services/pki-scep/pki-scep-service.ts b/backend/src/ee/services/pki-scep/pki-scep-service.ts
index 7c61199ce7..20cebb2ea8 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts
@@ -89,7 +89,7 @@ type TPkiScepServiceFactoryDep = {
certificateDAL: Pick<TCertificateDALFactory, "findOne" | "transaction">;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find" | "findById">;
- certificateRequestDAL: Pick<TCertificateRequestDALFactory, "findById">;
+ certificateRequestDAL: Pick<TCertificateRequestDALFactory, "findById" | "findOne">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction" | "findById">;
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey">;
@@ -669,23 +669,22 @@ export const pkiScepServiceFactory = ({
? await certificateDAL.findOne({ serialNumber: signerCertObj.serialNumber, caId: profile.caId! })
: null;
- const toSanExt = (ext: x509.Extension | null): x509.SubjectAlternativeNameExtension | null => {
- if (!ext) return null;
- if (ext instanceof x509.SubjectAlternativeNameExtension) return ext;
- try {
- return new x509.SubjectAlternativeNameExtension(ext.rawData);
- } catch {
- return null;
- }
- };
- const csrSanExt = toSanExt(csrObj.getExtension("2.5.29.17"));
- const signerSanExt = signerCertObj ? toSanExt(signerCertObj.getExtension("2.5.29.17")) : null;
+ let signerCertApplicationId = storedSignerCert?.applicationId ?? null;
+ if (storedSignerCert && !signerCertApplicationId) {
+ const originatingRequest = await certificateRequestDAL.findOne({ certificateId: storedSignerCert.id });
+ signerCertApplicationId = originatingRequest?.applicationId ?? null;
+ }
+
+ const csrSanExt = csrObj.getExtension("2.5.29.17");
+ const signerSanExt = signerCertObj ? signerCertObj.getExtension("2.5.29.17") : null;
const renewalAuth: TScepRenewalAuthResult = signerCertObj
? evaluateScepRenewalAuthorization({
isValidSigner,
- storedSignerCert,
+ storedSignerCert: storedSignerCert && { ...storedSignerCert, applicationId: signerCertApplicationId },
profileId: profile.id,
+ applicationId,
+ csrForwardedToCa: caType !== CaType.INTERNAL,
csrSubjectName: csrObj.subjectName,
signerCertSubjectName: signerCertObj.subjectName,
csrSubjectAltNames: csrSanExt,
@@ -693,17 +692,35 @@ export const pkiScepServiceFactory = ({
})
: { authorized: false, reason: ScepRenewalDenyReason.InvalidSigner };
+ const auditMetadata = {
+ profileId: profile.id,
+ profileSlug: profile.slug,
+ transactionId: parsed.transactionId,
+ csrSubject: csrObj.subject,
+ existingCertificateSerial: signerCertObj?.serialNumber,
+ existingCertificateSubject: signerCertObj?.subject,
+ clientIp
+ };
+
if (!renewalAuth.authorized) {
const failReasonByDenyReason: Record<ScepRenewalDenyReason, string> = {
[ScepRenewalDenyReason.InvalidSigner]:
"Signer certificate is missing, malformed, expired, revoked, or does not chain to profile CA",
[ScepRenewalDenyReason.WrongProfile]: "Signer certificate does not belong to this profile",
- [ScepRenewalDenyReason.IdentityMismatch]: "Renewal CSR identity does not match the renewing certificate"
+ [ScepRenewalDenyReason.WrongApplication]:
+ "Signer certificate was not issued through the application handling this request",
+ [ScepRenewalDenyReason.SubjectMismatch]:
+ "Renewal CSR subject does not match the subject of the renewing certificate",
+ [ScepRenewalDenyReason.SubjectAltNameMismatch]:
+ "Renewal CSR subject alternative names do not match those of the renewing certificate"
};
- const failInfo =
- renewalAuth.reason === ScepRenewalDenyReason.IdentityMismatch
- ? ScepFailInfo.BadRequest
- : ScepFailInfo.BadCertId;
+ const identityDenyReasons: ScepRenewalDenyReason[] = [
+ ScepRenewalDenyReason.SubjectMismatch,
+ ScepRenewalDenyReason.SubjectAltNameMismatch
+ ];
+ const failInfo = identityDenyReasons.includes(renewalAuth.reason)
+ ? ScepFailInfo.BadRequest
+ : ScepFailInfo.BadCertId;
void auditLogService.createAuditLog({
projectId: profile.projectId,
@@ -714,13 +731,9 @@ export const pkiScepServiceFactory = ({
event: {
type: EventType.SCEP_RENEWAL,
metadata: {
- profileId: profile.id,
- profileSlug: profile.slug,
- transactionId: parsed.transactionId,
- csrSubject: csrObj.subject,
+ ...auditMetadata,
status: ScepEnrollmentStatus.Failure,
- failReason: failReasonByDenyReason[renewalAuth.reason],
- clientIp
+ failReason: failReasonByDenyReason[renewalAuth.reason]
}
}
});
@@ -748,14 +761,6 @@ export const pkiScepServiceFactory = ({
applicationId
});
- const auditMetadata = {
- profileId: profile.id,
- profileSlug: profile.slug,
- transactionId: parsed.transactionId,
- csrSubject: csrObj.subject,
- clientIp
- };
-
if (result.status === ScepIssuanceStatus.Pending) {
void auditLogService.createAuditLog({
projectId: profile.projectId,