Skip to content

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

Add SCEP support for Microsoft Intune

Carlos Monastyrski63384f54b100
diff --git a/backend/src/db/migrations/20260721143512_add-scep-intune-and-ra-ca-signing.ts b/backend/src/db/migrations/20260721143512_add-scep-intune-and-ra-ca-signing.ts
new file mode 100644
index 0000000000..eb6cb65fdb
--- /dev/null
+++ b/backend/src/db/migrations/20260721143512_add-scep-intune-and-ra-ca-signing.ts
@@ -0,0 +1,45 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiScepEnrollmentConfig)) {
+ const hasValidationConnectionId = await knex.schema.hasColumn(
+ TableName.PkiScepEnrollmentConfig,
+ "validationConnectionId"
+ );
+ const hasSignRaWithCa = await knex.schema.hasColumn(TableName.PkiScepEnrollmentConfig, "signRaWithCa");
+
+ await knex.schema.alterTable(TableName.PkiScepEnrollmentConfig, (t) => {
+ if (!hasValidationConnectionId) {
+ t.uuid("validationConnectionId").nullable();
+ t.foreign("validationConnectionId").references("id").inTable(TableName.AppConnection).onDelete("SET NULL");
+ t.index("validationConnectionId");
+ }
+ if (!hasSignRaWithCa) {
+ t.boolean("signRaWithCa").notNullable().defaultTo(false);
+ }
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiScepEnrollmentConfig)) {
+ const hasValidationConnectionId = await knex.schema.hasColumn(
+ TableName.PkiScepEnrollmentConfig,
+ "validationConnectionId"
+ );
+ const hasSignRaWithCa = await knex.schema.hasColumn(TableName.PkiScepEnrollmentConfig, "signRaWithCa");
+
+ await knex.schema.alterTable(TableName.PkiScepEnrollmentConfig, (t) => {
+ if (hasValidationConnectionId) {
+ t.dropForeign(["validationConnectionId"]);
+ t.dropIndex("validationConnectionId");
+ t.dropColumn("validationConnectionId");
+ }
+ if (hasSignRaWithCa) {
+ t.dropColumn("signRaWithCa");
+ }
+ });
+ }
+}
diff --git a/backend/src/db/schemas/pki-scep-enrollment-configs.ts b/backend/src/db/schemas/pki-scep-enrollment-configs.ts
index b6f17edd6c..758e8022fa 100644
--- a/backend/src/db/schemas/pki-scep-enrollment-configs.ts
+++ b/backend/src/db/schemas/pki-scep-enrollment-configs.ts
@@ -22,7 +22,9 @@ export const PkiScepEnrollmentConfigsSchema = z.object({
challengeType: z.string().default("static"),
dynamicChallengeExpiryMinutes: z.number().nullable().optional(),
dynamicChallengeMaxPending: z.number().nullable().optional(),
- applicationProfileId: z.string().uuid().nullable().optional()
+ applicationProfileId: z.string().uuid().nullable().optional(),
+ validationConnectionId: z.string().uuid().nullable().optional(),
+ signRaWithCa: z.boolean().default(false)
});
export type TPkiScepEnrollmentConfigs = z.infer<typeof PkiScepEnrollmentConfigsSchema>;
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 7bba34fb93..5206f2abd4 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -4065,6 +4065,9 @@ interface SetPkiApplicationScepEnrollment {
applicationId: string;
profileId: string;
challengeType: string;
+ signRaWithCa: boolean;
+ validationConnectionId?: string;
+ validationConnectionName?: string;
};
}
diff --git a/backend/src/ee/services/pki-scep/challenge/index.ts b/backend/src/ee/services/pki-scep/challenge/index.ts
index a327cc0ddb..7fff04c608 100644
--- a/backend/src/ee/services/pki-scep/challenge/index.ts
+++ b/backend/src/ee/services/pki-scep/challenge/index.ts
@@ -1,29 +1,36 @@
import { BadRequestError } from "@app/lib/errors";
-import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";
-import { TScepDynamicChallengeDALFactory } from "../pki-scep-dynamic-challenge-dal";
-import { dynamicChallengeValidator } from "./scep-challenge-dynamic";
-import { staticChallengeValidator } from "./scep-challenge-static";
-import { IScepChallengeValidator, ScepChallengeType } from "./scep-challenge-types";
+import { ScepChallengeType } from "./scep-challenge-types";
+import { intuneDelegatedHandler } from "./scep-intune-handler";
+import { selfValidatedHandler } from "./scep-self-validated-handler";
+import { IScepValidationHandler, TScepValidationHandlerDeps } from "./scep-validation-handler-types";
export type { IScepChallengeValidator } from "./scep-challenge-types";
export { ScepChallengeType } from "./scep-challenge-types";
+export type {
+ IScepValidationHandler,
+ ScepFailureContext,
+ ScepIssuedContext,
+ ScepValidationContext,
+ ScepValidationResult
+} from "./scep-validation-handler-types";
-type TScepChallengeValidatorFactoryDep = {
- scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "findById">;
- scepDynamicChallengeDAL: Pick<TScepDynamicChallengeDALFactory, "consumeByHash">;
+const SCEP_VALIDATION_HANDLERS: Record<
+ ScepChallengeType,
+ (deps: TScepValidationHandlerDeps) => IScepValidationHandler
+> = {
+ [ScepChallengeType.STATIC]: (deps) => selfValidatedHandler(ScepChallengeType.STATIC, deps),
+ [ScepChallengeType.DYNAMIC]: (deps) => selfValidatedHandler(ScepChallengeType.DYNAMIC, deps),
+ [ScepChallengeType.MICROSOFT_INTUNE]: (deps) => intuneDelegatedHandler(deps)
};
-export const getScepChallengeValidator = (
+export const getScepValidationHandler = (
challengeType: ScepChallengeType,
- deps: TScepChallengeValidatorFactoryDep
-): IScepChallengeValidator => {
- switch (challengeType) {
- case ScepChallengeType.DYNAMIC:
- return dynamicChallengeValidator({ scepDynamicChallengeDAL: deps.scepDynamicChallengeDAL });
- case ScepChallengeType.STATIC:
- return staticChallengeValidator({ scepEnrollmentConfigDAL: deps.scepEnrollmentConfigDAL });
- default:
- throw new BadRequestError({ message: `Unsupported SCEP challenge type: ${String(challengeType)}` });
+ deps: TScepValidationHandlerDeps
+): IScepValidationHandler => {
+ const factory = SCEP_VALIDATION_HANDLERS[challengeType];
+ if (!factory) {
+ throw new BadRequestError({ message: `Unsupported SCEP challenge type: ${String(challengeType)}` });
}
+ return factory(deps);
};
diff --git a/backend/src/ee/services/pki-scep/challenge/scep-challenge-types.ts b/backend/src/ee/services/pki-scep/challenge/scep-challenge-types.ts
index 18fe9f5e44..0a11b6c961 100644
--- a/backend/src/ee/services/pki-scep/challenge/scep-challenge-types.ts
+++ b/backend/src/ee/services/pki-scep/challenge/scep-challenge-types.ts
@@ -1,6 +1,7 @@
export enum ScepChallengeType {
STATIC = "static",
- DYNAMIC = "dynamic"
+ DYNAMIC = "dynamic",
+ MICROSOFT_INTUNE = "microsoft-intune"
}
export interface IScepChallengeValidator {
diff --git a/backend/src/ee/services/pki-scep/challenge/scep-intune-handler.ts b/backend/src/ee/services/pki-scep/challenge/scep-intune-handler.ts
new file mode 100644
index 0000000000..fb80be0261
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/challenge/scep-intune-handler.ts
@@ -0,0 +1,103 @@
+import * as x509 from "@peculiar/x509";
+
+import { BadRequestError } from "@app/lib/errors";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
+import {
+ discoverScepValidationServiceUri,
+ getMicrosoftEntraToken,
+ intuneSendFailureNotification,
+ intuneSendSuccessNotification,
+ intuneValidateScepRequest,
+ MicrosoftEntraTokenResource,
+ TMicrosoftIntuneConnectionCredentials
+} from "@app/services/app-connection/microsoft-intune";
+
+import { IScepValidationHandler, TScepValidationHandlerDeps } from "./scep-validation-handler-types";
+
+const INTUNE_FAILURE_HRESULT = -2147467259;
+
+const toThumbprint = async (cert: x509.X509Certificate) => {
+ const digest = await cert.getThumbprint("SHA-1");
+ return Buffer.from(digest).toString("hex").toUpperCase();
+};
+
+export const intuneDelegatedHandler = (deps: TScepValidationHandlerDeps): IScepValidationHandler => {
+ // Cache the service URI + token across this handler's calls.
+ let cached: { serviceUri: string; intuneToken: string } | null = null;
+
+ const resolveIntune = async (connectionId?: string | null) => {
+ if (!connectionId) {
+ throw new BadRequestError({
+ message: "SCEP enrollment is configured for Microsoft Intune validation but no connection is selected."
+ });
+ }
+ if (cached) return cached;
+
+ const connection = await deps.appConnectionDAL.findById(connectionId);
+ if (!connection || connection.app !== AppConnection.MicrosoftIntune) {
+ throw new BadRequestError({ message: "The configured Microsoft Intune connection could not be found." });
+ }
+
+ const credentials = (await decryptAppConnectionCredentials({
+ orgId: connection.orgId,
+ projectId: connection.projectId,
+ encryptedCredentials: connection.encryptedCredentials,
+ kmsService: deps.kmsService
+ })) as TMicrosoftIntuneConnectionCredentials;
+
+ const graphToken = await getMicrosoftEntraToken(credentials, MicrosoftEntraTokenResource.Graph);
+ const serviceUri = await discoverScepValidationServiceUri(graphToken);
+ const intuneToken = await getMicrosoftEntraToken(credentials, MicrosoftEntraTokenResource.Intune);
+
+ cached = { serviceUri, intuneToken };
+ return cached;
+ };
+
+ return {
+ validateRequest: async (ctx) => {
+ const { serviceUri, intuneToken } = await resolveIntune(ctx.validationConnectionId);
+ const result = await intuneValidateScepRequest({
+ intuneAccessToken: intuneToken,
+ serviceUri,
+ transactionId: ctx.transactionId,
+ certificateRequest: ctx.csrDer.toString("base64")
+ });
+
+ return result.allowed ? { allowed: true } : { allowed: false, error: result.errorDescription };
+ },
+
+ reportIssued: async (ctx) => {
+ const { serviceUri, intuneToken } = await resolveIntune(ctx.validationConnectionId);
+ const cert = new x509.X509Certificate(ctx.certificateDer);
+
+ await intuneSendSuccessNotification({
+ intuneAccessToken: intuneToken,
+ serviceUri,
+ notification: {
+ transactionId: ctx.transactionId,
+ certificateRequest: ctx.csrDer.toString("base64"),
+ certificateThumbprint: await toThumbprint(cert),
+ certificateSerialNumber: cert.serialNumber,
+ certificateExpirationDateUtc: cert.notAfter.toISOString(),
+ issuingCertificateAuthority: cert.issuer
+ }
+ });
+ },
+
+ reportFailure: async (ctx) => {
+ const { serviceUri, intuneToken } = await resolveIntune(ctx.validationConnectionId);
+
+ await intuneSendFailureNotification({
+ intuneAccessToken: intuneToken,
+ serviceUri,
+ notification: {
+ transactionId: ctx.transactionId,
+ certificateRequest: ctx.csrDer.toString("base64"),
+ hResult: INTUNE_FAILURE_HRESULT,
+ errorDescription: ctx.error || "Certificate issuance failed"
+ }
+ });
+ }
+ };
+};
diff --git a/backend/src/ee/services/pki-scep/challenge/scep-self-validated-handler.ts b/backend/src/ee/services/pki-scep/challenge/scep-self-validated-handler.ts
new file mode 100644
index 0000000000..11eb3d00f6
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/challenge/scep-self-validated-handler.ts
@@ -0,0 +1,21 @@
+import { dynamicChallengeValidator } from "./scep-challenge-dynamic";
+import { staticChallengeValidator } from "./scep-challenge-static";
+import { IScepChallengeValidator, ScepChallengeType } from "./scep-challenge-types";
+import { IScepValidationHandler, TScepValidationHandlerDeps } from "./scep-validation-handler-types";
+
+export const selfValidatedHandler = (
+ challengeType: ScepChallengeType.STATIC | ScepChallengeType.DYNAMIC,
+ deps: TScepValidationHandlerDeps
+): IScepValidationHandler => {
+ const validator: IScepChallengeValidator =
+ challengeType === ScepChallengeType.DYNAMIC
+ ? dynamicChallengeValidator({ scepDynamicChallengeDAL: deps.scepDynamicChallengeDAL })
+ : staticChallengeValidator({ scepEnrollmentConfigDAL: deps.scepEnrollmentConfigDAL });
+
+ return {
+ validateRequest: async (ctx) => {
+ const isValid = await validator.validate(ctx.challengePassword, ctx.scepConfigId);
+ return isValid ? { allowed: true } : { allowed: false };
+ }
+ };
+};
diff --git a/backend/src/ee/services/pki-scep/challenge/scep-validation-handler-types.ts b/backend/src/ee/services/pki-scep/challenge/scep-validation-handler-types.ts
new file mode 100644
index 0000000000..6da60aa099
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/challenge/scep-validation-handler-types.ts
@@ -0,0 +1,42 @@
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { TScepDynamicChallengeDALFactory } from "../pki-scep-dynamic-challenge-dal";
+
+export type ScepValidationContext = {
+ challengePassword: string;
+ transactionId: string;
+ csrDer: Buffer;
+ scepConfigId: string;
+ validationConnectionId?: string | null;
+};
+
+export type ScepValidationResult = { allowed: true } | { allowed: false; error?: string };
+
+export type ScepIssuedContext = {
+ transactionId: string;
+ csrDer: Buffer;
+ certificateDer: Buffer;
+ validationConnectionId?: string | null;
+};
+
+export type ScepFailureContext = {
+ transactionId: string;
+ csrDer: Buffer;
+ error?: string;
+ validationConnectionId?: string | null;
+};
+
+export interface IScepValidationHandler {
+ validateRequest(ctx: ScepValidationContext): Promise<ScepValidationResult>;
+ reportIssued?(ctx: ScepIssuedContext): Promise<void>;
+ reportFailure?(ctx: ScepFailureContext): Promise<void>;
+}
+
+export type TScepValidationHandlerDeps = {
+ scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "findById">;
+ scepDynamicChallengeDAL: Pick<TScepDynamicChallengeDALFactory, "consumeByHash">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+};
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
new file mode 100644
index 0000000000..b2cfb70fe3
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.test.ts
@@ -0,0 +1,87 @@
+/* eslint-disable no-bitwise */
+import { webcrypto } from "node:crypto";
+
+import * as x509 from "@peculiar/x509";
+import { beforeAll, describe, expect, test } from "vitest";
+
+import { decodeAsn1ChallengePasswordValue, extractScepChallengePassword } 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 => {
+ const valueBytes = Buffer.from(value, "utf-8");
+ const len = valueBytes.length;
+ if (len < 0x80) {
+ return Uint8Array.from([tag, len, ...valueBytes]);
+ }
+ // Long-form length: 0x80 | number-of-length-bytes, then the big-endian length bytes.
+ const lenBytes: number[] = [];
+ let remaining = len;
+ while (remaining > 0) {
+ lenBytes.unshift(remaining & 0xff);
+ remaining >>= 8;
+ }
+ return Uint8Array.from([tag, 0x80 | lenBytes.length, ...lenBytes, ...valueBytes]);
+};
+
+const UTF8_STRING_TAG = 0x0c;
+const PRINTABLE_STRING_TAG = 0x13;
+
+describe("decodeAsn1ChallengePasswordValue", () => {
+ test("decodes a short-form UTF8String", () => {
+ expect(decodeAsn1ChallengePasswordValue(derString(UTF8_STRING_TAG, "s3cret-pass"))).toBe("s3cret-pass");
+ });
+
+ test("decodes a PrintableString tag the same way", () => {
+ expect(decodeAsn1ChallengePasswordValue(derString(PRINTABLE_STRING_TAG, "abc123"))).toBe("abc123");
+ });
+
+ test("decodes a long-form length (value >= 128 bytes)", () => {
+ const long = "x".repeat(200);
+ expect(decodeAsn1ChallengePasswordValue(derString(UTF8_STRING_TAG, long))).toBe(long);
+ });
+
+ test("accepts an ArrayBuffer as well as a Uint8Array", () => {
+ const u8 = derString(UTF8_STRING_TAG, "buffer-pass");
+ const ab = u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength);
+ expect(decodeAsn1ChallengePasswordValue(ab)).toBe("buffer-pass");
+ });
+
+ test("preserves multibyte UTF-8 content", () => {
+ expect(decodeAsn1ChallengePasswordValue(derString(UTF8_STRING_TAG, "pÄss-wörd-✓"))).toBe("pÄss-wörd-✓");
+ });
+
+ test("returns a plain string input unchanged", () => {
+ expect(decodeAsn1ChallengePasswordValue("already-a-string")).toBe("already-a-string");
+ });
+});
+
+describe("extractScepChallengePassword", () => {
+ beforeAll(() => {
+ x509.cryptoProvider.set(webcrypto as Crypto);
+ });
+
+ const generateCsr = async (attributes: x509.Attribute[]) => {
+ const keys = await webcrypto.subtle.generateKey(
+ { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" },
+ true,
+ ["sign", "verify"]
+ );
+ const csr = await x509.Pkcs10CertificateRequestGenerator.create({
+ name: "CN=scep-device",
+ keys,
+ signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
+ attributes
+ });
+ return new x509.Pkcs10CertificateRequest(csr.rawData);
+ };
+
+ test("extracts the challenge password embedded in a real CSR", async () => {
+ const csr = await generateCsr([new x509.ChallengePasswordAttribute("device-challenge-123")]);
+ expect(extractScepChallengePassword(csr)).toBe("device-challenge-123");
+ });
+
+ test("returns an empty string when the CSR carries no challenge password", async () => {
+ const csr = await generateCsr([]);
+ expect(extractScepChallengePassword(csr)).toBe("");
+ });
+});
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 ecabfbec79..7c240a9af6 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-fns.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.ts
@@ -3,19 +3,57 @@ import RE2 from "re2";
import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate";
import { crypto } from "@app/lib/crypto/cryptography";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { isCertChainValid } from "@app/services/certificate/certificate-fns";
import { CertStatus } from "@app/services/certificate/certificate-types";
+import { TCaSigner } from "@app/services/certificate-authority/ca-signer";
import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
-import { getCaCertChains } from "@app/services/certificate-authority/certificate-authority-fns";
+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 { 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";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
const RA_CERT_VALIDITY_YEARS = 10;
-export const generateRaCertificate = async (
- slug: string
+// PKCS#9 challengePassword attribute OID.
+const CHALLENGE_PASSWORD_OID = "1.2.840.113549.1.9.7";
+
+// @peculiar/x509 returns the challengePassword as a DER-encoded ASN.1 string; strip the tag and length
+// prefix (short- and long-form) to recover the UTF-8 value.
+export const decodeAsn1ChallengePasswordValue = (raw: ArrayBuffer | Uint8Array | string): string => {
+ if (raw instanceof ArrayBuffer || raw instanceof Uint8Array) {
+ const buf = Buffer.from(raw);
+ let offset = 1; // skip the ASN.1 tag byte
+ // eslint-disable-next-line no-bitwise
+ if (buf[offset] & 0x80) {
+ // Long-form length: the low 7 bits give the count of subsequent length bytes.
+ // eslint-disable-next-line no-bitwise
+ const numLenBytes = buf[offset] & 0x7f;
+ offset += 1 + numLenBytes;
+ } else {
+ offset += 1;
+ }
+ return buf.subarray(offset).toString("utf-8");
+ }
+ if (typeof raw === "string") return raw;
+ return String(raw);
+};
+
+export const extractScepChallengePassword = (csrObj: x509.Pkcs10CertificateRequest): string => {
+ const challengeAttr = csrObj.attributes.find((attr) => attr.type === CHALLENGE_PASSWORD_OID);
+ if (!challengeAttr?.values?.length) return "";
+ return decodeAsn1ChallengePasswordValue(challengeAttr.values[0] as unknown as ArrayBuffer | Uint8Array | string);
+};
+
+const buildRaCertificate = async (
+ slug: string,
+ issuer?: { signer: TCaSigner; caCertificate: x509.X509Certificate }
): Promise<{
privateKeyDer: ArrayBuffer;
certificatePem: string;
@@ -35,20 +73,41 @@ export const generateRaCertificate = async (
const now = new Date();
const notAfter = new Date(now);
notAfter.setFullYear(notAfter.getFullYear() + RA_CERT_VALIDITY_YEARS);
+ const serialNumber = crypto.randomBytes(16).toString("hex");
+ const subjectName = `CN=Infisical SCEP RA - ${slug}`;
- const cert = await x509.X509CertificateGenerator.createSelfSigned({
- serialNumber: crypto.randomBytes(16).toString("hex"),
- name: `CN=Infisical SCEP RA - ${slug}`,
- notBefore: now,
- notAfter,
- signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
- keys: keyPair,
- extensions: [
- // eslint-disable-next-line no-bitwise
- new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment, true),
- new x509.BasicConstraintsExtension(false, undefined, true)
- ]
- });
+ let cert: x509.X509Certificate;
+ if (issuer) {
+ cert = await issuer.signer.createCertificate({
+ serialNumber,
+ subject: subjectName,
+ issuer: issuer.caCertificate.subject,
+ notBefore: now,
+ notAfter,
+ publicKey: keyPair.publicKey,
+ extensions: [
+ // eslint-disable-next-line no-bitwise
+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment, true),
+ new x509.BasicConstraintsExtension(false, undefined, true),
+ await x509.AuthorityKeyIdentifierExtension.create(issuer.caCertificate, false),
+ await x509.SubjectKeyIdentifierExtension.create(keyPair.publicKey)
+ ]
+ });
+ } else {
+ cert = await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber,
+ name: subjectName,
+ notBefore: now,
+ notAfter,
+ signingAlgorithm: { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
+ keys: keyPair,
+ extensions: [
+ // eslint-disable-next-line no-bitwise
+ new x509.KeyUsagesExtension(x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment, true),
+ new x509.BasicConstraintsExtension(false, undefined, true)
+ ]
+ });
+ }
const privateKeyDer = await crypto.nativeCrypto.subtle.exportKey("pkcs8", keyPair.privateKey);
@@ -59,6 +118,131 @@ export const generateRaCertificate = async (
};
};
+type TGenerateScepRaCertificateDeps = {
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
+ kmsService: Parameters<typeof getCaCertChains>[0]["kmsService"] &
+ Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey">;
+ hsmConnectorService: THsmConnectorServiceFactory;
+};
+
+// Whether Infisical can CA-sign the SCEP RA for a CA type so it chains to the CA (RFC 8894).
+export const SCEP_RA_CA_SIGNING_SUPPORTED_BY_CA_TYPE: Record<CaType, boolean> = {
+ [CaType.INTERNAL]: true,
+ [CaType.AWS_PCA]: false,
+ [CaType.ADCS]: false,
+ [CaType.AZURE_AD_CS]: false,
+ [CaType.VENAFI_TPP]: false,
+ [CaType.ACME]: false,
+ [CaType.DIGICERT]: false,
+ [CaType.GODADDY]: false,
+ [CaType.AWS_ACM_PUBLIC_CA]: false
+};
+
+export const isScepRaCaSigningSupported = (caType: CaType): boolean =>
+ SCEP_RA_CA_SIGNING_SUPPORTED_BY_CA_TYPE[caType] ?? false;
+
+export const resolveScepRaSigning = async ({
+ caId,
+ requestedSignRaWithCa,
+ certificateAuthorityDAL
+}: {
+ caId?: string | null;
+ requestedSignRaWithCa?: boolean;
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;
+}): Promise<{ signRaWithCa: boolean; raCaSigningSupported: boolean; caType: CaType }> => {
+ const ca = caId ? await certificateAuthorityDAL.findByIdWithAssociatedCa(caId) : null;
+ const caType = (ca?.externalCa?.type as CaType) ?? CaType.INTERNAL;
+ const raCaSigningSupported = isScepRaCaSigningSupported(caType);
+ if (requestedSignRaWithCa === true && !raCaSigningSupported) {
+ throw new BadRequestError({
+ message: `CA-signed SCEP RA certificates are not supported for '${caType}' certificate authorities.`
+ });
+ }
+ return { signRaWithCa: requestedSignRaWithCa ?? false, raCaSigningSupported, caType };
+};
+
+const buildCaSignedRaCertificate = async (slug: string, caId: string, deps: TGenerateScepRaCertificateDeps) => {
+ const { signer } = await getCaSigner({
+ caId,
+ certificateAuthorityDAL: deps.certificateAuthorityDAL,
+ certificateAuthoritySecretDAL: deps.certificateAuthoritySecretDAL,
+ projectDAL: deps.projectDAL,
+ kmsService: deps.kmsService,
+ hsmConnectorService: deps.hsmConnectorService
+ });
+
+ const chains = await getCaCertChains({
+ caId,
+ certificateAuthorityDAL: deps.certificateAuthorityDAL,
+ certificateAuthorityCertDAL: deps.certificateAuthorityCertDAL,
+ projectDAL: deps.projectDAL,
+ kmsService: deps.kmsService
+ });
+ const activeChain = chains[chains.length - 1];
+ if (!activeChain) {
+ throw new BadRequestError({ message: "Certificate Authority has no active certificate to sign the SCEP RA cert" });
+ }
+ const caCertificate = new x509.X509Certificate(activeChain.certificate);
+
+ return buildRaCertificate(slug, { signer, caCertificate });
+};
+
+const generateScepRaCertificate = async ({
+ slug,
+ caId,
+ signRaWithCa,
+ deps
+}: {
+ slug: string;
+ caId?: string | null;
+ signRaWithCa: boolean;
+ deps: TGenerateScepRaCertificateDeps;
+}) => {
+ if (!caId || !signRaWithCa) {
+ return buildRaCertificate(slug);
+ }
+
+ const ca = await deps.certificateAuthorityDAL.findByIdWithAssociatedCa(caId);
+ const caType = (ca?.externalCa?.type as CaType) ?? CaType.INTERNAL;
+ if (!isScepRaCaSigningSupported(caType)) {
+ logger.warn(
+ `SCEP RA CA-signing requested for unsupported CA type '${caType}'; using a self-signed RA [caId=${caId}]`
+ );
+ return buildRaCertificate(slug);
+ }
+
+ return buildCaSignedRaCertificate(slug, caId, deps);
+};
+
+export const generateAndEncryptScepRaCertificate = async ({
+ slug,
+ caId,
+ signRaWithCa,
+ projectId,
+ deps
+}: {
+ slug: string;
+ caId?: string | null;
+ signRaWithCa: boolean;
+ projectId: string;
+ deps: TGenerateScepRaCertificateDeps;
+}): Promise<{ certificatePem: string; expiresAt: Date; encryptedPrivateKey: Buffer }> => {
+ const raCert = await generateScepRaCertificate({ slug, caId, signRaWithCa, deps });
+
+ const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
+ projectId,
+ projectDAL: deps.projectDAL,
+ kmsService: deps.kmsService
+ });
+ const kmsEncryptor = await deps.kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });
+ const { cipherTextBlob } = await kmsEncryptor({ plainText: Buffer.from(raCert.privateKeyDer) });
+
+ return { certificatePem: raCert.certificatePem, expiresAt: raCert.expiresAt, encryptedPrivateKey: cipherTextBlob };
+};
+
export const isSignerCertIssuedByCa = async ({
signerCertDer,
signerCert: providedSignerCert,
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 95e5ac0350..cd95a9217e 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts
@@ -15,6 +15,8 @@ import {
import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { ActorType } from "@app/services/auth/auth-type";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
@@ -48,10 +50,11 @@ import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns
import { EventType, TAuditLogServiceFactory } from "../audit-log/audit-log-types";
import { convertRawCertsToPkcs7 } from "../certificate-est/certificate-est-fns";
import { TLicenseServiceFactory } from "../license/license-service";
-import { getScepChallengeValidator, ScepChallengeType } from "./challenge";
+import { getScepValidationHandler, ScepChallengeType } from "./challenge";
import { TScepDynamicChallengeDALFactory } from "./pki-scep-dynamic-challenge-dal";
import {
evaluateScepRenewalAuthorization,
+ extractScepChallengePassword,
getScepCapabilities,
isSignerCertIssuedByCa,
ScepRenewalDenyReason,
@@ -82,7 +85,8 @@ type TPkiScepServiceFactoryDep = {
certificateRequestDAL: Pick<TCertificateRequestDALFactory, "findById">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
- kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
+ kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
certificatePolicyDAL: Pick<TCertificatePolicyDALFactory, "findById">;
certificatePolicyService: Pick<TCertificatePolicyServiceFactory, "validateCertificateRequest">;
@@ -110,6 +114,7 @@ export const pkiScepServiceFactory = ({
certificateBodyDAL,
projectDAL,
kmsService,
+ appConnectionDAL,
licenseService,
certificatePolicyDAL,
certificatePolicyService,
@@ -356,42 +361,48 @@ export const pkiScepServiceFactory = ({
}
const csrObj = new x509.Pkcs10CertificateRequest(parsed.csr);
- const challengePasswordOid = "1.2.840.113549.1.9.7"; // PKCS#9 challengePassword
- const challengeAttr = csrObj.attributes.find((attr) => attr.type === challengePasswordOid);
-
- let challengePassword = "";
- if (challengeAttr && challengeAttr.values && challengeAttr.values.length > 0) {
- // The challengePassword is typically a UTF8String or PrintableString
- // @peculiar/x509 returns ASN.1 ArrayBuffer values
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
- const raw = challengeAttr.values[0] as any;
- if (raw instanceof ArrayBuffer || raw instanceof Uint8Array) {
- // The value is DER-encoded ASN.1 string
- // Strip the tag+length to get the actual string bytes
- const buf = Buffer.from(raw);
- // ASN.1 string: tag (1 byte) + length (1+ bytes) + value
- let offset = 1; // skip tag
- // eslint-disable-next-line no-bitwise
- if (buf[offset] & 0x80) {
- // eslint-disable-next-line no-bitwise
- const numLenBytes = buf[offset] & 0x7f;
- offset += 1 + numLenBytes;
- } else {
- offset += 1;
+ const challengePassword = extractScepChallengePassword(csrObj);
+
+ const logEnrollmentEvent = (outcome: {
+ status: "success" | "pending" | "failure";
+ failReason?: string;
+ issuedCertificateId?: string;
+ issuedSerialNumber?: string;
+ }) =>
+ auditLogService.createAuditLog({
+ projectId: profile.projectId,
+ actor: { type: ActorType.SCEP_ACCOUNT, metadata: { profileId: profile.id } },
+ event: {
+ type: EventType.SCEP_ENROLLMENT,
+ metadata: {
+ profileId: profile.id,
+ profileSlug: profile.slug,
+ transactionId: parsed.transactionId,
+ csrSubject: csrObj.subject,
+ challengeType: scepConfig.challengeType as ScepChallengeType,
+ clientIp,
+ ...outcome
+ }
}
- challengePassword = buf.subarray(offset).toString("utf-8");
- } else if (typeof raw === "string") {
- challengePassword = raw;
- } else {
- challengePassword = String(raw);
- }
- }
+ });
- const challengeValidator = getScepChallengeValidator(scepConfig.challengeType as ScepChallengeType, {
+ const validationHandler = getScepValidationHandler(scepConfig.challengeType as ScepChallengeType, {
scepEnrollmentConfigDAL,
- scepDynamicChallengeDAL
+ scepDynamicChallengeDAL,
+ appConnectionDAL,
+ kmsService
});
- const isValid = await challengeValidator.validate(challengePassword, scepConfig.id);
+
+ const csrDer = Buffer.from(parsed.csr);
+ const validationResult = await validationHandler.validateRequest({
+ challengePassword,
+ transactionId: parsed.transactionId,
+ csrDer,
+ scepConfigId: scepConfig.id,
+ validationConnectionId: scepConfig.validationConnectionId
+ });
+ const isValid = validationResult.allowed;
+ const denyReason = validationResult.allowed ? undefined : validationResult.error?.slice(0, 500);
if (!isValid) {
// Many SCEP clients (including sscep) send PKCSReq for both initial enrollment
@@ -425,26 +436,7 @@ export const pkiScepServiceFactory = ({
}
}
- void auditLogService.createAuditLog({
- projectId: profile.projectId,
- actor: {
- type: ActorType.SCEP_ACCOUNT,
- metadata: { profileId: profile.id }
- },
- event: {
- type: EventType.SCEP_ENROLLMENT,
- metadata: {
- profileId: profile.id,
- profileSlug: profile.slug,
- transactionId: parsed.transactionId,
- csrSubject: csrObj.subject,
- challengeType: scepConfig.challengeType as ScepChallengeType,
- status: "failure" as const,
- failReason: "Invalid challenge password",
- clientIp
- }
- }
- });
+ void logEnrollmentEvent({ status: "failure", failReason: denyReason || "Invalid challenge password" });
return buildCertRepFailure({
raCertDer,
@@ -456,37 +448,37 @@ export const pkiScepServiceFactory = ({
}
const { ttl } = await resolveIssuanceParams(profile);
- const csrPem = derToPem(Buffer.from(parsed.csr), "CERTIFICATE REQUEST");
+ const csrPem = derToPem(csrDer, "CERTIFICATE REQUEST");
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
- const result = await issueOrQueueCertificate({
- profile,
- project,
- caType,
- parsed,
- csrPem,
- ttl,
- applicationId
- });
-
- const auditMetadata = {
- profileId: profile.id,
- profileSlug: profile.slug,
- transactionId: parsed.transactionId,
- csrSubject: csrObj.subject,
- challengeType: scepConfig.challengeType as ScepChallengeType,
- clientIp
- };
+ let result: TIssuanceResult;
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ result = await issueOrQueueCertificate({
+ profile,
+ project,
+ caType,
+ parsed,
+ csrPem,
+ ttl,
+ applicationId
+ });
+ } catch (err) {
+ // Notify the validator that post-validation issuance failed.
+ await validationHandler
+ .reportFailure?.({
+ transactionId: parsed.transactionId,
+ csrDer,
+ error: err instanceof Error ? err.message : "Certificate issuance failed",
+ validationConnectionId: scepConfig.validationConnectionId
+ })
+ .catch((reportErr) =>
+ logger.error(reportErr, `Failed to report SCEP issuance failure [transactionId=${parsed.transactionId}]`)
+ );
+ throw err;
+ }
if (result.status === "pending") {
- void auditLogService.createAuditLog({
- projectId: profile.projectId,
- actor: { type: ActorType.SCEP_ACCOUNT, metadata: { profileId: profile.id } },
- event: {
- type: EventType.SCEP_ENROLLMENT,
- metadata: { ...auditMetadata, status: "pending" as const }
- }
- });
+ void logEnrollmentEvent({ status: "pending" });
return buildCertRepPending({
raCertDer,
@@ -496,20 +488,24 @@ export const pkiScepServiceFactory = ({
});
}
- void auditLogService.createAuditLog({
- projectId: profile.projectId,
- actor: { type: ActorType.SCEP_ACCOUNT, metadata: { profileId: profile.id } },
- event: {
- type: EventType.SCEP_ENROLLMENT,
- metadata: {
- ...auditMetadata,
- status: "success" as const,
- issuedCertificateId: result.certificateId,
- issuedSerialNumber: result.serialNumber
- }
- }
+ void logEnrollmentEvent({
+ status: "success",
+ issuedCertificateId: result.certificateId,
+ issuedSerialNumber: result.serialNumber
});
+ // Notify the validator of the issued cert.
+ await validationHandler
+ .reportIssued?.({
+ transactionId: parsed.transactionId,
+ csrDer,
+ certificateDer: result.issuedCertDer,
+ validationConnectionId: scepConfig.validationConnectionId
+ })
+ .catch((reportErr) =>
+ logger.error(reportErr, `Failed to report SCEP issuance success [transactionId=${parsed.transactionId}]`)
+ );
+
return buildCertRepSuccess({
issuedCertDer: result.issuedCertDer,
recipientCertDer: parsed.signerCertDer,
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 02dd7b5089..c25bad1e33 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1644,26 +1644,6 @@ export const registerRoutes = async (
permissionService
});
- const certificateProfileService = certificateProfileServiceFactory({
- certificateProfileDAL,
- certificatePolicyDAL,
- certificatePolicyService,
- apiEnrollmentConfigDAL,
- estEnrollmentConfigDAL,
- acmeEnrollmentConfigDAL,
- scepEnrollmentConfigDAL,
- scepDynamicChallengeDAL,
- certificateBodyDAL,
- certificateSecretDAL,
- certificateAuthorityDAL,
- externalCertificateAuthorityDAL,
- permissionService,
- kmsService,
- projectDAL,
- resourceMetadataDAL,
- pkiApplicationProfileDAL
- });
-
const pkiApplicationService = pkiApplicationServiceFactory({
pkiApplicationDAL,
pkiApplicationProfileDAL,
@@ -1739,18 +1719,6 @@ export const registerRoutes = async (
permissionService
});
- const pkiApplicationEnrollmentService = pkiApplicationEnrollmentServiceFactory({
- pkiApplicationDAL,
- pkiApplicationProfileDAL,
- apiEnrollmentConfigDAL,
- estEnrollmentConfigDAL,
- acmeEnrollmentConfigDAL,
- scepEnrollmentConfigDAL,
- kmsService,
- projectDAL,
- permissionService
- });
-
const pkiAlertService = pkiAlertServiceFactory({
pkiAlertDAL,
pkiCollectionDAL,
@@ -2940,6 +2908,47 @@ export const registerRoutes = async (
licenseService
});
+ const certificateProfileService = certificateProfileServiceFactory({
+ certificateProfileDAL,
+ certificatePolicyDAL,
+ certificatePolicyService,
+ apiEnrollmentConfigDAL,
+ estEnrollmentConfigDAL,
+ acmeEnrollmentConfigDAL,
+ scepEnrollmentConfigDAL,
+ scepDynamicChallengeDAL,
+ certificateBodyDAL,
+ certificateSecretDAL,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ certificateAuthorityCertDAL,
+ hsmConnectorService,
+ externalCertificateAuthorityDAL,
+ permissionService,
+ kmsService,
+ projectDAL,
+ resourceMetadataDAL,
+ pkiApplicationProfileDAL
+ });
+
+ const pkiApplicationEnrollmentService = pkiApplicationEnrollmentServiceFactory({
+ pkiApplicationDAL,
+ pkiApplicationProfileDAL,
+ apiEnrollmentConfigDAL,
+ estEnrollmentConfigDAL,
+ acmeEnrollmentConfigDAL,
+ scepEnrollmentConfigDAL,
+ appConnectionDAL,
+ certificateProfileDAL,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ certificateAuthorityCertDAL,
+ hsmConnectorService,
+ kmsService,
+ projectDAL,
+ permissionService
+ });
+
const honeyTokenConfigService = honeyTokenConfigServiceFactory({
honeyTokenConfigDAL,
permissionService,
@@ -3499,6 +3508,7 @@ export const registerRoutes = async (
certificateBodyDAL,
projectDAL,
kmsService,
+ appConnectionDAL,
licenseService,
certificatePolicyDAL,
certificatePolicyService,
diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
index b58c3889bf..ead96ef29f 100644
--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-router.ts
@@ -150,6 +150,10 @@ import {
LiteLLMConnectionListItemSchema,
SanitizedLiteLLMConnectionSchema
} from "@app/services/app-connection/litellm";
+import {
+ MicrosoftIntuneConnectionListItemSchema,
+ SanitizedMicrosoftIntuneConnectionSchema
+} from "@app/services/app-connection/microsoft-intune";
import {
MongoDBConnectionListItemSchema,
SanitizedMongoDBConnectionSchema
@@ -311,6 +315,7 @@ const SanitizedAppConnectionSchema = z.union([
...SanitizedAnthropicConnectionSchema.options,
...SanitizedDevinConnectionSchema.options,
...SanitizedAzureEntraIdConnectionSchema.options,
+ ...SanitizedMicrosoftIntuneConnectionSchema.options,
...SanitizedVenafiConnectionSchema.options,
...SanitizedVenafiTppConnectionSchema.options,
...SanitizedExternalInfisicalConnectionSchema.options,
@@ -392,6 +397,7 @@ const AppConnectionOptionsSchema = z.discriminatedUnion("app", [
OpenRouterConnectionListItemSchema,
OpenAIConnectionListItemSchema,
AzureEntraIdConnectionListItemSchema,
+ MicrosoftIntuneConnectionListItemSchema,
VenafiConnectionListItemSchema,
VenafiTppConnectionListItemSchema,
ExternalInfisicalConnectionListItemSchema,
diff --git a/backend/src/server/routes/v1/app-connection-routers/index.ts b/backend/src/server/routes/v1/app-connection-routers/index.ts
index d90f5d1645..93fc6a53cf 100644
--- a/backend/src/server/routes/v1/app-connection-routers/index.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/index.ts
@@ -46,6 +46,7 @@ import { registerHumanitecConnectionRouter } from "./humanitec-connection-router
import { registerLaravelForgeConnectionRouter } from "./laravel-forge-connection-router";
import { registerLdapConnectionRouter } from "./ldap-connection-router";
import { registerLiteLLMConnectionRouter } from "./litellm-connection-router";
+import { registerMicrosoftIntuneConnectionRouter } from "./microsoft-intune-connection-router";
import { registerMongoDBConnectionRouter } from "./mongodb-connection-router";
import { registerMsSqlConnectionRouter } from "./mssql-connection-router";
import { registerMySqlConnectionRouter } from "./mysql-connection-router";
@@ -142,6 +143,7 @@ export const APP_CONNECTION_REGISTER_ROUTER_MAP: Record<AppConnection, (server:
[AppConnection.CircleCI]: registerCircleCIConnectionRouter,
[AppConnection.Cloud66]: registerCloud66ConnectionRouter,
[AppConnection.AzureEntraId]: registerAzureEntraIdConnectionRouter,
+ [AppConnection.MicrosoftIntune]: registerMicrosoftIntuneConnectionRouter,
[AppConnection.Venafi]: registerVenafiConnectionRouter,
[AppConnection.VenafiTpp]: registerVenafiTppConnectionRouter,
[AppConnection.ExternalInfisical]: registerExternalInfisicalConnectionRouter,
diff --git a/backend/src/server/routes/v1/app-connection-routers/microsoft-intune-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/microsoft-intune-connection-router.ts
new file mode 100644
index 0000000000..31f7ba7966
--- /dev/null
+++ b/backend/src/server/routes/v1/app-connection-routers/microsoft-intune-connection-router.ts
@@ -0,0 +1,18 @@
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import {
+ CreateMicrosoftIntuneConnectionSchema,
+ SanitizedMicrosoftIntuneConnectionSchema,
+ UpdateMicrosoftIntuneConnectionSchema
+} from "@app/services/app-connection/microsoft-intune";
+
+import { registerAppConnectionEndpoints } from "./app-connection-endpoints";
+
+export const registerMicrosoftIntuneConnectionRouter = async (server: FastifyZodProvider) => {
+ registerAppConnectionEndpoints({
+ app: AppConnection.MicrosoftIntune,
+ server,
+ sanitizedResponseSchema: SanitizedMicrosoftIntuneConnectionSchema,
+ createSchema: CreateMicrosoftIntuneConnectionSchema,
+ updateSchema: UpdateMicrosoftIntuneConnectionSchema
+ });
+};
diff --git a/backend/src/server/routes/v1/pki-application-enrollment-routers/enrollment-state-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-routers/enrollment-state-router.ts
index 5076be249e..868bba88bf 100644
--- a/backend/src/server/routes/v1/pki-application-enrollment-routers/enrollment-state-router.ts
+++ b/backend/src/server/routes/v1/pki-application-enrollment-routers/enrollment-state-router.ts
@@ -6,6 +6,7 @@ import { ApiDocsTags } from "@app/lib/api-docs";
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
+import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
const ApiEnrollmentSchema = z.object({
id: z.string().uuid(),
@@ -36,7 +37,9 @@ const ScepEnrollmentStateSchema = z.object({
scepEndpointUrl: z.string(),
challengeEndpointUrl: z.string().nullable(),
raCertificatePem: z.string(),
- raCertExpiresAt: z.date()
+ raCertExpiresAt: z.date(),
+ validationConnectionId: z.string().uuid().nullable(),
+ signRaWithCa: z.boolean()
});
const EnrollmentStateSchema = z.object({
@@ -46,6 +49,8 @@ const EnrollmentStateSchema = z.object({
est: EstEnrollmentStateSchema.nullable(),
acme: AcmeEnrollmentStateSchema.nullable(),
scep: ScepEnrollmentStateSchema.nullable(),
+ raCaSigningSupported: z.boolean(),
+ caType: z.nativeEnum(CaType),
estConfigured: z.boolean(),
acmeConfigured: z.boolean(),
scepConfigured: z.boolean()
diff --git a/backend/src/server/routes/v1/pki-application-enrollment-routers/scep-enrollment-router.ts b/backend/src/server/routes/v1/pki-application-enrollment-routers/scep-enrollment-router.ts
index cb64300e4d..e0069af51a 100644
--- a/backend/src/server/routes/v1/pki-application-enrollment-routers/scep-enrollment-router.ts
+++ b/backend/src/server/routes/v1/pki-application-enrollment-routers/scep-enrollment-router.ts
@@ -26,7 +26,9 @@ export const registerPkiApplicationScepEnrollmentRouter = async (server: Fastify
includeCaCertInResponse: z.boolean().optional().default(true),
allowCertBasedRenewal: z.boolean().optional().default(true),
dynamicChallengeExpiryMinutes: z.number().int().min(5).max(1440).optional(),
- dynamicChallengeMaxPending: z.number().int().min(1).max(1000).optional()
+ dynamicChallengeMaxPending: z.number().int().min(1).max(1000).optional(),
+ validationConnectionId: z.string().uuid().optional(),
+ signRaWithCa: z.boolean().optional()
}),
response: {
200: z.object({
@@ -56,7 +58,12 @@ export const registerPkiApplicationScepEnrollmentRouter = async (server: Fastify
metadata: {
applicationId: req.params.applicationId,
profileId: req.params.profileId,
- challengeType: result.scep.challengeType
+ challengeType: result.scep.challengeType,
+ signRaWithCa: result.signRaWithCa,
+ ...(result.validationConnection && {
+ validationConnectionId: result.validationConnection.id,
+ validationConnectionName: result.validationConnection.name ?? undefined
+ })
}
}
});
diff --git a/backend/src/services/app-connection/app-connection-enums.ts b/backend/src/services/app-connection/app-connection-enums.ts
index b3b0ef2d29..9607a72927 100644
--- a/backend/src/services/app-connection/app-connection-enums.ts
+++ b/backend/src/services/app-connection/app-connection-enums.ts
@@ -78,7 +78,8 @@ export enum AppConnection {
Cloud66 = "cloud-66",
LiteLLM = "litellm",
Fireworks = "fireworks",
- NutanixPrismCentral = "nutanix-prism-central"
+ NutanixPrismCentral = "nutanix-prism-central",
+ MicrosoftIntune = "microsoft-intune"
}
export enum AWSRegion {
diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts
index eb6e31076c..3d90358f54 100644
--- a/backend/src/services/app-connection/app-connection-fns.ts
+++ b/backend/src/services/app-connection/app-connection-fns.ts
@@ -194,6 +194,11 @@ import {
} from "./laravel-forge";
import { getLdapConnectionListItem, LdapConnectionMethod, validateLdapConnectionCredentials } from "./ldap";
import { getLiteLLMConnectionListItem, LiteLLMConnectionMethod, validateLiteLLMConnectionCredentials } from "./litellm";
+import {
+ getMicrosoftIntuneConnectionListItem,
+ MicrosoftIntuneConnectionMethod,
+ validateMicrosoftIntuneConnectionCredentials
+} from "./microsoft-intune";
import { getMongoDBConnectionListItem, MongoDBConnectionMethod, validateMongoDBConnectionCredentials } from "./mongodb";
import { getMsSqlConnectionListItem, MsSqlConnectionMethod } from "./mssql";
import { MySqlConnectionMethod } from "./mysql/mysql-connection-enums";
@@ -319,7 +324,8 @@ const PKI_APP_CONNECTIONS = [
AppConnection.GoDaddy,
AppConnection.SSH,
AppConnection.WinRM,
- AppConnection.NutanixPrismCentral
+ AppConnection.NutanixPrismCentral,
+ AppConnection.MicrosoftIntune
];
export const listAppConnectionOptions = (projectType?: ProjectType) => {
@@ -384,6 +390,7 @@ export const listAppConnectionOptions = (projectType?: ProjectType) => {
getCircleCIConnectionListItem(),
getCloud66ConnectionListItem(),
getAzureEntraIdConnectionListItem(),
+ getMicrosoftIntuneConnectionListItem(),
getVenafiConnectionListItem(),
getVenafiTppConnectionListItem(),
getExternalInfisicalConnectionListItem(),
@@ -627,6 +634,7 @@ export const validateAppConnectionCredentials = async (
[AppConnection.CircleCI]: validateCircleCIConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Cloud66]: validateCloud66ConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.AzureEntraId]: validateAzureEntraIdConnectionCredentials as TAppConnectionCredentialsValidator,
+ [AppConnection.MicrosoftIntune]: validateMicrosoftIntuneConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.Venafi]: validateVenafiConnectionCredentials as TAppConnectionCredentialsValidator,
[AppConnection.VenafiTpp]: ((config: TAppConnectionConfig) =>
validateVenafiTppConnectionCredentials(
@@ -714,6 +722,7 @@ export const getAppConnectionMethodName = (method: TAppConnection["method"]) =>
return "API Key & Secret";
case AzureDnsConnectionMethod.ClientSecret:
case AzureEntraIdConnectionMethod.ClientSecret:
+ case MicrosoftIntuneConnectionMethod.ClientSecret:
return "Client Secret";
case PostgresConnectionMethod.UsernameAndPassword:
case MsSqlConnectionMethod.UsernameAndPassword:
@@ -900,6 +909,7 @@ export const TRANSITION_CONNECTION_CREDENTIALS_TO_PLATFORM: Record<
[AppConnection.CircleCI]: platformManagedCredentialsNotSupported,
[AppConnection.Cloud66]: platformManagedCredentialsNotSupported,
[AppConnection.AzureEntraId]: platformManagedCredentialsNotSupported,
+ [AppConnection.MicrosoftIntune]: platformManagedCredentialsNotSupported,
[AppConnection.Venafi]: platformManagedCredentialsNotSupported,
[AppConnection.VenafiTpp]: platformManagedCredentialsNotSupported,
[AppConnection.ExternalInfisical]: platformManagedCredentialsNotSupported,
diff --git a/backend/src/services/app-connection/app-connection-maps.ts b/backend/src/services/app-connection/app-connection-maps.ts
index d6302baf3b..386a7ce943 100644
--- a/backend/src/services/app-connection/app-connection-maps.ts
+++ b/backend/src/services/app-connection/app-connection-maps.ts
@@ -80,7 +80,8 @@ export const APP_CONNECTION_NAME_MAP: Record<AppConnection, string> = {
[AppConnection.Cloud66]: "Cloud 66",
[AppConnection.LiteLLM]: "LiteLLM",
[AppConnection.Fireworks]: "Fireworks",
- [AppConnection.NutanixPrismCentral]: "Nutanix Prism Central"
+ [AppConnection.NutanixPrismCentral]: "Nutanix Prism Central",
+ [AppConnection.MicrosoftIntune]: "Microsoft Intune"
};
export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanType> = {
@@ -163,5 +164,6 @@ export const APP_CONNECTION_PLAN_MAP: Record<AppConnection, AppConnectionPlanTyp
[AppConnection.Cloud66]: AppConnectionPlanType.Regular,
[AppConnection.LiteLLM]: AppConnectionPlanType.Regular,
[AppConnection.Fireworks]: AppConnectionPlanType.Regular,
- [AppConnection.NutanixPrismCentral]: AppConnectionPlanType.Regular
+ [AppConnection.NutanixPrismCentral]: AppConnectionPlanType.Regular,
+ [AppConnection.MicrosoftIntune]: AppConnectionPlanType.Regular
};
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index 0f7f85e50d..f7194e612c 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -136,6 +136,7 @@ import { laravelForgeConnectionService } from "./laravel-forge/laravel-forge-con
import { ValidateLdapConnectionCredentialsSchema } from "./ldap";
import { ValidateLiteLLMConnectionCredentialsSchema } from "./litellm";
import { liteLLMConnectionService } from "./litellm/litellm-connection-service";
+import { ValidateMicrosoftIntuneConnectionCredentialsSchema } from "./microsoft-intune";
import { ValidateMongoDBConnectionCredentialsSchema } from "./mongodb";
import { ValidateMsSqlConnectionCredentialsSchema } from "./mssql";
import { ValidateMySqlConnectionCredentialsSchema } from "./mysql";
@@ -276,6 +277,7 @@ const VALIDATE_APP_CONNECTION_CREDENTIALS_MAP: Record<AppConnection, TValidateAp
[AppConnection.CircleCI]: ValidateCircleCIConnectionCredentialsSchema,
[AppConnection.Cloud66]: ValidateCloud66ConnectionCredentialsSchema,
[AppConnection.AzureEntraId]: ValidateAzureEntraIdConnectionCredentialsSchema,
+ [AppConnection.MicrosoftIntune]: ValidateMicrosoftIntuneConnectionCredentialsSchema,
[AppConnection.Venafi]: ValidateVenafiConnectionCredentialsSchema,
[AppConnection.VenafiTpp]: ValidateVenafiTppConnectionCredentialsSchema,
[AppConnection.ExternalInfisical]: ValidateExternalInfisicalConnectionCredentialsSchema,
diff --git a/backend/src/services/app-connection/app-connection-types.ts b/backend/src/services/app-connection/app-connection-types.ts
index 639e9ab97b..e91758dc54 100644
--- a/backend/src/services/app-connection/app-connection-types.ts
+++ b/backend/src/services/app-connection/app-connection-types.ts
@@ -280,6 +280,12 @@ import {
TLiteLLMConnectionInput,
TValidateLiteLLMConnectionCredentialsSchema
} from "./litellm";
+import {
+ TMicrosoftIntuneConnection,
+ TMicrosoftIntuneConnectionConfig,
+ TMicrosoftIntuneConnectionInput,
+ TValidateMicrosoftIntuneConnectionCredentialsSchema
+} from "./microsoft-intune/microsoft-intune-connection-types";
import {
TMongoDBConnection,
TMongoDBConnectionConfig,
@@ -534,6 +540,7 @@ export type TAppConnection = { id: string; configuration?: TAppConnectionConfigu
| TCircleCIConnection
| TCloud66Connection
| TAzureEntraIdConnection
+ | TMicrosoftIntuneConnection
| TVenafiConnection
| TVenafiTppConnection
| TExternalInfisicalConnection
@@ -625,6 +632,7 @@ export type TAppConnectionInput = { id: string } & (
| TCircleCIConnectionInput
| TCloud66ConnectionInput
| TAzureEntraIdConnectionInput
+ | TMicrosoftIntuneConnectionInput
| TVenafiConnectionInput
| TVenafiTppConnectionInput
| TExternalInfisicalConnectionInput
@@ -748,6 +756,7 @@ export type TAppConnectionConfig =
| TCircleCIConnectionConfig
| TCloud66ConnectionConfig
| TAzureEntraIdConnectionConfig
+ | TMicrosoftIntuneConnectionConfig
| TVenafiConnectionConfig
| TVenafiTppConnectionConfig
| TExternalInfisicalConnectionConfig
@@ -830,6 +839,7 @@ export type TValidateAppConnectionCredentialsSchema =
| TValidateCircleCIConnectionCredentialsSchema
| TValidateCloud66ConnectionCredentialsSchema
| TValidateAzureEntraIdConnectionCredentialsSchema
+ | TValidateMicrosoftIntuneConnectionCredentialsSchema
| TValidateVenafiConnectionCredentialsSchema
| TValidateVenafiTppConnectionCredentialsSchema
| TValidateExternalInfisicalConnectionCredentialsSchema
diff --git a/backend/src/services/app-connection/microsoft-intune/index.ts b/backend/src/services/app-connection/microsoft-intune/index.ts
new file mode 100644
index 0000000000..4314744bac
--- /dev/null
+++ b/backend/src/services/app-connection/microsoft-intune/index.ts
@@ -0,0 +1,4 @@
+export * from "./microsoft-intune-connection-enums";
+export * from "./microsoft-intune-connection-fns";
+export * from "./microsoft-intune-connection-schemas";
+export * from "./microsoft-intune-connection-types";
diff --git a/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-enums.ts b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-enums.ts
new file mode 100644
index 0000000000..d32497459f
--- /dev/null
+++ b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-enums.ts
@@ -0,0 +1,3 @@
+export enum MicrosoftIntuneConnectionMethod {
+ ClientSecret = "client-secret"
+}
diff --git a/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-fns.ts b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-fns.ts
new file mode 100644
index 0000000000..4727a867b4
--- /dev/null
+++ b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-fns.ts
@@ -0,0 +1,218 @@
+import { AxiosError } from "axios";
+import { randomUUID } from "crypto";
+
+import { request } from "@app/lib/config/request";
+import { BadRequestError, InternalServerError } from "@app/lib/errors";
+import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+
+import { AppConnection } from "../app-connection-enums";
+import { MicrosoftIntuneConnectionMethod } from "./microsoft-intune-connection-enums";
+import {
+ TIntuneScepValidationResponse,
+ TMicrosoftEntraTokenResponse,
+ TMicrosoftGraphServicePrincipalEndpointsResponse,
+ TMicrosoftIntuneConnectionConfig,
+ TMicrosoftIntuneConnectionCredentials
+} from "./microsoft-intune-connection-types";
+
+// Intune's well-known first-party app id; its service principal exposes the SCEP validation endpoint.
+const INTUNE_WELL_KNOWN_APP_ID = "0000000a-0000-0000-c000-000000000000";
+const SCEP_VALIDATION_SERVICE_NAME = "ScepRequestValidationFEService";
+const INTUNE_API_VERSION = "2018-02-20";
+// Intune returns this (case-insensitively) in the `code` field when a SCEP request passes validation.
+const INTUNE_SUCCESS_CODE = "success";
+
+export const MicrosoftEntraTokenResource = {
+ Graph: "https://graph.microsoft.com/.default",
+ Intune: "https://api.manage.microsoft.com/.default"
+} as const;
+
+// Sent to Intune on every call to attribute the request.
+export const INTUNE_CALLER_INFO = "Infisical";
+
+export const getMicrosoftIntuneConnectionListItem = () => {
+ return {
+ name: "Microsoft Intune" as const,
+ app: AppConnection.MicrosoftIntune as const,
+ methods: Object.values(MicrosoftIntuneConnectionMethod) as [MicrosoftIntuneConnectionMethod.ClientSecret]
+ };
+};
+
+export const getMicrosoftEntraToken = async (
+ credentials: Pick<TMicrosoftIntuneConnectionCredentials, "tenantId" | "clientId" | "clientSecret">,
+ scope: string
+) => {
+ const { tenantId, clientId, clientSecret } = credentials;
+
+ try {
+ const { data } = await request.post<TMicrosoftEntraTokenResponse>(
+ IntegrationUrls.AZURE_TOKEN_URL.replace("common", tenantId || "common"),
+ new URLSearchParams({
+ grant_type: "client_credentials",
+ scope,
+ client_id: clientId,
+ client_secret: clientSecret
+ })
+ );
+
+ return data.access_token;
+ } catch (err) {
+ if (err instanceof AxiosError) {
+ throw new BadRequestError({
+ message: `Failed to obtain Microsoft Entra access token: ${
+ (err.response?.data as { error_description?: string })?.error_description || err.message
+ }`
+ });
+ }
+ throw new InternalServerError({ message: "Failed to obtain Microsoft Entra access token" });
+ }
+};
+
+export const discoverScepValidationServiceUri = async (graphAccessToken: string) => {
+ try {
+ const { data } = await request.get<TMicrosoftGraphServicePrincipalEndpointsResponse>(
+ `https://graph.microsoft.com/v1.0/servicePrincipals/appId=${INTUNE_WELL_KNOWN_APP_ID}/endpoints`,
+ {
+ headers: {
+ Authorization: `Bearer ${graphAccessToken}`,
+ Accept: "application/json"
+ }
+ }
+ );
+
+ const endpoint = data.value?.find((e) => e.providerName === SCEP_VALIDATION_SERVICE_NAME);
+ if (!endpoint?.uri) {
+ throw new BadRequestError({
+ message:
+ "Could not locate the Intune SCEP validation service. Ensure the Entra application has the Intune 'scep_challenge_provider' permission with admin consent granted."
+ });
+ }
+
+ return endpoint.uri.replace(/\/+$/, "");
+ } catch (err) {
+ if (err instanceof BadRequestError) throw err;
+ if (err instanceof AxiosError) {
+ throw new BadRequestError({
+ message: `Failed to discover the Intune SCEP validation service: ${
+ (err.response?.data as { error?: { message?: string } })?.error?.message || err.message
+ }`
+ });
+ }
+ throw new InternalServerError({ message: "Failed to discover the Intune SCEP validation service" });
+ }
+};
+
+const intuneScepActionHeaders = (intuneAccessToken: string) => ({
+ Authorization: `Bearer ${intuneAccessToken}`,
+ "Content-Type": "application/json",
+ Accept: "application/json",
+ "api-version": INTUNE_API_VERSION,
+ "client-request-id": randomUUID()
+});
+
+export const intuneValidateScepRequest = async ({
+ intuneAccessToken,
+ serviceUri,
+ transactionId,
+ certificateRequest
+}: {
+ intuneAccessToken: string;
+ serviceUri: string;
+ transactionId: string;
+ certificateRequest: string;
+}): Promise<{ allowed: boolean; errorDescription?: string }> => {
+ try {
+ const { data } = await request.post<TIntuneScepValidationResponse>(
+ `${serviceUri}/ScepActions/validateRequest`,
+ {
+ request: {
+ transactionId,
+ certificateRequest,
+ callerInfo: INTUNE_CALLER_INFO
+ }
+ },
+ { headers: intuneScepActionHeaders(intuneAccessToken) }
+ );
+
+ if (data?.code && data.code.toLowerCase() === INTUNE_SUCCESS_CODE) {
+ return { allowed: true };
+ }
+
+ return { allowed: false, errorDescription: data?.errorDescription || data?.code || "Intune rejected the request" };
+ } catch (err) {
+ if (err instanceof AxiosError) {
+ const body = err.response?.data as TIntuneScepValidationResponse | undefined;
+ return {
+ allowed: false,
+ errorDescription: body?.errorDescription || body?.code || err.message
+ };
+ }
+ return { allowed: false, errorDescription: "Failed to reach the Intune SCEP validation service" };
+ }
+};
+
+export const intuneSendSuccessNotification = async ({
+ intuneAccessToken,
+ serviceUri,
+ notification
+}: {
+ intuneAccessToken: string;
+ serviceUri: string;
+ notification: {
+ transactionId: string;
+ certificateRequest: string;
+ certificateThumbprint: string;
+ certificateSerialNumber: string;
+ certificateExpirationDateUtc: string;
+ issuingCertificateAuthority: string;
+ };
+}) => {
+ await request.post(
+ `${serviceUri}/ScepActions/successNotification`,
+ { notification: { ...notification, callerInfo: INTUNE_CALLER_INFO } },
+ { headers: intuneScepActionHeaders(intuneAccessToken) }
+ );
+};
+
+export const intuneSendFailureNotification = async ({
+ intuneAccessToken,
+ serviceUri,
+ notification
+}: {
+ intuneAccessToken: string;
+ serviceUri: string;
+ notification: {
+ transactionId: string;
+ certificateRequest: string;
+ hResult: number;
+ errorDescription: string;
+ };
+}) => {
+ await request.post(
+ `${serviceUri}/ScepActions/failureNotification`,
+ { notification: { ...notification, callerInfo: INTUNE_CALLER_INFO } },
+ { headers: intuneScepActionHeaders(intuneAccessToken) }
+ );
+};
+
+export const validateMicrosoftIntuneConnectionCredentials = async (config: TMicrosoftIntuneConnectionConfig) => {
+ const { credentials, method } = config;
+
+ switch (method) {
+ case MicrosoftIntuneConnectionMethod.ClientSecret: {
+ const graphToken = await getMicrosoftEntraToken(credentials, MicrosoftEntraTokenResource.Graph);
+ await discoverScepValidationServiceUri(graphToken);
+ await getMicrosoftEntraToken(credentials, MicrosoftEntraTokenResource.Intune);
+
+ return {
+ tenantId: credentials.tenantId,
+ clientId: credentials.clientId,
+ clientSecret: credentials.clientSecret
+ };
+ }
+ default:
+ throw new InternalServerError({
+ message: `Unhandled Microsoft Intune connection method: ${method as MicrosoftIntuneConnectionMethod}`
+ });
+ }
+};
diff --git a/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-schemas.ts b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-schemas.ts
new file mode 100644
index 0000000000..55f346e8bb
--- /dev/null
+++ b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-schemas.ts
@@ -0,0 +1,79 @@
+import { z } from "zod";
+
+import { AppConnections } from "@app/lib/api-docs";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import {
+ BaseAppConnectionSchema,
+ GenericCreateAppConnectionFieldsSchema,
+ GenericUpdateAppConnectionFieldsSchema
+} from "@app/services/app-connection/app-connection-schemas";
+
+import { APP_CONNECTION_NAME_MAP } from "../app-connection-maps";
+import { MicrosoftIntuneConnectionMethod } from "./microsoft-intune-connection-enums";
+
+export const MicrosoftIntuneConnectionClientSecretInputCredentialsSchema = z.object({
+ tenantId: z.string().uuid().trim().min(1, "Tenant ID required"),
+ clientId: z.string().uuid().trim().min(1, "Client ID required"),
+ clientSecret: z.string().trim().min(1, "Client Secret required")
+});
+
+export const MicrosoftIntuneConnectionClientSecretOutputCredentialsSchema = z.object({
+ tenantId: z.string(),
+ clientId: z.string(),
+ clientSecret: z.string()
+});
+
+export const ValidateMicrosoftIntuneConnectionCredentialsSchema = z.discriminatedUnion("method", [
+ z.object({
+ method: z
+ .literal(MicrosoftIntuneConnectionMethod.ClientSecret)
+ .describe(AppConnections.CREATE(AppConnection.MicrosoftIntune).method),
+ credentials: MicrosoftIntuneConnectionClientSecretInputCredentialsSchema.describe(
+ AppConnections.CREATE(AppConnection.MicrosoftIntune).credentials
+ )
+ })
+]);
+
+export const CreateMicrosoftIntuneConnectionSchema = ValidateMicrosoftIntuneConnectionCredentialsSchema.and(
+ GenericCreateAppConnectionFieldsSchema(AppConnection.MicrosoftIntune)
+);
+
+export const UpdateMicrosoftIntuneConnectionSchema = z
+ .object({
+ credentials: MicrosoftIntuneConnectionClientSecretInputCredentialsSchema.optional().describe(
+ AppConnections.UPDATE(AppConnection.MicrosoftIntune).credentials
+ )
+ })
+ .and(GenericUpdateAppConnectionFieldsSchema(AppConnection.MicrosoftIntune));
+
+const BaseMicrosoftIntuneConnectionSchema = BaseAppConnectionSchema.extend({
+ app: z.literal(AppConnection.MicrosoftIntune)
+});
+
+export const MicrosoftIntuneConnectionSchema = z.intersection(
+ BaseMicrosoftIntuneConnectionSchema,
+ z.discriminatedUnion("method", [
+ z.object({
+ method: z.literal(MicrosoftIntuneConnectionMethod.ClientSecret),
+ credentials: MicrosoftIntuneConnectionClientSecretOutputCredentialsSchema
+ })
+ ])
+);
+
+export const SanitizedMicrosoftIntuneConnectionSchema = z.discriminatedUnion("method", [
+ BaseMicrosoftIntuneConnectionSchema.extend({
+ method: z.literal(MicrosoftIntuneConnectionMethod.ClientSecret),
+ credentials: MicrosoftIntuneConnectionClientSecretOutputCredentialsSchema.pick({
+ tenantId: true,
+ clientId: true
+ })
+ }).describe(JSON.stringify({ title: `${APP_CONNECTION_NAME_MAP[AppConnection.MicrosoftIntune]} (Client Secret)` }))
+]);
+
+export const MicrosoftIntuneConnectionListItemSchema = z
+ .object({
+ name: z.literal("Microsoft Intune"),
+ app: z.literal(AppConnection.MicrosoftIntune),
+ methods: z.nativeEnum(MicrosoftIntuneConnectionMethod).array()
+ })
+ .describe(JSON.stringify({ title: APP_CONNECTION_NAME_MAP[AppConnection.MicrosoftIntune] }));
diff --git a/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-types.ts b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-types.ts
new file mode 100644
index 0000000000..e1c19b968a
--- /dev/null
+++ b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-types.ts
@@ -0,0 +1,53 @@
+import z from "zod";
+
+import { DiscriminativePick } from "@app/lib/types";
+
+import { AppConnection } from "../app-connection-enums";
+import {
+ CreateMicrosoftIntuneConnectionSchema,
+ MicrosoftIntuneConnectionClientSecretOutputCredentialsSchema,
+ MicrosoftIntuneConnectionSchema,
+ ValidateMicrosoftIntuneConnectionCredentialsSchema
+} from "./microsoft-intune-connection-schemas";
+
+export type TMicrosoftIntuneConnection = z.infer<typeof MicrosoftIntuneConnectionSchema>;
+
+export type TMicrosoftIntuneConnectionInput = z.infer<typeof CreateMicrosoftIntuneConnectionSchema> & {
+ app: AppConnection.MicrosoftIntune;
+};
+
+export type TValidateMicrosoftIntuneConnectionCredentialsSchema =
+ typeof ValidateMicrosoftIntuneConnectionCredentialsSchema;
+
+export type TMicrosoftIntuneConnectionConfig = DiscriminativePick<
+ TMicrosoftIntuneConnectionInput,
+ "method" | "app" | "credentials"
+> & {
+ orgId: string;
+};
+
+export type TMicrosoftIntuneConnectionCredentials = z.infer<
+ typeof MicrosoftIntuneConnectionClientSecretOutputCredentialsSchema
+>;
+
+export type TMicrosoftEntraTokenResponse = {
+ token_type: string;
+ expires_in: number;
+ access_token: string;
+};
+
+export type TMicrosoftGraphServicePrincipalEndpoint = {
+ id: string;
+ providerName?: string;
+ providerResourceId?: string;
+ uri: string;
+};
+
+export type TMicrosoftGraphServicePrincipalEndpointsResponse = {
+ value: TMicrosoftGraphServicePrincipalEndpoint[];
+};
+
+export type TIntuneScepValidationResponse = {
+ code?: string;
+ errorDescription?: string;
+};
diff --git a/backend/src/services/certificate-common/certificate-issuance-utils.test.ts b/backend/src/services/certificate-common/certificate-issuance-utils.test.ts
new file mode 100644
index 0000000000..590fefb8c5
--- /dev/null
+++ b/backend/src/services/certificate-common/certificate-issuance-utils.test.ts
@@ -0,0 +1,49 @@
+import { CertKeyAlgorithm } from "@app/services/certificate/certificate-types";
+import { TCertificateAuthorityWithAssociatedCa } from "@app/services/certificate-authority/certificate-authority-dal";
+
+import { validateAlgorithmCompatibility } from "./certificate-issuance-utils";
+
+const caWithKeyAlgorithm = (keyAlgorithm: CertKeyAlgorithm): TCertificateAuthorityWithAssociatedCa =>
+ ({ internalCa: { keyAlgorithm } }) as unknown as TCertificateAuthorityWithAssociatedCa;
+
+describe("validateAlgorithmCompatibility", () => {
+ // Stored policies use both orderings for the same algorithm, so compatibility must match either.
+ test.each(["SHA256-RSA", "RSA-SHA256"])("accepts RSA signature '%s' for an RSA CA", (sig) => {
+ expect(() =>
+ validateAlgorithmCompatibility(caWithKeyAlgorithm(CertKeyAlgorithm.RSA_2048), {
+ algorithms: { signature: [sig] }
+ })
+ ).not.toThrow();
+ });
+
+ test.each(["SHA384-ECDSA", "ECDSA-SHA384"])("accepts ECDSA signature '%s' for an EC CA", (sig) => {
+ expect(() =>
+ validateAlgorithmCompatibility(caWithKeyAlgorithm(CertKeyAlgorithm.ECDSA_P384), {
+ algorithms: { signature: [sig] }
+ })
+ ).not.toThrow();
+ });
+
+ test("rejects an ECDSA signature algorithm for an RSA CA", () => {
+ expect(() =>
+ validateAlgorithmCompatibility(caWithKeyAlgorithm(CertKeyAlgorithm.RSA_2048), {
+ algorithms: { signature: ["SHA256-ECDSA"] }
+ })
+ ).toThrow();
+ });
+
+ test("rejects an RSA signature algorithm for an EC CA", () => {
+ expect(() =>
+ validateAlgorithmCompatibility(caWithKeyAlgorithm(CertKeyAlgorithm.ECDSA_P256), {
+ algorithms: { signature: ["SHA256-RSA"] }
+ })
+ ).toThrow();
+ });
+
+ test("is a no-op when the template specifies no signature algorithms", () => {
+ expect(() =>
+ validateAlgorithmCompatibility(caWithKeyAlgorithm(CertKeyAlgorithm.RSA_2048), { algorithms: { signature: [] } })
+ ).not.toThrow();
+ expect(() => validateAlgorithmCompatibility(caWithKeyAlgorithm(CertKeyAlgorithm.RSA_2048), {})).not.toThrow();
+ });
+});
diff --git a/backend/src/services/certificate-common/certificate-issuance-utils.ts b/backend/src/services/certificate-common/certificate-issuance-utils.ts
index 84a045fba0..e4b44da769 100644
--- a/backend/src/services/certificate-common/certificate-issuance-utils.ts
+++ b/backend/src/services/certificate-common/certificate-issuance-utils.ts
@@ -179,17 +179,13 @@ export const validateAlgorithmCompatibility = (
}
const parts = sigAlg.split("-");
- if (parts.length === 0) {
- return false;
- }
- const keyType = parts[parts.length - 1];
if (caKeyAlgorithm.startsWith("RSA")) {
- return keyType === CertKeyType.RSA;
+ return parts.includes(CertKeyType.RSA);
}
if (caKeyAlgorithm.startsWith("EC")) {
- return keyType === CertKeyType.ECDSA;
+ return parts.includes(CertKeyType.ECDSA);
}
return false;
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.test.ts b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
index c99058841e..3a45e1ddc1 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.test.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.test.ts
@@ -288,6 +288,9 @@ describe("CertificateProfileService", () => {
certificateBodyDAL: mockCertificateBodyDAL,
certificateSecretDAL: mockCertificateSecretDAL,
certificateAuthorityDAL: mockCertificateAuthorityDAL,
+ certificateAuthoritySecretDAL: { findOne: vi.fn() } as never,
+ certificateAuthorityCertDAL: { find: vi.fn() } as never,
+ hsmConnectorService: {} as never,
externalCertificateAuthorityDAL: mockExternalCertificateAuthorityDAL,
permissionService: mockPermissionService,
kmsService: mockKmsService,
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts
index 3fc5fb17fd..5fb9824a1f 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts
@@ -16,7 +16,7 @@ import {
import { buildUrl } from "@app/ee/services/pki-acme/pki-acme-fns";
import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
import { TScepDynamicChallengeDALFactory } from "@app/ee/services/pki-scep/pki-scep-dynamic-challenge-dal";
-import { generateRaCertificate } from "@app/ee/services/pki-scep/pki-scep-fns";
+import { generateAndEncryptScepRaCertificate, resolveScepRaSigning } from "@app/ee/services/pki-scep/pki-scep-fns";
import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";
import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate";
import { getConfig } from "@app/lib/config/env";
@@ -27,8 +27,10 @@ import { ActorAuthMethod, ActorType } from "../auth/auth-type";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
import { getCertificateCredentials, isCertChainValid } from "../certificate/certificate-fns";
import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-dal";
+import { TCertificateAuthorityCertDALFactory } from "../certificate-authority/certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
import { CaType } from "../certificate-authority/certificate-authority-enums";
+import { TCertificateAuthoritySecretDALFactory } from "../certificate-authority/certificate-authority-secret-dal";
import { TExternalCertificateAuthorityDALFactory } from "../certificate-authority/external-certificate-authority-dal";
import { TCertificatePolicyDALFactory } from "../certificate-policy/certificate-policy-dal";
import { TCertificatePolicyServiceFactory } from "../certificate-policy/certificate-policy-service";
@@ -43,6 +45,7 @@ import {
} from "../enrollment-config/enrollment-config-types";
import { TEstEnrollmentConfigDALFactory } from "../enrollment-config/est-enrollment-config-dal";
import { TScepEnrollmentConfigDALFactory } from "../enrollment-config/scep-enrollment-config-dal";
+import { THsmConnectorServiceFactory } from "../hsm-connector/hsm-connector-service";
import { TKmsServiceFactory } from "../kms/kms-service";
import { TPkiApplicationProfileDALFactory } from "../pki-application/pki-application-profile-dal";
import { TProjectDALFactory } from "../project/project-dal";
@@ -292,7 +295,10 @@ type TCertificateProfileServiceFactoryDep = {
scepDynamicChallengeDAL: Pick<TScepDynamicChallengeDALFactory, "deleteByConfigId">;
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "findOne">;
certificateSecretDAL: Pick<TCertificateSecretDALFactory, "findOne">;
- certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find">;
+ hsmConnectorService: THsmConnectorServiceFactory;
externalCertificateAuthorityDAL: Pick<TExternalCertificateAuthorityDALFactory, "findById" | "findOne">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getResourcePermission">;
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
@@ -354,6 +360,9 @@ export const certificateProfileServiceFactory = ({
certificateBodyDAL,
certificateSecretDAL,
certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ certificateAuthorityCertDAL,
+ hsmConnectorService,
externalCertificateAuthorityDAL,
permissionService,
kmsService,
@@ -482,20 +491,37 @@ export const certificateProfileServiceFactory = ({
allowCertBasedRenewal: boolean;
dynamicChallengeExpiryMinutes: number | null;
dynamicChallengeMaxPending: number | null;
+ signRaWithCa: boolean;
}
| undefined;
if (enrollmentType === EnrollmentType.SCEP && data.scepConfig) {
- const raCert = await generateRaCertificate(data.slug);
+ if (data.scepConfig.challengeType === ScepChallengeType.MICROSOFT_INTUNE) {
+ throw new BadRequestError({
+ message:
+ "Microsoft Intune SCEP validation must be configured through an application's enrollment method, not directly on a certificate profile."
+ });
+ }
- const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
- projectId,
- projectDAL,
- kmsService
+ const { signRaWithCa } = await resolveScepRaSigning({
+ caId: data.caId,
+ requestedSignRaWithCa: data.scepConfig.signRaWithCa,
+ certificateAuthorityDAL
});
- const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });
- const { cipherTextBlob: encryptedRaPrivateKey } = await kmsEncryptor({
- plainText: Buffer.from(raCert.privateKeyDer)
+
+ const raCert = await generateAndEncryptScepRaCertificate({
+ slug: data.slug,
+ caId: data.caId,
+ signRaWithCa,
+ projectId,
+ deps: {
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ certificateAuthorityCertDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService
+ }
});
const challengeType = (data.scepConfig.challengeType as ScepChallengeType) || ScepChallengeType.STATIC;
@@ -509,13 +535,14 @@ export const certificateProfileServiceFactory = ({
}
precomputedScepConfig = {
- encryptedRaPrivateKey,
+ encryptedRaPrivateKey: raCert.encryptedPrivateKey,
raCertificatePem: raCert.certificatePem,
raCertExpiresAt: raCert.expiresAt,
hashedChallengePassword,
challengeType,
includeCaCertInResponse: data.scepConfig.includeCaCertInResponse ?? true,
allowCertBasedRenewal: data.scepConfig.allowCertBasedRenewal ?? true,
+ signRaWithCa,
dynamicChallengeExpiryMinutes:
challengeType === ScepChallengeType.DYNAMIC ? (data.scepConfig.dynamicChallengeExpiryMinutes ?? 60) : null,
dynamicChallengeMaxPending:
@@ -585,6 +612,7 @@ export const certificateProfileServiceFactory = ({
challengeType: precomputedScepConfig.challengeType,
includeCaCertInResponse: precomputedScepConfig.includeCaCertInResponse,
allowCertBasedRenewal: precomputedScepConfig.allowCertBasedRenewal,
+ signRaWithCa: precomputedScepConfig.signRaWithCa,
dynamicChallengeExpiryMinutes: precomputedScepConfig.dynamicChallengeExpiryMinutes,
dynamicChallengeMaxPending: precomputedScepConfig.dynamicChallengeMaxPending
},
diff --git a/backend/src/services/enrollment-config/enrollment-config-types.ts b/backend/src/services/enrollment-config/enrollment-config-types.ts
index afc31220b9..79cfcf1056 100644
--- a/backend/src/services/enrollment-config/enrollment-config-types.ts
+++ b/backend/src/services/enrollment-config/enrollment-config-types.ts
@@ -58,4 +58,6 @@ export interface TScepConfigData {
allowCertBasedRenewal?: boolean;
dynamicChallengeExpiryMinutes?: number;
dynamicChallengeMaxPending?: number;
+ validationConnectionId?: string;
+ signRaWithCa?: boolean;
}
diff --git a/backend/src/services/pki-application/pki-application-enrollment-service.ts b/backend/src/services/pki-application/pki-application-enrollment-service.ts
index 77c813773e..a489f7e8b5 100644
--- a/backend/src/services/pki-application/pki-application-enrollment-service.ts
+++ b/backend/src/services/pki-application/pki-application-enrollment-service.ts
@@ -8,11 +8,17 @@ import {
ResourcePermissionSub
} from "@app/ee/services/permission/resource-permission";
import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
-import { generateRaCertificate } from "@app/ee/services/pki-scep/pki-scep-fns";
+import { generateAndEncryptScepRaCertificate, resolveScepRaSigning } from "@app/ee/services/pki-scep/pki-scep-fns";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { TProjectPermission } from "@app/lib/types";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { TCertificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
+import { TCertificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
+import { TCertificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
+import { TCertificateProfileDALFactory } from "@app/services/certificate-profile/certificate-profile-dal";
import {
generateAndEncryptAcmeEabSecret,
validateAndEncryptPemCaChain
@@ -21,6 +27,7 @@ import { TAcmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config
import { TApiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
import { TEstEnrollmentConfigDALFactory } from "@app/services/enrollment-config/est-enrollment-config-dal";
import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";
+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";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
@@ -66,6 +73,8 @@ type TSetScepEnrollmentDTO = {
allowCertBasedRenewal?: boolean;
dynamicChallengeExpiryMinutes?: number;
dynamicChallengeMaxPending?: number;
+ validationConnectionId?: string;
+ signRaWithCa?: boolean;
};
} & TProjectPermission;
@@ -89,7 +98,16 @@ type TPkiApplicationEnrollmentServiceFactoryDep = {
estEnrollmentConfigDAL: Pick<TEstEnrollmentConfigDALFactory, "create" | "updateById" | "deleteById" | "findById">;
acmeEnrollmentConfigDAL: Pick<TAcmeEnrollmentConfigDALFactory, "create" | "updateById" | "deleteById" | "findById">;
scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "create" | "updateById" | "deleteById" | "findById">;
- kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findById">;
+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
+ certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
+ certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find">;
+ hsmConnectorService: THsmConnectorServiceFactory;
+ kmsService: Pick<
+ TKmsServiceFactory,
+ "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey" | "createCipherPairWithDataKey"
+ >;
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
permissionService: Pick<TPermissionServiceFactory, "getResourcePermission">;
};
@@ -103,6 +121,12 @@ export const pkiApplicationEnrollmentServiceFactory = ({
estEnrollmentConfigDAL,
acmeEnrollmentConfigDAL,
scepEnrollmentConfigDAL,
+ appConnectionDAL,
+ certificateProfileDAL,
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ certificateAuthorityCertDAL,
+ hsmConnectorService,
kmsService,
projectDAL,
permissionService
@@ -188,6 +212,12 @@ export const pkiApplicationEnrollmentServiceFactory = ({
const estConfig = junction.estConfigId ? await estEnrollmentConfigDAL.findById(junction.estConfigId) : null;
const scepConfig = junction.scepConfigId ? await scepEnrollmentConfigDAL.findById(junction.scepConfigId) : null;
+ const profile = await certificateProfileDAL.findById(profileId);
+ const { raCaSigningSupported, caType } = await resolveScepRaSigning({
+ caId: profile?.caId,
+ certificateAuthorityDAL
+ });
+
const siteUrl = getConfig().SITE_URL ?? "";
const appProfilePath = `applications/${applicationId}/profiles/${profileId}`;
@@ -230,9 +260,13 @@ export const pkiApplicationEnrollmentServiceFactory = ({
? `${siteUrl}/scep/${appProfilePath}/challenge`
: null,
raCertificatePem: scepConfig.raCertificate,
- raCertExpiresAt: scepConfig.raCertExpiresAt
+ raCertExpiresAt: scepConfig.raCertExpiresAt,
+ validationConnectionId: scepConfig.validationConnectionId ?? null,
+ signRaWithCa: Boolean(scepConfig.signRaWithCa)
}
: null,
+ raCaSigningSupported,
+ caType,
estConfigured: Boolean(junction.estConfigId),
acmeConfigured: Boolean(junction.acmeConfigId),
scepConfigured: Boolean(junction.scepConfigId)
@@ -622,7 +656,25 @@ export const pkiApplicationEnrollmentServiceFactory = ({
);
const challengeType = config.challengeType ?? ScepChallengeType.STATIC;
+ const isIntune = challengeType === ScepChallengeType.MICROSOFT_INTUNE;
const appCfg = getConfig();
+
+ let validationConnectionId: string | null = null;
+ let validationConnectionName: string | null = null;
+ if (isIntune) {
+ if (!config.validationConnectionId) {
+ throw new BadRequestError({
+ message: "A Microsoft Intune connection is required for Microsoft Intune SCEP validation."
+ });
+ }
+ const connection = await appConnectionDAL.findById(config.validationConnectionId);
+ if (!connection || connection.orgId !== actorOrgId || connection.app !== AppConnection.MicrosoftIntune) {
+ throw new BadRequestError({ message: "The selected Microsoft Intune connection could not be found." });
+ }
+ validationConnectionId = connection.id;
+ validationConnectionName = connection.name;
+ }
+
let hashedChallengePassword: string | null = null;
if (challengeType === ScepChallengeType.STATIC) {
if (!config.challengePassword) {
@@ -631,14 +683,41 @@ export const pkiApplicationEnrollmentServiceFactory = ({
hashedChallengePassword = await crypto.hashing().createHash(config.challengePassword, appCfg.SALT_ROUNDS);
}
+ // Cert-based renewal skips the challenge, which would bypass Intune's per-request validation, so force it off.
+ const allowCertBasedRenewal = isIntune ? false : (config.allowCertBasedRenewal ?? true);
+
const isFirstCreate = !junction.scepConfigId;
- const raCert = isFirstCreate ? await generateRaCertificate(`app-${applicationId}-${profileId}`) : null;
- let encryptedRaPrivateKey: Buffer | null = null;
- if (raCert) {
- const certificateManagerKmsId = await getProjectKmsCertificateKeyId({ projectId, projectDAL, kmsService });
- const kmsEncryptor = await kmsService.encryptWithKmsKey({ kmsId: certificateManagerKmsId });
- const encResult = await kmsEncryptor({ plainText: Buffer.from(raCert.privateKeyDer) });
- encryptedRaPrivateKey = encResult.cipherTextBlob;
+ const raSlug = `app-${applicationId}-${profileId}`;
+
+ const profile = await certificateProfileDAL.findById(profileId);
+ const { signRaWithCa } = await resolveScepRaSigning({
+ caId: profile?.caId,
+ requestedSignRaWithCa: config.signRaWithCa,
+ certificateAuthorityDAL
+ });
+
+ const existingScepConfig = junction.scepConfigId
+ ? await scepEnrollmentConfigDAL.findById(junction.scepConfigId)
+ : null;
+ // Regenerating the RA breaks devices already trusting it, so only do it on first enable or a signing change.
+ const shouldGenerateRaCert =
+ isFirstCreate || (existingScepConfig ? existingScepConfig.signRaWithCa !== signRaWithCa : false);
+ let raCert: Awaited<ReturnType<typeof generateAndEncryptScepRaCertificate>> | null = null;
+ if (shouldGenerateRaCert) {
+ raCert = await generateAndEncryptScepRaCertificate({
+ slug: raSlug,
+ caId: profile?.caId,
+ signRaWithCa,
+ projectId,
+ deps: {
+ certificateAuthorityDAL,
+ certificateAuthoritySecretDAL,
+ certificateAuthorityCertDAL,
+ projectDAL,
+ kmsService,
+ hsmConnectorService
+ }
+ });
}
return pkiApplicationProfileDAL.transaction(async (tx) => {
@@ -653,30 +732,41 @@ export const pkiApplicationEnrollmentServiceFactory = ({
scepConfigId,
{
...(hashedChallengePassword !== null ? { hashedChallengePassword } : {}),
+ ...(raCert
+ ? {
+ raCertificate: raCert.certificatePem,
+ raCertExpiresAt: raCert.expiresAt,
+ encryptedRaPrivateKey: raCert.encryptedPrivateKey
+ }
+ : {}),
challengeType,
includeCaCertInResponse: config.includeCaCertInResponse ?? true,
- allowCertBasedRenewal: config.allowCertBasedRenewal ?? true,
+ allowCertBasedRenewal,
+ signRaWithCa,
dynamicChallengeExpiryMinutes,
- dynamicChallengeMaxPending
+ dynamicChallengeMaxPending,
+ validationConnectionId
},
tx
);
} else {
- if (!raCert || !encryptedRaPrivateKey) {
+ if (!raCert) {
// Defensive, should never hit; raCert is generated when isFirstCreate.
throw new BadRequestError({ message: "Failed to generate SCEP RA certificate." });
}
const created = await scepEnrollmentConfigDAL.create(
{
- encryptedRaPrivateKey,
+ encryptedRaPrivateKey: raCert.encryptedPrivateKey,
raCertificate: raCert.certificatePem,
raCertExpiresAt: raCert.expiresAt,
hashedChallengePassword,
challengeType,
includeCaCertInResponse: config.includeCaCertInResponse ?? true,
- allowCertBasedRenewal: config.allowCertBasedRenewal ?? true,
+ allowCertBasedRenewal,
+ signRaWithCa,
dynamicChallengeExpiryMinutes,
dynamicChallengeMaxPending,
+ validationConnectionId,
applicationProfileId: junction.id
},
tx
@@ -684,7 +774,15 @@ export const pkiApplicationEnrollmentServiceFactory = ({
scepConfigId = created.id;
await pkiApplicationProfileDAL.update({ applicationId, profileId }, { scepConfigId }, tx);
}
- return { applicationId, profileId, scep: { id: scepConfigId, challengeType } };
+ return {
+ applicationId,
+ profileId,
+ scep: { id: scepConfigId, challengeType },
+ signRaWithCa,
+ validationConnection: validationConnectionId
+ ? { id: validationConnectionId, name: validationConnectionName }
+ : null
+ };
});
};
diff --git a/docs/docs.json b/docs/docs.json
index ecfb4e8cbe..0e412e5865 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -151,6 +151,7 @@
"integrations/app-connections/litellm",
"integrations/app-connections/ssh",
"integrations/app-connections/mssql",
+ "integrations/app-connections/microsoft-intune",
"integrations/app-connections/mongodb",
"integrations/app-connections/mysql",
"integrations/app-connections/netlify",
diff --git a/docs/documentation/platform/pki/applications/enrollment-methods/scep.mdx b/docs/documentation/platform/pki/applications/enrollment-methods/scep.mdx
index e9e06944b6..ade08bc1ca 100644
--- a/docs/documentation/platform/pki/applications/enrollment-methods/scep.mdx
+++ b/docs/documentation/platform/pki/applications/enrollment-methods/scep.mdx
@@ -52,7 +52,7 @@ For self-hosted Infisical instances, replace `app.infisical.com` with your insta
## Challenge Types
-Infisical supports two challenge authentication modes for SCEP enrollment:
+Infisical supports three challenge authentication modes for SCEP enrollment:
<Tabs>
<Tab title="Static Challenge">
@@ -63,6 +63,18 @@ Infisical supports two challenge authentication modes for SCEP enrollment:
- The challenge password must be at least 8 characters.
- The password is hashed before storage and cannot be retrieved after creation.
</Tab>
+ <Tab title="Microsoft Intune">
+ The challenge password is validated directly with Microsoft Intune instead of against a password stored in Infisical. Intune generates a unique challenge for each device it enrolls, and Infisical asks Intune to confirm that the challenge is valid before issuing the certificate.
+
+ Use this mode when devices are managed by Microsoft Intune. It removes the need to distribute a shared password and lets Intune track certificate issuance per device.
+
+ - Requires a **Microsoft Intune** [App Connection](/integrations/app-connections/microsoft-intune) with permission to validate SCEP requests.
+ - Infisical reports issuance success and failure back to Intune for each request.
+
+ <Warning>
+ **Do not attach an approval policy to a profile used with Microsoft Intune.** Intune SCEP issues synchronously, so a pending (approval-gated) response makes the device give up and re-enroll instead of installing the certificate.
+ </Warning>
+ </Tab>
<Tab title="Dynamic Challenge">
One-time-use challenge passwords are generated on demand via an authenticated API endpoint. Each challenge can only be used once and expires after a configurable time period.
@@ -111,6 +123,7 @@ Infisical supports two challenge authentication modes for SCEP enrollment:
- **Challenge Password** (static only): A shared secret that SCEP clients must include in their certificate signing request (CSR) to authenticate with Infisical's SCEP server. Must be at least 8 characters.
- **Challenge Expiry** (dynamic only): How long each generated challenge remains valid, in minutes.
- **Max Pending Challenges** (dynamic only): Maximum number of unused challenges that can exist at once.
+ - **Sign RA certificate with the CA**: Choose whether the RA certificate is self-signed or signed by this profile's CA. Signing it with the CA makes it chain to your CA root, which strict clients such as Apple (macOS and iOS) and Microsoft Intune require. Currently only internal CAs can sign the RA. Other CAs use a self-signed RA.
- **Include CA Cert in Response**: When enabled, the CA certificate chain is included alongside the RA certificate in the GetCACert response. Most SCEP clients expect this to be enabled (default: enabled).
- **Allow Certificate-Based Renewal**: When enabled, devices that already hold a valid certificate issued by the same CA can renew their certificate without providing the challenge password (default: enabled).
@@ -269,7 +282,7 @@ Infisical's SCEP server supports the following algorithms for the CMS message ex
<AccordionGroup>
<Accordion title="What is the RA certificate?">
- The RA (Registration Authority) certificate is automatically generated when you create a SCEP-enabled certificate profile. It is used to encrypt and sign the SCEP message exchange between the client and server. The RA certificate has a 10-year validity and is separate from your CA certificate.
+ The RA (Registration Authority) certificate is Infisical's identity for the SCEP message exchange. It is generated automatically when SCEP enrollment is enabled on a profile, and Infisical holds its private key. It is either self-signed or signed by the profile's CA, controlled by the **Sign RA certificate with the CA** option (see above). Strict clients such as Microsoft Intune and Apple require a CA-signed RA, which currently only internal CAs support.
</Accordion>
<Accordion title="When should I use static vs. dynamic challenges?">
Use **static challenges** for simple setups where a shared password is acceptable, such as network devices or test environments.
diff --git a/docs/integrations/app-connections/microsoft-intune.mdx b/docs/integrations/app-connections/microsoft-intune.mdx
new file mode 100644
index 0000000000..316281fa76
--- /dev/null
+++ b/docs/integrations/app-connections/microsoft-intune.mdx
@@ -0,0 +1,87 @@
+---
+title: "Microsoft Intune Connection"
+description: "Learn how to configure a Microsoft Intune Connection for Infisical."
+---
+
+Infisical's Microsoft Intune Connection lets you validate SCEP certificate requests against Microsoft Intune using Client Secrets. When a device enrolls through a [SCEP enrollment method](/documentation/platform/pki/applications/enrollment-methods/scep) configured with Intune validation, Infisical asks Intune to confirm the device's challenge before issuing the certificate, then reports the outcome back to Intune.
+
+**Prerequisites:**
+
+- A Microsoft Entra ID tenant with Microsoft Intune enabled.
+- An App Registration in Azure with a Client Secret and the API permissions below.
+
+#### Required Azure permissions
+
+Set the API permissions of your Azure application to include the following **Application permissions**, then grant admin consent:
+
+- Microsoft Graph
+ - `Application.Read.All`
+- Microsoft Intune
+ - `scep_challenge_provider`
+
+## Setup Microsoft Intune Connection in Infisical
+
+<Tabs>
+ <Tab title="Infisical UI">
+ <Steps>
+ <Step title="Navigate to App Connections">
+ In your **Certificate Manager** project, go to **Settings** and open the **App Connections** tab, then click **Add Connection**.
+ </Step>
+ <Step title="Add Connection">
+ Select the **Microsoft Intune** option from the connection options modal.
+ </Step>
+ <Step title="Create Connection">
+ Fill in the following fields with the credentials from your Azure App Registration:
+
+ - **Tenant ID**: The Directory (Tenant) ID of your Microsoft Entra ID tenant.
+ - **Client ID**: The Application (Client) ID of your registered application.
+ - **Client Secret**: A client secret generated for your registered application.
+
+ Click **Connect** to create the connection.
+ </Step>
+ <Step title="Connection Created">
+ Your **Microsoft Intune Connection** is now available for use as the validation connection on a SCEP enrollment method.
+ </Step>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ To create a Microsoft Intune Connection via API, send a request to the [Create Microsoft Intune Connection](/api-reference/endpoints/app-connections/microsoft-intune/create) endpoint.
+
+ ### Sample request
+
+ ```bash Request
+ curl --request POST \
+ --url https://app.infisical.com/api/v1/app-connections/microsoft-intune \
+ --header 'Content-Type: application/json' \
+ --data '{
+ "name": "my-microsoft-intune-connection",
+ "method": "client-secret",
+ "credentials": {
+ "tenantId": "your-tenant-id",
+ "clientId": "your-client-id",
+ "clientSecret": "your-client-secret"
+ }
+ }'
+ ```
+
+ ### Sample response
+
+ ```json Response
+ {
+ "appConnection": {
+ "id": "3c90c3cc-0d44-4b50-8888-8dd25736052a",
+ "name": "my-microsoft-intune-connection",
+ "description": null,
+ "version": 1,
+ "orgId": "6f03caa1-a5de-43ce-b127-95a145d3464c",
+ "createdAt": "2023-11-07T05:31:56Z",
+ "updatedAt": "2023-11-07T05:31:56Z",
+ "isPlatformManagedCredentials": false,
+ "app": "microsoft-intune",
+ "method": "client-secret",
+ "credentials": {}
+ }
+ }
+ ```
+ </Tab>
+</Tabs>
diff --git a/frontend/public/images/integrations/Microsoft Intune.svg b/frontend/public/images/integrations/Microsoft Intune.svg
new file mode 100644
index 0000000000..4b493c9544
--- /dev/null
+++ b/frontend/public/images/integrations/Microsoft Intune.svg
@@ -0,0 +1,16 @@
+<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Microsoft Intune">
+ <defs>
+ <linearGradient id="intuneBg" x1="0" y1="0" x2="64" y2="64" gradientUnits="userSpaceOnUse">
+ <stop offset="0" stop-color="#2E8CE6"/>
+ <stop offset="1" stop-color="#1B5FB3"/>
+ </linearGradient>
+ </defs>
+ <rect x="4" y="4" width="56" height="56" rx="12" fill="url(#intuneBg)"/>
+ <path d="M32 14 L46 20 V32 C46 41 40 47 32 50 C24 47 18 41 18 32 V20 Z" fill="#FFFFFF" fill-opacity="0.16"/>
+ <rect x="24" y="24" width="16" height="20" rx="2" fill="#FFFFFF"/>
+ <rect x="27" y="28" width="10" height="2" rx="1" fill="#1B5FB3"/>
+ <rect x="27" y="32" width="10" height="2" rx="1" fill="#1B5FB3"/>
+ <rect x="27" y="36" width="6" height="2" rx="1" fill="#1B5FB3"/>
+ <circle cx="41" cy="41" r="6" fill="#0F4C92" stroke="#FFFFFF" stroke-width="1.5"/>
+ <path d="M38.5 41 L40.3 42.8 L43.6 39.4" stroke="#FFFFFF" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
+</svg>
diff --git a/frontend/src/helpers/appConnections.ts b/frontend/src/helpers/appConnections.ts
index e8f39410eb..be0f219673 100644
--- a/frontend/src/helpers/appConnections.ts
+++ b/frontend/src/helpers/appConnections.ts
@@ -73,6 +73,7 @@ import { HasuraCloudConnectionMethod } from "@app/hooks/api/appConnections/types
import { HerokuConnectionMethod } from "@app/hooks/api/appConnections/types/heroku-connection";
import { LaravelForgeConnectionMethod } from "@app/hooks/api/appConnections/types/laravel-forge-connection";
import { LiteLLMConnectionMethod } from "@app/hooks/api/appConnections/types/litellm-connection";
+import { MicrosoftIntuneConnectionMethod } from "@app/hooks/api/appConnections/types/microsoft-intune-connection";
import { NetlifyConnectionMethod } from "@app/hooks/api/appConnections/types/netlify-connection";
import { NetScalerConnectionMethod } from "@app/hooks/api/appConnections/types/netscaler-connection";
import { NorthflankConnectionMethod } from "@app/hooks/api/appConnections/types/northflank-connection";
@@ -456,6 +457,12 @@ export const APP_CONNECTION_MAP: Record<
category: "IDENTITY",
description: "Manage users and groups in Entra ID."
},
+ [AppConnection.MicrosoftIntune]: {
+ name: "Microsoft Intune",
+ image: "Microsoft Intune.svg",
+ category: "CERTIFICATES",
+ description: "Validate SCEP certificate requests with Microsoft Intune."
+ },
[AppConnection.Venafi]: {
name: "Venafi TLS Protect Cloud",
image: "Venafi.png",
@@ -725,6 +732,7 @@ export const getAppConnectionMethodDetails = (method: TAppConnection["method"])
return { name: "API Key & Secret", icon: faKey };
case AzureDNSConnectionMethod.ClientSecret:
case AzureEntraIdConnectionMethod.ClientSecret:
+ case MicrosoftIntuneConnectionMethod.ClientSecret:
return { name: "Client Secret", icon: faKey };
case OctopusDeployConnectionMethod.ApiKey:
return { name: "API Key", icon: faKey };
diff --git a/frontend/src/hooks/api/appConnections/enums.ts b/frontend/src/hooks/api/appConnections/enums.ts
index 9891ace9a0..6c38652631 100644
--- a/frontend/src/hooks/api/appConnections/enums.ts
+++ b/frontend/src/hooks/api/appConnections/enums.ts
@@ -6,6 +6,7 @@ export enum AppConnection {
AzureKeyVault = "azure-key-vault",
AzureAppConfiguration = "azure-app-configuration",
AzureClientSecrets = "azure-client-secrets",
+ MicrosoftIntune = "microsoft-intune",
AzureDevOps = "azure-devops",
AzureADCS = "azure-adcs",
ADCS = "adcs",
diff --git a/frontend/src/hooks/api/appConnections/types/app-options.ts b/frontend/src/hooks/api/appConnections/types/app-options.ts
index 5bba6da562..9be461b806 100644
--- a/frontend/src/hooks/api/appConnections/types/app-options.ts
+++ b/frontend/src/hooks/api/appConnections/types/app-options.ts
@@ -49,6 +49,10 @@ export type TAzureEntraIdConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.AzureEntraId;
};
+export type TMicrosoftIntuneConnectionOption = TAppConnectionOptionBase & {
+ app: AppConnection.MicrosoftIntune;
+};
+
export type TAzureDevOpsConnectionOption = TAppConnectionOptionBase & {
app: AppConnection.AzureDevOps;
oauthClientId?: string;
@@ -390,6 +394,7 @@ export type TAppConnectionOption =
| TSmbConnectionOption
| TWinRMConnectionOption
| TAzureEntraIdConnectionOption
+ | TMicrosoftIntuneConnectionOption
| TVenafiConnectionOption
| TVenafiTppConnectionOption
| TExternalInfisicalConnectionOption
@@ -472,6 +477,7 @@ export type TAppConnectionOptionMap = {
[AppConnection.CircleCI]: TCircleCISyncConnectionOption;
[AppConnection.Cloud66]: TCloud66ConnectionOption;
[AppConnection.AzureEntraId]: TAzureEntraIdConnectionOption;
+ [AppConnection.MicrosoftIntune]: TMicrosoftIntuneConnectionOption;
[AppConnection.Venafi]: TVenafiConnectionOption;
[AppConnection.VenafiTpp]: TVenafiTppConnectionOption;
[AppConnection.ExternalInfisical]: TExternalInfisicalConnectionOption;
diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.ts
index 8637f54520..7492161d56 100644
--- a/frontend/src/hooks/api/appConnections/types/index.ts
+++ b/frontend/src/hooks/api/appConnections/types/index.ts
@@ -44,6 +44,7 @@ import { THumanitecConnection } from "./humanitec-connection";
import { TLaravelForgeConnection } from "./laravel-forge-connection";
import { TLdapConnection } from "./ldap-connection";
import { TLiteLLMConnection } from "./litellm-connection";
+import { TMicrosoftIntuneConnection } from "./microsoft-intune-connection";
import { TMongoDBConnection } from "./mongodb-connection";
import { TMsSqlConnection } from "./mssql-connection";
import { TMySqlConnection } from "./mysql-connection";
@@ -122,6 +123,7 @@ export * from "./humanitec-connection";
export * from "./laravel-forge-connection";
export * from "./ldap-connection";
export * from "./litellm-connection";
+export * from "./microsoft-intune-connection";
export * from "./mongodb-connection";
export * from "./mssql-connection";
export * from "./mysql-connection";
@@ -217,6 +219,7 @@ export type TAppConnection =
| TCircleCIConnection
| TCloud66Connection
| TAzureEntraIdConnection
+ | TMicrosoftIntuneConnection
| TVenafiConnection
| TVenafiTppConnection
| TExternalInfisicalConnection
diff --git a/frontend/src/hooks/api/appConnections/types/microsoft-intune-connection.ts b/frontend/src/hooks/api/appConnections/types/microsoft-intune-connection.ts
new file mode 100644
index 0000000000..e4e35cd098
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/types/microsoft-intune-connection.ts
@@ -0,0 +1,17 @@
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { TRootAppConnection } from "@app/hooks/api/appConnections/types/root-connection";
+
+export enum MicrosoftIntuneConnectionMethod {
+ ClientSecret = "client-secret"
+}
+
+export type TMicrosoftIntuneConnection = TRootAppConnection & {
+ app: AppConnection.MicrosoftIntune;
+} & {
+ method: MicrosoftIntuneConnectionMethod.ClientSecret;
+ credentials: {
+ tenantId: string;
+ clientId: string;
+ clientSecret: string;
+ };
+};
diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.ts
index f434794bdc..3c6c308341 100644
--- a/frontend/src/hooks/api/certificateProfiles/types.ts
+++ b/frontend/src/hooks/api/certificateProfiles/types.ts
@@ -12,7 +12,8 @@ export enum IssuerType {
export enum ScepChallengeType {
STATIC = "static",
- DYNAMIC = "dynamic"
+ DYNAMIC = "dynamic",
+ MICROSOFT_INTUNE = "microsoft-intune"
}
export type TCertificateProfileDefaults = {
diff --git a/frontend/src/hooks/api/pkiApplications/types.ts b/frontend/src/hooks/api/pkiApplications/types.ts
index b9632b8821..a96dc66059 100644
--- a/frontend/src/hooks/api/pkiApplications/types.ts
+++ b/frontend/src/hooks/api/pkiApplications/types.ts
@@ -1,3 +1,6 @@
+import { CaType } from "@app/hooks/api/ca/enums";
+import { ScepChallengeType } from "@app/hooks/api/certificateProfiles/types";
+
/**
* Mirror of backend's `ResourcePermissionSub` for type-safe `permission.can(...)` checks
* on the application's resource ability. Keep in sync with
@@ -85,7 +88,7 @@ export type TPkiApplicationMember = {
details?: TPkiApplicationMemberDetails | null;
};
-export type ScepChallengeType = "static" | "dynamic";
+export { ScepChallengeType };
export type TPkiApplicationEnrollmentState = {
applicationId: string;
@@ -113,7 +116,11 @@ export type TPkiApplicationEnrollmentState = {
challengeEndpointUrl: string | null;
raCertificatePem: string;
raCertExpiresAt: string;
+ validationConnectionId: string | null;
+ signRaWithCa: boolean;
} | null;
+ raCaSigningSupported: boolean;
+ caType: CaType;
estConfigured: boolean;
acmeConfigured: boolean;
scepConfigured: boolean;
@@ -226,4 +233,6 @@ export type TSetScepEnrollmentDTO = {
allowCertBasedRenewal?: boolean;
dynamicChallengeExpiryMinutes?: number;
dynamicChallengeMaxPending?: number;
+ validationConnectionId?: string;
+ signRaWithCa?: boolean;
};
diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx
index aa3e72cb57..bc59557b51 100644
--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx
+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx
@@ -4,6 +4,7 @@ import { faCheck, faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { EyeIcon, EyeOffIcon, FileTextIcon, Plus, RotateCwIcon } from "lucide-react";
+import { AppConnectionOption } from "@app/components/app-connections";
import { createNotification } from "@app/components/notifications";
import { ConfirmActionModal, Spinner, Tab, TabList, TabPanel, Tabs } from "@app/components/v2";
import {
@@ -26,6 +27,7 @@ import {
FieldDescription,
FieldError,
FieldLabel,
+ FilterableSelect,
Input,
InputGroup,
InputGroupAddon,
@@ -42,8 +44,12 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
+import { useProject } from "@app/context";
import { downloadFile } from "@app/helpers/download";
import { useToggle } from "@app/hooks";
+import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { CaType } from "@app/hooks/api/ca/enums";
import { useGetPkiApplicationEnrollment } from "@app/hooks/api/pkiApplications";
import {
useClearPkiApplicationAcmeEnrollment,
@@ -739,12 +745,16 @@ const ScepPanel = ({
profileId,
profileSlug,
enabled,
+ raCaSigningSupported,
+ caType,
initial
}: {
applicationId: string;
profileId: string;
profileSlug: string;
enabled: boolean;
+ raCaSigningSupported: boolean;
+ caType: CaType;
initial: {
challengeType: ScepChallengeType;
includeCaCertInResponse: boolean;
@@ -755,8 +765,11 @@ const ScepPanel = ({
challengeEndpointUrl: string | null;
raCertificatePem: string;
raCertExpiresAt: string;
+ validationConnectionId: string | null;
+ signRaWithCa: boolean;
} | null;
}) => {
+ const { currentProject } = useProject();
const setMutation = useSetPkiApplicationScepEnrollment();
const clearMutation = useClearPkiApplicationScepEnrollment();
const { control, handleSubmit, watch, reset } = useForm<{
@@ -766,25 +779,31 @@ const ScepPanel = ({
allowCertBasedRenewal: boolean;
dynamicChallengeExpiryMinutes?: number;
dynamicChallengeMaxPending?: number;
+ validationConnectionId?: string;
+ signRaWithCa: boolean;
}>({
defaultValues: {
- challengeType: initial?.challengeType ?? "static",
+ challengeType: initial?.challengeType ?? ScepChallengeType.STATIC,
challengePassword: "",
includeCaCertInResponse: initial?.includeCaCertInResponse ?? true,
allowCertBasedRenewal: initial?.allowCertBasedRenewal ?? true,
dynamicChallengeExpiryMinutes: initial?.dynamicChallengeExpiryMinutes ?? 60,
- dynamicChallengeMaxPending: initial?.dynamicChallengeMaxPending ?? 100
+ dynamicChallengeMaxPending: initial?.dynamicChallengeMaxPending ?? 100,
+ validationConnectionId: initial?.validationConnectionId ?? undefined,
+ signRaWithCa: initial?.signRaWithCa ?? false
}
});
useEffect(() => {
reset({
- challengeType: initial?.challengeType ?? "static",
+ challengeType: initial?.challengeType ?? ScepChallengeType.STATIC,
challengePassword: "",
includeCaCertInResponse: initial?.includeCaCertInResponse ?? true,
allowCertBasedRenewal: initial?.allowCertBasedRenewal ?? true,
dynamicChallengeExpiryMinutes: initial?.dynamicChallengeExpiryMinutes ?? 60,
- dynamicChallengeMaxPending: initial?.dynamicChallengeMaxPending ?? 100
+ dynamicChallengeMaxPending: initial?.dynamicChallengeMaxPending ?? 100,
+ validationConnectionId: initial?.validationConnectionId ?? undefined,
+ signRaWithCa: initial?.signRaWithCa ?? false
});
}, [
initial?.challengeType,
@@ -792,14 +811,36 @@ const ScepPanel = ({
initial?.allowCertBasedRenewal,
initial?.dynamicChallengeExpiryMinutes,
initial?.dynamicChallengeMaxPending,
+ initial?.validationConnectionId,
+ initial?.signRaWithCa,
+ raCaSigningSupported,
reset
]);
const challengeType = watch("challengeType");
+ const isIntune = challengeType === ScepChallengeType.MICROSOFT_INTUNE;
+
+ const { data: intuneConnections, isPending: isIntuneConnectionsLoading } =
+ useListAvailableAppConnections(AppConnection.MicrosoftIntune, currentProject.id, {
+ enabled: isIntune
+ });
const onSave = handleSubmit(async (values) => {
try {
- await setMutation.mutateAsync({ applicationId, profileId, ...values });
+ const signRaWithCa = raCaSigningSupported && values.signRaWithCa;
+ const payload = isIntune
+ ? {
+ applicationId,
+ profileId,
+ challengeType: values.challengeType,
+ includeCaCertInResponse: values.includeCaCertInResponse,
+ // Cert-based renewal would bypass Intune's per-request validation, so it is always off.
+ allowCertBasedRenewal: false,
+ signRaWithCa,
+ validationConnectionId: values.validationConnectionId
+ }
+ : { applicationId, profileId, ...values, signRaWithCa, validationConnectionId: undefined };
+ await setMutation.mutateAsync(payload);
createNotification({ type: "success", text: "SCEP enrollment saved" });
} catch (err) {
createNotification({ type: "error", text: errorText(err, "Failed to save SCEP enrollment") });
@@ -835,7 +876,7 @@ const ScepPanel = ({
value={initial.scepEndpointUrl}
helper="Configure your MDM or SCEP client to point at this URL."
/>
- {initial.challengeType === "dynamic" && initial.challengeEndpointUrl ? (
+ {initial.challengeType === ScepChallengeType.DYNAMIC && initial.challengeEndpointUrl ? (
<CopyableField
label="Challenge endpoint URL"
value={initial.challengeEndpointUrl}
@@ -890,20 +931,65 @@ const ScepPanel = ({
<SelectValue />
</SelectTrigger>
<SelectContent>
- <SelectItem value="static">Static password</SelectItem>
- <SelectItem value="dynamic">Dynamic (per-client)</SelectItem>
+ <SelectItem value={ScepChallengeType.STATIC}>Static password</SelectItem>
+ <SelectItem value={ScepChallengeType.DYNAMIC}>Dynamic (per-client)</SelectItem>
+ <SelectItem value={ScepChallengeType.MICROSOFT_INTUNE}>
+ Microsoft Intune
+ </SelectItem>
</SelectContent>
</Select>
</FieldContent>
<FieldDescription>
- {field.value === "static"
- ? "All clients present the same shared challenge password."
- : "Each client requests a fresh, one-time challenge before enrolling."}
+ {(() => {
+ if (field.value === ScepChallengeType.STATIC)
+ return "All clients present the same shared challenge password.";
+ if (field.value === ScepChallengeType.DYNAMIC)
+ return "Each client requests a fresh, one-time challenge before enrolling.";
+ return "Requests are validated with Microsoft Intune, which seals its own challenge into each device request.";
+ })()}
</FieldDescription>
</Field>
)}
/>
- {challengeType === "static" && (
+ {isIntune && (
+ <Controller
+ control={control}
+ name="validationConnectionId"
+ rules={{ required: true }}
+ render={({ field: { value, onChange }, fieldState: { error } }) => {
+ const selected = intuneConnections?.find((c) => c.id === value) ?? null;
+ return (
+ <Field>
+ <FieldLabel>Microsoft Intune connection</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ value={selected}
+ isError={Boolean(error)}
+ isLoading={isIntuneConnectionsLoading}
+ onChange={(newValue) =>
+ onChange((newValue as { id: string } | null)?.id ?? undefined)
+ }
+ options={intuneConnections ?? []}
+ placeholder="Select connection..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ components={{ Option: AppConnectionOption }}
+ />
+ </FieldContent>
+ <FieldDescription>
+ Selecting the connection is all that is required. The transaction and
+ certificate request arrive in the device request, and the expected subject and
+ SAN are validated by Intune.
+ </FieldDescription>
+ {error ? (
+ <FieldError>A Microsoft Intune connection is required.</FieldError>
+ ) : null}
+ </Field>
+ );
+ }}
+ />
+ )}
+ {challengeType === ScepChallengeType.STATIC && (
<Controller
control={control}
name="challengePassword"
@@ -929,7 +1015,7 @@ const ScepPanel = ({
)}
/>
)}
- {challengeType === "dynamic" && (
+ {challengeType === ScepChallengeType.DYNAMIC && (
<div className="grid grid-cols-2 gap-4">
<Controller
control={control}
@@ -971,44 +1057,86 @@ const ScepPanel = ({
<SectionCard title="Advanced options">
<Controller
control={control}
- name="includeCaCertInResponse"
+ name="signRaWithCa"
render={({ field }) => (
<div className="flex items-start justify-between gap-4">
<div>
- <FieldLabel>Include CA cert in response</FieldLabel>
+ <FieldLabel>Sign RA certificate with the CA</FieldLabel>
<p className="text-xs text-accent">
- Return the issuing CA certificate inline alongside the issued cert.
+ Issue the SCEP RA certificate from this profile&apos;s CA so it chains to the CA
+ root. Strict clients such as Apple and Microsoft Intune require this. Only
+ available for internal certificate authorities.
</p>
</div>
- <Switch
- variant="project"
- id="scep-include-ca"
- checked={field.value}
- onCheckedChange={field.onChange}
- />
+ {raCaSigningSupported ? (
+ <Switch
+ variant="project"
+ id="scep-sign-ra-with-ca"
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Switch
+ variant="project"
+ id="scep-sign-ra-with-ca"
+ checked={false}
+ disabled
+ />
+ </div>
+ </TooltipTrigger>
+ <TooltipContent>
+ Not supported for {caType} certificate authorities.
+ </TooltipContent>
+ </Tooltip>
+ )}
</div>
)}
/>
<Controller
control={control}
- name="allowCertBasedRenewal"
+ name="includeCaCertInResponse"
render={({ field }) => (
<div className="flex items-start justify-between gap-4">
<div>
- <FieldLabel>Allow cert-based renewal</FieldLabel>
+ <FieldLabel>Include CA cert in response</FieldLabel>
<p className="text-xs text-accent">
- Let clients renew using their existing certificate as authentication.
+ Return the issuing CA certificate inline alongside the issued cert.
</p>
</div>
<Switch
variant="project"
- id="scep-cert-renewal"
+ id="scep-include-ca"
checked={field.value}
onCheckedChange={field.onChange}
/>
</div>
)}
/>
+ {!isIntune && (
+ <Controller
+ control={control}
+ name="allowCertBasedRenewal"
+ render={({ field }) => (
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <FieldLabel>Allow cert-based renewal</FieldLabel>
+ <p className="text-xs text-accent">
+ Let clients renew using their existing certificate as authentication.
+ </p>
+ </div>
+ <Switch
+ variant="project"
+ id="scep-cert-renewal"
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </div>
+ )}
+ />
+ )}
</SectionCard>
<div className="flex justify-end gap-2 pt-2">
{enabled && (
@@ -1243,6 +1371,8 @@ export const ConfigureEnrollmentModal = ({
profileId={profileId}
profileSlug={profile?.profileSlug ?? ""}
enabled={Boolean(data?.scepConfigured)}
+ raCaSigningSupported={Boolean(data?.raCaSigningSupported)}
+ caType={data?.caType ?? CaType.INTERNAL}
initial={data?.scep ?? null}
/>
</TabPanel>
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
index 1b100791d0..4bdf0f3d0c 100644
--- a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/AppConnectionForm.tsx
@@ -59,6 +59,7 @@ import { HumanitecConnectionForm } from "./HumanitecConnectionForm";
import { LaravelForgeConnectionForm } from "./LaravelForgeConnectionForm";
import { LdapConnectionForm } from "./LdapConnectionForm";
import { LiteLLMConnectionForm } from "./LiteLLMConnectionForm";
+import { MicrosoftIntuneConnectionForm } from "./MicrosoftIntuneConnectionForm";
import { MongoDBConnectionForm } from "./MongoDBConnectionForm";
import { MsSqlConnectionForm } from "./MsSqlConnectionForm";
import { MySqlConnectionForm } from "./MySqlConnectionForm";
@@ -324,6 +325,8 @@ const CreateForm = ({ app, onComplete, projectId }: CreateFormProps) => {
return <VenafiTppConnectionForm onSubmit={onSubmit} />;
case AppConnection.AzureEntraId:
return <AzureEntraIdConnectionForm onSubmit={onSubmit} />;
+ case AppConnection.MicrosoftIntune:
+ return <MicrosoftIntuneConnectionForm onSubmit={onSubmit} />;
case AppConnection.ExternalInfisical:
return <ExternalInfisicalConnectionForm onSubmit={onSubmit} />;
case AppConnection.Doppler:
@@ -627,6 +630,8 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
return <VenafiTppConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
case AppConnection.Netlify:
return <NetlifyConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
+ case AppConnection.MicrosoftIntune:
+ return <MicrosoftIntuneConnectionForm onSubmit={onSubmit} appConnection={appConnection} />;
default:
throw new Error(`Unhandled App ${(appConnection as TAppConnection).app}`);
}
diff --git a/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MicrosoftIntuneConnectionForm.tsx b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MicrosoftIntuneConnectionForm.tsx
new file mode 100644
index 0000000000..c9b04e7a02
--- /dev/null
+++ b/frontend/src/pages/organization/AppConnections/AppConnectionsPage/components/AppConnectionForm/MicrosoftIntuneConnectionForm.tsx
@@ -0,0 +1,231 @@
+import { Controller, FormProvider, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Info } from "lucide-react";
+import { z } from "zod";
+
+import {
+ Button,
+ Field,
+ FieldError,
+ FieldLabel,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ SheetFooter,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
+import { useScopeVariant } from "@app/hooks";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import {
+ MicrosoftIntuneConnectionMethod,
+ TMicrosoftIntuneConnection
+} from "@app/hooks/api/appConnections/types/microsoft-intune-connection";
+
+import { useAppConnectionForm } from "./AppConnectionFormContext";
+import {
+ genericAppConnectionFieldsSchema,
+ GenericAppConnectionsFields
+} from "./GenericAppConnectionFields";
+
+const formSchema = genericAppConnectionFieldsSchema.extend({
+ app: z.literal(AppConnection.MicrosoftIntune),
+ method: z.literal(MicrosoftIntuneConnectionMethod.ClientSecret),
+ credentials: z.object({
+ tenantId: z.string().trim().min(1, "Tenant ID is required"),
+ clientId: z.string().trim().min(1, "Client ID is required"),
+ clientSecret: z.string().trim().min(1, "Client Secret is required")
+ })
+});
+
+type FormData = z.infer<typeof formSchema>;
+
+type Props = {
+ appConnection?: TMicrosoftIntuneConnection;
+ onSubmit: (formData: FormData) => Promise<void>;
+};
+
+export const MicrosoftIntuneConnectionForm = ({ appConnection, onSubmit }: Props) => {
+ const isUpdate = Boolean(appConnection);
+ const { onCancel } = useAppConnectionForm();
+
+ const form = useForm<FormData>({
+ resolver: zodResolver(formSchema),
+ defaultValues: appConnection
+ ? {
+ name: appConnection.name,
+ description: appConnection.description,
+ app: AppConnection.MicrosoftIntune,
+ method: MicrosoftIntuneConnectionMethod.ClientSecret,
+ credentials: {
+ tenantId: appConnection.credentials.tenantId,
+ clientId: appConnection.credentials.clientId,
+ clientSecret: ""
+ }
+ }
+ : {
+ app: AppConnection.MicrosoftIntune,
+ method: MicrosoftIntuneConnectionMethod.ClientSecret,
+ credentials: {
+ tenantId: "",
+ clientId: "",
+ clientSecret: ""
+ }
+ }
+ });
+
+ const {
+ handleSubmit,
+ control,
+ formState: { isSubmitting, isDirty }
+ } = form;
+
+ const scopeVariant = useScopeVariant();
+
+ return (
+ <FormProvider {...form}>
+ <form onSubmit={handleSubmit(onSubmit)}>
+ {!isUpdate && <GenericAppConnectionsFields />}
+
+ <Controller
+ name="method"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel htmlFor="method">
+ Method
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ The method you would like to use to connect with{" "}
+ {APP_CONNECTION_MAP[AppConnection.MicrosoftIntune].name}. This field cannot be
+ changed after creation.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <Select disabled={isUpdate} value={value} onValueChange={(val) => onChange(val)}>
+ <SelectTrigger id="method" className="w-full" isError={Boolean(error)}>
+ <SelectValue placeholder="Select a method..." />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {Object.values(MicrosoftIntuneConnectionMethod).map((method) => {
+ return (
+ <SelectItem value={method} key={method}>
+ {getAppConnectionMethodDetails(method).name}
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="credentials.tenantId"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel htmlFor="credentials.tenantId">
+ Tenant ID
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ The Microsoft Entra (Azure AD) Tenant ID of the application.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <Input
+ {...field}
+ id="credentials.tenantId"
+ placeholder="00000000-0000-0000-0000-000000000000"
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="credentials.clientId"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel htmlFor="credentials.clientId">
+ Client ID
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ The Application (Client) ID of the Entra app registration granted the Intune
+ SCEP challenge validation permission.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <Input
+ {...field}
+ id="credentials.clientId"
+ placeholder="00000000-0000-0000-0000-000000000000"
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+
+ <Controller
+ name="credentials.clientSecret"
+ control={control}
+ render={({ field, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel htmlFor="credentials.clientSecret">
+ Client Secret
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ The client secret of the Entra app registration.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ <Input
+ {...field}
+ id="credentials.clientSecret"
+ type="password"
+ placeholder="~JzD8e6S.tH~w8XRaNnKcb7W1fM4rCns7FY"
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+
+ <SheetFooter className="sticky bottom-0 -mx-4 items-center border-t bg-popover">
+ <Button
+ type="submit"
+ variant={scopeVariant}
+ isPending={isSubmitting}
+ isDisabled={isSubmitting || (!isUpdate && !isDirty)}
+ >
+ {isUpdate ? "Reconnect to Microsoft Intune" : "Connect to Microsoft Intune"}
+ </Button>
+ <Button type="button" variant="outline" onClick={onCancel} isDisabled={isSubmitting}>
+ Cancel
+ </Button>
+ </SheetFooter>
+ </form>
+ </FormProvider>
+ );
+};