Skip to content

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

Add dynamic challenges to SCEP

Carlos Monastyrskie655d770fd77
diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.ts
index 27f5c05471..395d0a8e0f 100644
--- a/backend/src/@types/knex.d.ts
+++ b/backend/src/@types/knex.d.ts
@@ -368,6 +368,9 @@ import {
TPkiEstEnrollmentConfigs,
TPkiEstEnrollmentConfigsInsert,
TPkiEstEnrollmentConfigsUpdate,
+ TPkiScepDynamicChallenges,
+ TPkiScepDynamicChallengesInsert,
+ TPkiScepDynamicChallengesUpdate,
TPkiScepEnrollmentConfigs,
TPkiScepEnrollmentConfigsInsert,
TPkiScepEnrollmentConfigsUpdate,
@@ -875,6 +878,11 @@ declare module "knex/types/tables" {
TPkiScepTransactionsInsert,
TPkiScepTransactionsUpdate
>;
+ [TableName.PkiScepDynamicChallenge]: KnexOriginal.CompositeTableType<
+ TPkiScepDynamicChallenges,
+ TPkiScepDynamicChallengesInsert,
+ TPkiScepDynamicChallengesUpdate
+ >;
[TableName.PkiApiEnrollmentConfig]: KnexOriginal.CompositeTableType<
TPkiApiEnrollmentConfigs,
TPkiApiEnrollmentConfigsInsert,
diff --git a/backend/src/db/migrations/20260413325231_add-scep-dynamic-challenges.ts b/backend/src/db/migrations/20260413325231_add-scep-dynamic-challenges.ts
new file mode 100644
index 0000000000..744318b29b
--- /dev/null
+++ b/backend/src/db/migrations/20260413325231_add-scep-dynamic-challenges.ts
@@ -0,0 +1,66 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
+
+export async function up(knex: Knex): Promise<void> {
+ if (!(await knex.schema.hasTable(TableName.PkiScepDynamicChallenge))) {
+ await knex.schema.createTable(TableName.PkiScepDynamicChallenge, (t) => {
+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
+
+ t.uuid("scepConfigId").notNullable();
+ t.foreign("scepConfigId").references("id").inTable(TableName.PkiScepEnrollmentConfig).onDelete("CASCADE");
+ t.index("scepConfigId");
+
+ t.text("hashedChallenge").notNullable();
+
+ t.timestamp("expiresAt").notNullable();
+ t.index("expiresAt");
+
+ t.timestamp("usedAt").nullable();
+
+ t.string("clientIp", 45).nullable();
+
+ t.timestamps(true, true, true);
+ });
+
+ await createOnUpdateTrigger(knex, TableName.PkiScepDynamicChallenge);
+ }
+
+ if (!(await knex.schema.hasColumn(TableName.PkiScepEnrollmentConfig, "challengeType"))) {
+ await knex.schema.alterTable(TableName.PkiScepEnrollmentConfig, (t) => {
+ t.string("challengeType", 32).notNullable().defaultTo("static");
+ t.integer("dynamicChallengeExpiryMinutes").notNullable().defaultTo(60);
+ t.integer("dynamicChallengeMaxPending").notNullable().defaultTo(100);
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.PkiScepEnrollmentConfig, "hashedChallengePassword")) {
+ await knex.schema.alterTable(TableName.PkiScepEnrollmentConfig, (t) => {
+ t.text("hashedChallengePassword").nullable().alter();
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ if (await knex.schema.hasTable(TableName.PkiScepDynamicChallenge)) {
+ await dropOnUpdateTrigger(knex, TableName.PkiScepDynamicChallenge);
+ await knex.schema.dropTable(TableName.PkiScepDynamicChallenge);
+ }
+
+ if (await knex.schema.hasColumn(TableName.PkiScepEnrollmentConfig, "challengeType")) {
+ await knex.schema.alterTable(TableName.PkiScepEnrollmentConfig, (t) => {
+ t.dropColumn("challengeType");
+ t.dropColumn("dynamicChallengeExpiryMinutes");
+ t.dropColumn("dynamicChallengeMaxPending");
+ });
+ }
+
+ if (await knex.schema.hasColumn(TableName.PkiScepEnrollmentConfig, "hashedChallengePassword")) {
+ await knex(TableName.PkiScepEnrollmentConfig).whereNull("hashedChallengePassword").delete();
+
+ await knex.schema.alterTable(TableName.PkiScepEnrollmentConfig, (t) => {
+ t.text("hashedChallengePassword").notNullable().alter();
+ });
+ }
+}
diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.ts
index 1ee9a97033..432971065a 100644
--- a/backend/src/db/schemas/index.ts
+++ b/backend/src/db/schemas/index.ts
@@ -145,6 +145,7 @@ export * from "./pki-discovery-configs";
export * from "./pki-discovery-installations";
export * from "./pki-discovery-scan-history";
export * from "./pki-est-enrollment-configs";
+export * from "./pki-scep-dynamic-challenges";
export * from "./pki-scep-enrollment-configs";
export * from "./pki-scep-transactions";
export * from "./pki-signers";
diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.ts
index 33752dd9ef..5ef2824fef 100644
--- a/backend/src/db/schemas/models.ts
+++ b/backend/src/db/schemas/models.ts
@@ -32,6 +32,7 @@ export enum TableName {
PkiAcmeEnrollmentConfig = "pki_acme_enrollment_configs",
PkiScepEnrollmentConfig = "pki_scep_enrollment_configs",
PkiScepTransaction = "pki_scep_transactions",
+ PkiScepDynamicChallenge = "pki_scep_dynamic_challenges",
PkiSubscriber = "pki_subscribers",
PkiAlert = "pki_alerts",
PkiAlertsV2 = "pki_alerts_v2",
diff --git a/backend/src/db/schemas/pki-scep-dynamic-challenges.ts b/backend/src/db/schemas/pki-scep-dynamic-challenges.ts
new file mode 100644
index 0000000000..d990e0c07d
--- /dev/null
+++ b/backend/src/db/schemas/pki-scep-dynamic-challenges.ts
@@ -0,0 +1,25 @@
+// Code generated by automation script, DO NOT EDIT.
+// Automated by pulling database and generating zod schema
+// To update. Just run npm run generate:schema
+// Written by akhilmhdh.
+
+import { z } from "zod";
+
+import { TImmutableDBKeys } from "./models";
+
+export const PkiScepDynamicChallengesSchema = z.object({
+ id: z.string().uuid(),
+ scepConfigId: z.string().uuid(),
+ hashedChallenge: z.string(),
+ expiresAt: z.date(),
+ usedAt: z.date().nullable().optional(),
+ clientIp: z.string().nullable().optional(),
+ createdAt: z.date(),
+ updatedAt: z.date()
+});
+
+export type TPkiScepDynamicChallenges = z.infer<typeof PkiScepDynamicChallengesSchema>;
+export type TPkiScepDynamicChallengesInsert = Omit<z.input<typeof PkiScepDynamicChallengesSchema>, TImmutableDBKeys>;
+export type TPkiScepDynamicChallengesUpdate = Partial<
+ Omit<z.input<typeof PkiScepDynamicChallengesSchema>, TImmutableDBKeys>
+>;
diff --git a/backend/src/db/schemas/pki-scep-enrollment-configs.ts b/backend/src/db/schemas/pki-scep-enrollment-configs.ts
index 22dd50fd39..9c0cfb18a2 100644
--- a/backend/src/db/schemas/pki-scep-enrollment-configs.ts
+++ b/backend/src/db/schemas/pki-scep-enrollment-configs.ts
@@ -14,9 +14,12 @@ export const PkiScepEnrollmentConfigsSchema = z.object({
encryptedRaPrivateKey: zodBuffer,
raCertificate: z.string(),
raCertExpiresAt: z.date(),
- hashedChallengePassword: z.string(),
+ hashedChallengePassword: z.string().nullable().optional(),
includeCaCertInResponse: z.boolean().default(true),
allowCertBasedRenewal: z.boolean().default(true),
+ challengeType: z.string().default("static"),
+ dynamicChallengeExpiryMinutes: z.number().default(60),
+ dynamicChallengeMaxPending: z.number().default(100),
createdAt: z.date(),
updatedAt: z.date()
});
diff --git a/backend/src/ee/routes/scep/pki-scep-router.ts b/backend/src/ee/routes/scep/pki-scep-router.ts
index e68b6e6dfe..d308fc9834 100644
--- a/backend/src/ee/routes/scep/pki-scep-router.ts
+++ b/backend/src/ee/routes/scep/pki-scep-router.ts
@@ -2,6 +2,8 @@ import { z } from "zod";
import { BadRequestError } from "@app/lib/errors";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AuthMode } from "@app/services/auth/auth-type";
const MAX_SCEP_MESSAGE_SIZE = 64 * 1024; // 64KB
@@ -18,6 +20,7 @@ export const registerPkiScepRouter = async (server: FastifyZodProvider) => {
server.addHook("onRequest", async (req) => {
if (
req.method === "POST" &&
+ req.url.includes("/pkiclient.exe") &&
(!req.headers["content-type"] || req.headers["content-type"] === "application/octet-stream")
) {
// eslint-disable-next-line no-param-reassign
@@ -113,4 +116,34 @@ export const registerPkiScepRouter = async (server: FastifyZodProvider) => {
return res.send(response);
}
});
+
+ server.route({
+ method: "POST",
+ url: "/:profileId/challenge",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ params: z.object({
+ profileId: z.string().uuid()
+ })
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req, res) => {
+ const { profileId } = req.params;
+ const clientIp = req.ip || "unknown";
+
+ const result = await server.services.pkiScep.generateDynamicChallenge({
+ profileId,
+ clientIp,
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ void res.header("Content-Type", "text/plain");
+ return res.send(result.challenge);
+ }
+ });
};
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 3fd4913399..ba5c6d008c 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -1,4 +1,5 @@
import { ProjectType } from "@app/db/schemas";
+import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
import {
TCreateProjectTemplateDTO,
TUpdateProjectTemplateDTO
@@ -727,6 +728,7 @@ export enum EventType {
PKI_SIGNER_SIGN = "pki-signer-sign",
SCEP_ENROLLMENT = "scep-enrollment",
SCEP_RENEWAL = "scep-renewal",
+ SCEP_DYNAMIC_CHALLENGE_GENERATED = "scep-dynamic-challenge-generated",
// Secret Validation Rules
SECRET_VALIDATION_RULE_CREATE = "secret-validation-rule-create",
@@ -5708,7 +5710,7 @@ interface ScepEnrollmentEvent {
profileSlug: string;
transactionId: string;
csrSubject: string;
- challengeType: "static";
+ challengeType: ScepChallengeType;
status: "success" | "pending" | "failure";
failReason?: string;
issuedCertificateId?: string;
@@ -5733,6 +5735,16 @@ interface ScepRenewalEvent {
};
}
+interface ScepDynamicChallengeGeneratedEvent {
+ type: EventType.SCEP_DYNAMIC_CHALLENGE_GENERATED;
+ metadata: {
+ profileId: string;
+ profileSlug: string;
+ expiresAt: string;
+ clientIp: string;
+ };
+}
+
interface SecretValidationRuleCreateEvent {
type: EventType.SECRET_VALIDATION_RULE_CREATE;
metadata: {
@@ -6283,6 +6295,7 @@ export type Event =
| CertificateCleanupCompletedEvent
| ScepEnrollmentEvent
| ScepRenewalEvent
+ | ScepDynamicChallengeGeneratedEvent
| SecretValidationRuleCreateEvent
| SecretValidationRuleUpdateEvent
| SecretValidationRuleDeleteEvent;
diff --git a/backend/src/ee/services/pki-scep/challenge/index.ts b/backend/src/ee/services/pki-scep/challenge/index.ts
new file mode 100644
index 0000000000..62e862b0a1
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/challenge/index.ts
@@ -0,0 +1,29 @@
+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";
+
+export type { IScepChallengeValidator } from "./scep-challenge-types";
+export { ScepChallengeType } from "./scep-challenge-types";
+
+type TScepChallengeValidatorFactoryDep = {
+ scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "findById">;
+ scepDynamicChallengeDAL: Pick<TScepDynamicChallengeDALFactory, "findUnusedByConfigId" | "markUsed">;
+};
+
+export const getScepChallengeValidator = (
+ 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)}` });
+ }
+};
diff --git a/backend/src/ee/services/pki-scep/challenge/scep-challenge-dynamic.ts b/backend/src/ee/services/pki-scep/challenge/scep-challenge-dynamic.ts
new file mode 100644
index 0000000000..33c11a7e25
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/challenge/scep-challenge-dynamic.ts
@@ -0,0 +1,30 @@
+import { crypto } from "@app/lib/crypto/cryptography";
+
+import { TScepDynamicChallengeDALFactory } from "../pki-scep-dynamic-challenge-dal";
+import { IScepChallengeValidator } from "./scep-challenge-types";
+
+type TDynamicChallengeValidatorDep = {
+ scepDynamicChallengeDAL: Pick<TScepDynamicChallengeDALFactory, "findUnusedByConfigId" | "markUsed">;
+};
+
+export const dynamicChallengeValidator = ({
+ scepDynamicChallengeDAL
+}: TDynamicChallengeValidatorDep): IScepChallengeValidator => ({
+ validate: async (challengePassword: string, scepConfigId: string): Promise<boolean> => {
+ if (!challengePassword) return false;
+
+ const pendingChallenges = await scepDynamicChallengeDAL.findUnusedByConfigId(scepConfigId);
+
+ for (const challenge of pendingChallenges) {
+ // eslint-disable-next-line no-await-in-loop
+ const matches = await crypto.hashing().compareHash(challengePassword, challenge.hashedChallenge);
+ if (matches) {
+ // eslint-disable-next-line no-await-in-loop
+ const claimed = await scepDynamicChallengeDAL.markUsed(challenge.id);
+ if (claimed) return true;
+ }
+ }
+
+ return false;
+ }
+});
diff --git a/backend/src/ee/services/pki-scep/challenge/scep-challenge-static.ts b/backend/src/ee/services/pki-scep/challenge/scep-challenge-static.ts
new file mode 100644
index 0000000000..538842d40d
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/challenge/scep-challenge-static.ts
@@ -0,0 +1,21 @@
+import { crypto } from "@app/lib/crypto/cryptography";
+import { TScepEnrollmentConfigDALFactory } from "@app/services/enrollment-config/scep-enrollment-config-dal";
+
+import { IScepChallengeValidator } from "./scep-challenge-types";
+
+type TStaticChallengeValidatorDep = {
+ scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "findById">;
+};
+
+export const staticChallengeValidator = ({
+ scepEnrollmentConfigDAL
+}: TStaticChallengeValidatorDep): IScepChallengeValidator => ({
+ validate: async (challengePassword: string, scepConfigId: string): Promise<boolean> => {
+ if (!challengePassword) return false;
+
+ const scepConfig = await scepEnrollmentConfigDAL.findById(scepConfigId);
+ if (!scepConfig?.hashedChallengePassword) return false;
+
+ return crypto.hashing().compareHash(challengePassword, scepConfig.hashedChallengePassword);
+ }
+});
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
new file mode 100644
index 0000000000..18fe9f5e44
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/challenge/scep-challenge-types.ts
@@ -0,0 +1,8 @@
+export enum ScepChallengeType {
+ STATIC = "static",
+ DYNAMIC = "dynamic"
+}
+
+export interface IScepChallengeValidator {
+ validate(challengePassword: string, scepConfigId: string): Promise<boolean>;
+}
diff --git a/backend/src/ee/services/pki-scep/pki-scep-dynamic-challenge-dal.ts b/backend/src/ee/services/pki-scep/pki-scep-dynamic-challenge-dal.ts
new file mode 100644
index 0000000000..aea087704b
--- /dev/null
+++ b/backend/src/ee/services/pki-scep/pki-scep-dynamic-challenge-dal.ts
@@ -0,0 +1,75 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { DatabaseError } from "@app/lib/errors";
+import { ormify } from "@app/lib/knex";
+
+export type TScepDynamicChallengeDALFactory = ReturnType<typeof scepDynamicChallengeDALFactory>;
+
+export const scepDynamicChallengeDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.PkiScepDynamicChallenge);
+
+ const findUnusedByConfigId = async (scepConfigId: string, tx?: Knex) => {
+ try {
+ const results = await (tx || db.replicaNode())(TableName.PkiScepDynamicChallenge)
+ .where({ scepConfigId })
+ .whereNull("usedAt")
+ .where("expiresAt", ">", new Date());
+
+ return results;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find unused SCEP dynamic challenges" });
+ }
+ };
+
+ const countPending = async (scepConfigId: string, tx?: Knex) => {
+ try {
+ const result = await (tx || db.replicaNode())(TableName.PkiScepDynamicChallenge)
+ .where({ scepConfigId })
+ .whereNull("usedAt")
+ .where("expiresAt", ">", new Date())
+ .count("id as count")
+ .first();
+
+ return Number((result as { count?: string | number })?.count ?? 0);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Count pending SCEP dynamic challenges" });
+ }
+ };
+
+ const markUsed = async (id: string, tx?: Knex) => {
+ try {
+ const [result] = await (tx || db)(TableName.PkiScepDynamicChallenge)
+ .where({ id })
+ .whereNull("usedAt")
+ .update({ usedAt: new Date() })
+ .returning("*");
+
+ return result;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Mark SCEP dynamic challenge as used" });
+ }
+ };
+
+ const pruneExpired = async (scepConfigId: string, tx?: Knex) => {
+ try {
+ const deletedCount = await (tx || db)(TableName.PkiScepDynamicChallenge)
+ .where({ scepConfigId })
+ .where("expiresAt", "<", new Date())
+ .delete();
+
+ return deletedCount;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Prune expired SCEP dynamic challenges" });
+ }
+ };
+
+ return {
+ ...orm,
+ findUnusedByConfigId,
+ countPending,
+ markUsed,
+ pruneExpired
+ };
+};
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 4c19006425..0d70404e70 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-service.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-service.ts
@@ -1,6 +1,15 @@
+import { ForbiddenError, subject } from "@casl/ability";
import * as x509 from "@peculiar/x509";
+import { randomBytes } from "crypto";
+import { ActionProjectType } from "@app/db/schemas";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import {
+ ProjectPermissionCertificateProfileActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
import { extractX509CertFromChain } from "@app/lib/certificates/extract-certificate";
+import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { ActorType } from "@app/services/auth/auth-type";
@@ -31,6 +40,8 @@ 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 { TScepDynamicChallengeDALFactory } from "./pki-scep-dynamic-challenge-dal";
import { getScepCapabilities, isSignerCertIssuedByCa } from "./pki-scep-fns";
import { buildCertRepFailure, buildCertRepPending, buildCertRepSuccess } from "./pki-scep-message-builder";
import { parseScepMessage } from "./pki-scep-message-parser";
@@ -38,6 +49,7 @@ import { TScepTransactionDALFactory } from "./pki-scep-transaction-dal";
import {
ScepFailInfo,
ScepMessageType,
+ TGenerateDynamicChallengeDTO,
TGetCaCapsDTO,
TGetCaCertDTO,
THandlePkiOperationDTO,
@@ -48,6 +60,7 @@ type TPkiScepServiceFactoryDep = {
certificateV3Service: Pick<TCertificateV3ServiceFactory, "signCertificateFromProfile">;
certificateProfileDAL: Pick<TCertificateProfileDALFactory, "findByIdWithConfigs">;
scepEnrollmentConfigDAL: Pick<TScepEnrollmentConfigDALFactory, "findById">;
+ scepDynamicChallengeDAL: TScepDynamicChallengeDALFactory;
scepTransactionDAL: TScepTransactionDALFactory;
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById" | "findByIdWithAssociatedCa">;
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "find" | "findById">;
@@ -61,6 +74,7 @@ type TPkiScepServiceFactoryDep = {
certificateRequestService: Pick<TCertificateRequestServiceFactory, "createCertificateRequest">;
certificateIssuanceQueue: Pick<TCertificateIssuanceQueueFactory, "queueCertificateIssuance">;
auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
};
export type TPkiScepServiceFactory = ReturnType<typeof pkiScepServiceFactory>;
@@ -71,6 +85,7 @@ export const pkiScepServiceFactory = ({
certificateV3Service,
certificateProfileDAL,
scepEnrollmentConfigDAL,
+ scepDynamicChallengeDAL,
scepTransactionDAL,
certificateAuthorityDAL,
certificateAuthorityCertDAL,
@@ -83,7 +98,8 @@ export const pkiScepServiceFactory = ({
certificatePolicyService,
certificateRequestService,
certificateIssuanceQueue,
- auditLogService
+ auditLogService,
+ permissionService
}: TPkiScepServiceFactoryDep) => {
const loadScepContext = async (profileId: string) => {
const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
@@ -303,9 +319,11 @@ export const pkiScepServiceFactory = ({
}
}
- const isValid = challengePassword
- ? await crypto.hashing().compareHash(challengePassword, scepConfig.hashedChallengePassword)
- : false;
+ const challengeValidator = getScepChallengeValidator(scepConfig.challengeType as ScepChallengeType, {
+ scepEnrollmentConfigDAL,
+ scepDynamicChallengeDAL
+ });
+ const isValid = await challengeValidator.validate(challengePassword, scepConfig.id);
if (!isValid) {
// Many SCEP clients (including sscep) send PKCSReq for both initial enrollment
@@ -350,7 +368,7 @@ export const pkiScepServiceFactory = ({
profileSlug: profile.slug,
transactionId: parsed.transactionId,
csrSubject: csrObj.subject,
- challengeType: "static" as const,
+ challengeType: scepConfig.challengeType as ScepChallengeType,
status: "failure" as const,
failReason: "Invalid challenge password",
clientIp
@@ -385,7 +403,7 @@ export const pkiScepServiceFactory = ({
profileSlug: profile.slug,
transactionId: parsed.transactionId,
csrSubject: csrObj.subject,
- challengeType: "static" as const,
+ challengeType: scepConfig.challengeType as ScepChallengeType,
clientIp
};
@@ -838,9 +856,102 @@ export const pkiScepServiceFactory = ({
}
};
+ const generateDynamicChallenge = async ({
+ profileId,
+ clientIp,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TGenerateDynamicChallengeDTO) => {
+ const profile = await certificateProfileDAL.findByIdWithConfigs(profileId);
+ if (!profile || profile.enrollmentType !== EnrollmentType.SCEP) {
+ throw new NotFoundError({ message: "SCEP profile not found" });
+ }
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: profile.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.CertificateManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionCertificateProfileActions.Edit,
+ subject(ProjectPermissionSub.CertificateProfiles, { slug: profile.slug })
+ );
+
+ if (!profile.scepConfigId) {
+ throw new BadRequestError({ message: "SCEP enrollment not configured for this profile" });
+ }
+
+ const scepConfig = await scepEnrollmentConfigDAL.findById(profile.scepConfigId);
+ if (!scepConfig) {
+ throw new NotFoundError({ message: "SCEP configuration not found" });
+ }
+
+ if (scepConfig.challengeType !== ScepChallengeType.DYNAMIC) {
+ throw new BadRequestError({ message: "Dynamic challenges are not enabled for this SCEP profile" });
+ }
+
+ const project = await projectDAL.findOne({ id: profile.projectId });
+ if (!project) {
+ throw new NotFoundError({ message: "Project not found" });
+ }
+
+ const plan = await licenseService.getPlan(project.orgId);
+ if (!plan.pkiScep) {
+ throw new BadRequestError({
+ message: "Failed to generate SCEP challenge due to plan restriction. Upgrade to the Enterprise plan."
+ });
+ }
+
+ const pendingCount = await scepDynamicChallengeDAL.countPending(scepConfig.id);
+ if (pendingCount >= scepConfig.dynamicChallengeMaxPending) {
+ throw new BadRequestError({
+ message: `Maximum number of pending challenges (${scepConfig.dynamicChallengeMaxPending}) reached. Wait for existing challenges to expire or be used.`
+ });
+ }
+
+ const challengePlaintext = randomBytes(32).toString("hex");
+
+ const appCfg = getConfig();
+ const hashedChallenge = await crypto.hashing().createHash(challengePlaintext, appCfg.SALT_ROUNDS);
+
+ const expiresAt = new Date();
+ expiresAt.setMinutes(expiresAt.getMinutes() + scepConfig.dynamicChallengeExpiryMinutes);
+
+ await scepDynamicChallengeDAL.create({
+ scepConfigId: scepConfig.id,
+ hashedChallenge,
+ expiresAt,
+ clientIp: clientIp || null
+ });
+
+ void scepDynamicChallengeDAL.pruneExpired(scepConfig.id);
+
+ void auditLogService.createAuditLog({
+ projectId: profile.projectId,
+ actor: { type: ActorType.SCEP_ACCOUNT, metadata: { profileId: profile.id } },
+ event: {
+ type: EventType.SCEP_DYNAMIC_CHALLENGE_GENERATED,
+ metadata: {
+ profileId: profile.id,
+ profileSlug: profile.slug,
+ expiresAt: expiresAt.toISOString(),
+ clientIp: clientIp || "unknown"
+ }
+ }
+ });
+
+ return { challenge: challengePlaintext };
+ };
+
return {
getCaCaps,
getCaCert,
- handlePkiOperation
+ handlePkiOperation,
+ generateDynamicChallenge
};
};
diff --git a/backend/src/ee/services/pki-scep/pki-scep-types.ts b/backend/src/ee/services/pki-scep/pki-scep-types.ts
index f752fb81c6..f343c81506 100644
--- a/backend/src/ee/services/pki-scep/pki-scep-types.ts
+++ b/backend/src/ee/services/pki-scep/pki-scep-types.ts
@@ -1,3 +1,5 @@
+import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
+
export enum ScepMessageType {
CertRep = "3",
RenewalReq = "17",
@@ -63,3 +65,12 @@ export type THandlePkiOperationDTO = {
message: Buffer;
clientIp: string;
};
+
+export type TGenerateDynamicChallengeDTO = {
+ profileId: string;
+ clientIp: string;
+ actor: ActorType;
+ actorId: string;
+ actorAuthMethod: ActorAuthMethod;
+ actorOrgId: string;
+};
diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.ts
index b155a12dfb..b8ccda18ec 100644
--- a/backend/src/server/plugins/auth/inject-identity.ts
+++ b/backend/src/server/plugins/auth/inject-identity.ts
@@ -150,7 +150,11 @@ export const injectIdentity = fp(
return;
}
- if (req.url.includes(".well-known/est") || req.url.includes("/scep/") || req.url.includes("/api/v3/auth/")) {
+ if (req.url.includes(".well-known/est") || req.url.includes("/api/v3/auth/")) {
+ return;
+ }
+
+ if (req.url.includes("/scep/") && !req.url.includes("/challenge")) {
return;
}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 7d51408344..2141ae0d71 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -122,6 +122,7 @@ import { pkiDiscoveryQueueFactory } from "@app/ee/services/pki-discovery/pki-dis
import { pkiDiscoveryScanHistoryDALFactory } from "@app/ee/services/pki-discovery/pki-discovery-scan-history-dal";
import { pkiDiscoveryServiceFactory } from "@app/ee/services/pki-discovery/pki-discovery-service";
import { pkiInstallationServiceFactory } from "@app/ee/services/pki-discovery/pki-installation-service";
+import { scepDynamicChallengeDALFactory } from "@app/ee/services/pki-scep/pki-scep-dynamic-challenge-dal";
import { pkiScepServiceFactory } from "@app/ee/services/pki-scep/pki-scep-service";
import { scepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";
import { projectEventsServiceFactory } from "@app/ee/services/project-events/project-events-service";
@@ -1240,6 +1241,7 @@ export const registerRoutes = async (
const acmeEnrollmentConfigDAL = acmeEnrollmentConfigDALFactory(db);
const scepEnrollmentConfigDAL = scepEnrollmentConfigDALFactory(db);
const scepTransactionDAL = scepTransactionDALFactory(db);
+ const scepDynamicChallengeDAL = scepDynamicChallengeDALFactory(db);
const acmeAccountDAL = pkiAcmeAccountDALFactory(db);
const acmeOrderDAL = pkiAcmeOrderDALFactory(db);
const acmeAuthDAL = pkiAcmeAuthDALFactory(db);
@@ -2610,6 +2612,7 @@ export const registerRoutes = async (
certificateV3Service,
certificateProfileDAL,
scepEnrollmentConfigDAL,
+ scepDynamicChallengeDAL,
scepTransactionDAL,
certificateAuthorityDAL,
certificateAuthorityCertDAL,
@@ -2622,7 +2625,8 @@ export const registerRoutes = async (
certificatePolicyService,
certificateRequestService,
certificateIssuanceQueue,
- auditLogService
+ auditLogService,
+ permissionService
});
const acmeChallengeService = pkiAcmeChallengeServiceFactory({
diff --git a/backend/src/server/routes/v1/certificate-profiles-router.ts b/backend/src/server/routes/v1/certificate-profiles-router.ts
index 37a53e8c75..0d2f8ef179 100644
--- a/backend/src/server/routes/v1/certificate-profiles-router.ts
+++ b/backend/src/server/routes/v1/certificate-profiles-router.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { PkiCertificateProfilesSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
import { ApiDocsTags } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
@@ -87,9 +88,12 @@ export const registerCertificateProfilesRouter = async (
.optional(),
scepConfig: z
.object({
- challengePassword: z.string().min(8),
+ challengeType: z.nativeEnum(ScepChallengeType).default(ScepChallengeType.STATIC),
+ challengePassword: z.string().optional(),
includeCaCertInResponse: z.boolean().optional(),
- allowCertBasedRenewal: z.boolean().optional()
+ allowCertBasedRenewal: z.boolean().optional(),
+ dynamicChallengeExpiryMinutes: z.number().int().min(1).max(1440).default(60),
+ dynamicChallengeMaxPending: z.number().int().min(1).max(1000).default(100)
})
.optional(),
externalConfigs: ExternalConfigUnionSchema,
@@ -195,12 +199,15 @@ export const registerCertificateProfilesRouter = async (
.refine(
(data) => {
if (data.enrollmentType === EnrollmentType.SCEP) {
- return !!data.scepConfig?.challengePassword;
+ if (!data.scepConfig) return false;
+ // Static mode requires a challenge password with min 8 chars; dynamic mode does not
+ if (data.scepConfig.challengeType === ScepChallengeType.DYNAMIC) return true;
+ return !!data.scepConfig.challengePassword && data.scepConfig.challengePassword.length >= 8;
}
return true;
},
{
- message: "SCEP enrollment type requires SCEP configuration with a challenge password"
+ message: "SCEP static challenge requires a challenge password with at least 8 characters"
}
)
.refine(
@@ -357,7 +364,11 @@ export const registerCertificateProfilesRouter = async (
raCertificatePem: z.string(),
raCertExpiresAt: z.date(),
includeCaCertInResponse: z.boolean(),
- allowCertBasedRenewal: z.boolean()
+ allowCertBasedRenewal: z.boolean(),
+ challengeType: z.string(),
+ challengeEndpointUrl: z.string().optional(),
+ dynamicChallengeExpiryMinutes: z.number(),
+ dynamicChallengeMaxPending: z.number()
})
.optional(),
externalConfigs: ExternalConfigUnionSchema,
@@ -459,7 +470,11 @@ export const registerCertificateProfilesRouter = async (
raCertificatePem: z.string(),
raCertExpiresAt: z.date(),
includeCaCertInResponse: z.boolean(),
- allowCertBasedRenewal: z.boolean()
+ allowCertBasedRenewal: z.boolean(),
+ challengeType: z.string(),
+ challengeEndpointUrl: z.string().optional(),
+ dynamicChallengeExpiryMinutes: z.number(),
+ dynamicChallengeMaxPending: z.number()
})
.optional(),
externalConfigs: ExternalConfigUnionSchema
@@ -578,9 +593,12 @@ export const registerCertificateProfilesRouter = async (
.optional(),
scepConfig: z
.object({
- challengePassword: z.string().min(8).optional(),
+ challengeType: z.nativeEnum(ScepChallengeType).optional(),
+ challengePassword: z.string().optional(),
includeCaCertInResponse: z.boolean().optional(),
- allowCertBasedRenewal: z.boolean().optional()
+ allowCertBasedRenewal: z.boolean().optional(),
+ dynamicChallengeExpiryMinutes: z.number().int().min(1).max(1440).optional(),
+ dynamicChallengeMaxPending: z.number().int().min(1).max(1000).optional()
})
.optional(),
externalConfigs: ExternalConfigUnionSchema,
diff --git a/backend/src/services/certificate-profile/certificate-profile-dal.ts b/backend/src/services/certificate-profile/certificate-profile-dal.ts
index b0ba1f02c7..2276483277 100644
--- a/backend/src/services/certificate-profile/certificate-profile-dal.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-dal.ts
@@ -205,7 +205,16 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
db
.ref("allowCertBasedRenewal")
.withSchema(TableName.PkiScepEnrollmentConfig)
- .as("scepConfigAllowCertBasedRenewal")
+ .as("scepConfigAllowCertBasedRenewal"),
+ db.ref("challengeType").withSchema(TableName.PkiScepEnrollmentConfig).as("scepConfigChallengeType"),
+ db
+ .ref("dynamicChallengeExpiryMinutes")
+ .withSchema(TableName.PkiScepEnrollmentConfig)
+ .as("scepConfigDynamicChallengeExpiryMinutes"),
+ db
+ .ref("dynamicChallengeMaxPending")
+ .withSchema(TableName.PkiScepEnrollmentConfig)
+ .as("scepConfigDynamicChallengeMaxPending")
)
.where(`${TableName.PkiCertificateProfile}.id`, id)
.first();
@@ -247,7 +256,10 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
raCertificatePem: result.scepConfigRaCertificate,
raCertExpiresAt: result.scepConfigRaCertExpiresAt,
includeCaCertInResponse: result.scepConfigIncludeCaCertInResponse ?? true,
- allowCertBasedRenewal: result.scepConfigAllowCertBasedRenewal ?? true
+ allowCertBasedRenewal: result.scepConfigAllowCertBasedRenewal ?? true,
+ challengeType: result.scepConfigChallengeType,
+ dynamicChallengeExpiryMinutes: result.scepConfigDynamicChallengeExpiryMinutes,
+ dynamicChallengeMaxPending: result.scepConfigDynamicChallengeMaxPending
} as TCertificateProfileWithConfigs["scepConfig"])
: undefined;
@@ -430,7 +442,16 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
.ref("includeCaCertInResponse")
.withSchema(TableName.PkiScepEnrollmentConfig)
.as("scepIncludeCaCertInResponse"),
- db.ref("allowCertBasedRenewal").withSchema(TableName.PkiScepEnrollmentConfig).as("scepAllowCertBasedRenewal")
+ db.ref("allowCertBasedRenewal").withSchema(TableName.PkiScepEnrollmentConfig).as("scepAllowCertBasedRenewal"),
+ db.ref("challengeType").withSchema(TableName.PkiScepEnrollmentConfig).as("scepChallengeType"),
+ db
+ .ref("dynamicChallengeExpiryMinutes")
+ .withSchema(TableName.PkiScepEnrollmentConfig)
+ .as("scepDynamicChallengeExpiryMinutes"),
+ db
+ .ref("dynamicChallengeMaxPending")
+ .withSchema(TableName.PkiScepEnrollmentConfig)
+ .as("scepDynamicChallengeMaxPending")
);
if (processedRules) {
@@ -479,7 +500,10 @@ export const certificateProfileDALFactory = (db: TDbClient) => {
raCertificatePem: result.scepRaCertificate as string,
raCertExpiresAt: result.scepRaCertExpiresAt as Date,
includeCaCertInResponse: (result.scepIncludeCaCertInResponse as boolean) ?? true,
- allowCertBasedRenewal: (result.scepAllowCertBasedRenewal as boolean) ?? true
+ allowCertBasedRenewal: (result.scepAllowCertBasedRenewal as boolean) ?? true,
+ challengeType: result.scepChallengeType as string,
+ dynamicChallengeExpiryMinutes: result.scepDynamicChallengeExpiryMinutes as number,
+ dynamicChallengeMaxPending: result.scepDynamicChallengeMaxPending as number
}
: undefined;
diff --git a/backend/src/services/certificate-profile/certificate-profile-service.ts b/backend/src/services/certificate-profile/certificate-profile-service.ts
index dc392b5c8e..b52cb862bb 100644
--- a/backend/src/services/certificate-profile/certificate-profile-service.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-service.ts
@@ -9,6 +9,7 @@ import {
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
import { buildUrl } from "@app/ee/services/pki-acme/pki-acme-fns";
+import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
import { generateRaCertificate } 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";
@@ -414,9 +415,12 @@ export const certificateProfileServiceFactory = ({
encryptedRaPrivateKey: Buffer;
raCertificatePem: string;
raCertExpiresAt: Date;
- hashedChallengePassword: string;
+ hashedChallengePassword: string | null;
+ challengeType: string;
includeCaCertInResponse: boolean;
allowCertBasedRenewal: boolean;
+ dynamicChallengeExpiryMinutes: number;
+ dynamicChallengeMaxPending: number;
}
| undefined;
@@ -433,18 +437,26 @@ export const certificateProfileServiceFactory = ({
plainText: Buffer.from(raCert.privateKeyDer)
});
- const appCfg = getConfig();
- const hashedChallengePassword = await crypto
- .hashing()
- .createHash(data.scepConfig.challengePassword, appCfg.SALT_ROUNDS);
+ const challengeType = (data.scepConfig.challengeType as ScepChallengeType) || ScepChallengeType.STATIC;
+ let hashedChallengePassword: string | null = null;
+
+ if (challengeType === ScepChallengeType.STATIC && data.scepConfig.challengePassword) {
+ const appCfg = getConfig();
+ hashedChallengePassword = await crypto
+ .hashing()
+ .createHash(data.scepConfig.challengePassword, appCfg.SALT_ROUNDS);
+ }
precomputedScepConfig = {
encryptedRaPrivateKey,
raCertificatePem: raCert.certificatePem,
raCertExpiresAt: raCert.expiresAt,
hashedChallengePassword,
+ challengeType,
includeCaCertInResponse: data.scepConfig.includeCaCertInResponse ?? true,
- allowCertBasedRenewal: data.scepConfig.allowCertBasedRenewal ?? true
+ allowCertBasedRenewal: data.scepConfig.allowCertBasedRenewal ?? true,
+ dynamicChallengeExpiryMinutes: data.scepConfig.dynamicChallengeExpiryMinutes ?? 60,
+ dynamicChallengeMaxPending: data.scepConfig.dynamicChallengeMaxPending ?? 100
};
}
@@ -507,8 +519,11 @@ export const certificateProfileServiceFactory = ({
raCertificate: precomputedScepConfig.raCertificatePem,
raCertExpiresAt: precomputedScepConfig.raCertExpiresAt,
hashedChallengePassword: precomputedScepConfig.hashedChallengePassword,
+ challengeType: precomputedScepConfig.challengeType,
includeCaCertInResponse: precomputedScepConfig.includeCaCertInResponse,
- allowCertBasedRenewal: precomputedScepConfig.allowCertBasedRenewal
+ allowCertBasedRenewal: precomputedScepConfig.allowCertBasedRenewal,
+ dynamicChallengeExpiryMinutes: precomputedScepConfig.dynamicChallengeExpiryMinutes,
+ dynamicChallengeMaxPending: precomputedScepConfig.dynamicChallengeMaxPending
},
tx
);
@@ -711,12 +726,21 @@ export const certificateProfileServiceFactory = ({
if (scepConfig && existingProfile.scepConfigId) {
const scepUpdateData: {
- hashedChallengePassword?: string;
+ hashedChallengePassword?: string | null;
+ challengeType?: string;
includeCaCertInResponse?: boolean;
allowCertBasedRenewal?: boolean;
+ dynamicChallengeExpiryMinutes?: number;
+ dynamicChallengeMaxPending?: number;
} = {};
- if (scepConfig.challengePassword) {
+ if (scepConfig.challengeType !== undefined) {
+ scepUpdateData.challengeType = scepConfig.challengeType;
+ if (scepConfig.challengeType === ScepChallengeType.DYNAMIC) {
+ scepUpdateData.hashedChallengePassword = null;
+ }
+ }
+ if (scepConfig.challengePassword && scepUpdateData.challengeType !== ScepChallengeType.DYNAMIC) {
scepUpdateData.hashedChallengePassword = await crypto
.hashing()
.createHash(scepConfig.challengePassword, getConfig().SALT_ROUNDS);
@@ -727,6 +751,12 @@ export const certificateProfileServiceFactory = ({
if (scepConfig.allowCertBasedRenewal !== undefined) {
scepUpdateData.allowCertBasedRenewal = scepConfig.allowCertBasedRenewal;
}
+ if (scepConfig.dynamicChallengeExpiryMinutes !== undefined) {
+ scepUpdateData.dynamicChallengeExpiryMinutes = scepConfig.dynamicChallengeExpiryMinutes;
+ }
+ if (scepConfig.dynamicChallengeMaxPending !== undefined) {
+ scepUpdateData.dynamicChallengeMaxPending = scepConfig.dynamicChallengeMaxPending;
+ }
if (Object.keys(scepUpdateData).length > 0) {
await scepEnrollmentConfigDAL.updateById(existingProfile.scepConfigId, scepUpdateData, tx);
}
@@ -839,6 +869,9 @@ export const certificateProfileServiceFactory = ({
const appCfg = getConfig();
const siteUrl = appCfg.SITE_URL ?? "";
profile.scepConfig.scepEndpointUrl = `${siteUrl}/scep/${profile.id}/pkiclient.exe`;
+ if (profile.scepConfig.challengeType === ScepChallengeType.DYNAMIC) {
+ profile.scepConfig.challengeEndpointUrl = `${siteUrl}/scep/${profile.id}/challenge`;
+ }
}
// Parse externalConfigs from JSON string to object if it exists
@@ -1017,7 +1050,13 @@ export const certificateProfileServiceFactory = ({
? { ...profileWithConfigs.acmeConfig, directoryUrl: buildUrl(profile.id, "/directory") }
: undefined,
scepConfig: profileWithConfigs.scepConfig
- ? { ...profileWithConfigs.scepConfig, scepEndpointUrl: `${siteUrl}/scep/${profile.id}/pkiclient.exe` }
+ ? {
+ ...profileWithConfigs.scepConfig,
+ scepEndpointUrl: `${siteUrl}/scep/${profile.id}/pkiclient.exe`,
+ ...(profileWithConfigs.scepConfig.challengeType === ScepChallengeType.DYNAMIC
+ ? { challengeEndpointUrl: `${siteUrl}/scep/${profile.id}/challenge` }
+ : {})
+ }
: undefined
};
diff --git a/backend/src/services/certificate-profile/certificate-profile-types.ts b/backend/src/services/certificate-profile/certificate-profile-types.ts
index 5d38505e46..b8bf90f4cc 100644
--- a/backend/src/services/certificate-profile/certificate-profile-types.ts
+++ b/backend/src/services/certificate-profile/certificate-profile-types.ts
@@ -80,9 +80,12 @@ export type TCertificateProfileUpdate = Omit<
skipEabBinding?: boolean;
};
scepConfig?: {
+ challengeType?: string;
challengePassword?: string;
includeCaCertInResponse?: boolean;
allowCertBasedRenewal?: boolean;
+ dynamicChallengeExpiryMinutes?: number;
+ dynamicChallengeMaxPending?: number;
};
};
@@ -130,6 +133,10 @@ export type TCertificateProfileWithConfigs = TCertificateProfile & {
raCertExpiresAt: Date;
includeCaCertInResponse: boolean;
allowCertBasedRenewal: boolean;
+ challengeType: string;
+ challengeEndpointUrl?: string;
+ dynamicChallengeExpiryMinutes: number;
+ dynamicChallengeMaxPending: number;
};
};
diff --git a/backend/src/services/enrollment-config/enrollment-config-types.ts b/backend/src/services/enrollment-config/enrollment-config-types.ts
index badf981a17..afc31220b9 100644
--- a/backend/src/services/enrollment-config/enrollment-config-types.ts
+++ b/backend/src/services/enrollment-config/enrollment-config-types.ts
@@ -52,7 +52,10 @@ export type TScepEnrollmentConfigInsert = TPkiScepEnrollmentConfigsInsert;
export type TScepEnrollmentConfigUpdate = TPkiScepEnrollmentConfigsUpdate;
export interface TScepConfigData {
- challengePassword: string;
+ challengeType?: string;
+ challengePassword?: string;
includeCaCertInResponse?: boolean;
allowCertBasedRenewal?: boolean;
+ dynamicChallengeExpiryMinutes?: number;
+ dynamicChallengeMaxPending?: number;
}
diff --git a/docs/documentation/platform/pki/enrollment-methods/scep.mdx b/docs/documentation/platform/pki/enrollment-methods/scep.mdx
index ba27c3aac5..ba6ec25ebd 100644
--- a/docs/documentation/platform/pki/enrollment-methods/scep.mdx
+++ b/docs/documentation/platform/pki/enrollment-methods/scep.mdx
@@ -27,6 +27,43 @@ For self-hosted Infisical instances, replace `app.infisical.com` with your insta
- A SCEP-compatible client (e.g., [sscep](https://github.com/certnanny/sscep)) or a network device with built-in SCEP support.
- A certificate profile with a **CA-issued** issuer type.
+## Challenge Types
+
+Infisical supports two challenge authentication modes for SCEP enrollment:
+
+<Tabs>
+ <Tab title="Static Challenge">
+ A single shared secret password is configured on the certificate profile. All SCEP clients must include this password in their certificate signing request (CSR) to authenticate.
+
+ This is the simplest option and works well when the same challenge password is acceptable for all devices enrolling through the profile.
+
+ - The challenge password must be at least 8 characters.
+ - The password is hashed before storage and cannot be retrieved after creation.
+ </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.
+
+ This mode is designed for MDM tools like **Jamf Pro** that support fetching a challenge from an external webhook before delivering the SCEP profile to a device.
+
+ When dynamic challenges are enabled, Infisical exposes a challenge endpoint at:
+
+ ```
+ https://app.infisical.com/scep/{profile_id}/challenge
+ ```
+
+ The endpoint accepts authenticated `POST` requests and returns a plain-text one-time challenge password. The caller must authenticate using a [Machine Identity](/documentation/platform/identities/machine-identities) access token.
+
+ Configuration options for dynamic challenges:
+
+ - **Challenge Expiry (minutes)**: How long each generated challenge remains valid before expiring. Default: 60 minutes. Maximum: 1440 minutes (24 hours).
+ - **Max Pending Challenges**: Maximum number of unused challenges that can exist at once. Default: 100. Maximum: 1000.
+
+ <Note>
+ Dynamic challenges are consumed on first use. Once a device successfully enrolls with a challenge, that challenge cannot be reused. Expired and used challenges are automatically cleaned up.
+ </Note>
+ </Tab>
+</Tabs>
+
## Guide to Certificate Enrollment via SCEP
In the following steps, we walk through how to issue an X.509 certificate using the SCEP enrollment method.
@@ -37,7 +74,10 @@ In the following steps, we walk through how to issue an X.509 certificate using
Here's some guidance on each SCEP-specific configuration field:
- - **Challenge Password**: 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 Type**: Select **Static** for a shared password or **Dynamic** for one-time-use challenges generated via API. See [Challenge Types](#challenge-types) above.
+ - **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.
- **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).
@@ -53,79 +93,114 @@ In the following steps, we walk through how to issue an X.509 certificate using
Where `{profile_id}` is the UUID of the certificate profile. This is the URL you provide to your SCEP clients as the SCEP server URL.
+ For profiles with **dynamic challenges** enabled, you will also see a **Challenge Endpoint URL**:
+
+ ```
+ https://app.infisical.com/scep/{profile_id}/challenge
+ ```
+
+ This is the URL your MDM tool or automation calls to generate one-time challenge passwords.
+
</Step>
<Step title="Configure your SCEP client and enroll">
Provide the **SCEP endpoint URL** and **challenge password** from the previous steps to your SCEP client.
- Below is an example using [sscep](https://github.com/certnanny/sscep), an open-source SCEP client.
+ <Tabs>
+ <Tab title="Static Challenge">
+ Below is an example using [sscep](https://github.com/certnanny/sscep), an open-source SCEP client.
- **1. Retrieve the CA/RA certificates:**
+ **1. Retrieve the CA/RA certificates:**
- ```bash
- sscep getca \
- -u https://app.infisical.com/scep/{profile_id}/pkiclient.exe \
- -c ca.pem
- ```
+ ```bash
+ sscep getca \
+ -u https://app.infisical.com/scep/{profile_id}/pkiclient.exe \
+ -c ca.pem
+ ```
- This writes the RA certificate to `ca.pem-0` and the CA certificate to `ca.pem-1` (when "Include CA Cert in Response" is enabled).
+ This writes the RA certificate to `ca.pem-0` and the CA certificate to `ca.pem-1` (when "Include CA Cert in Response" is enabled).
- **2. Generate a device key and CSR with the challenge password:**
+ **2. Generate a device key and CSR with the challenge password:**
- The challenge password must be embedded in the CSR as a PKCS#9 attribute. Create an OpenSSL config file to include it:
+ The challenge password must be embedded in the CSR as a PKCS#9 attribute. Create an OpenSSL config file to include it:
- ```bash
- cat > device-csr.cnf << 'EOF'
- [req]
- default_bits = 2048
- prompt = no
- distinguished_name = dn
- attributes = req_attributes
-
- [dn]
- CN = my-device.example.com
-
- [req_attributes]
- challengePassword = your-challenge-password
- EOF
-
- # Generate the key and CSR
- openssl genrsa -out device.key 2048
- openssl req -new -key device.key -out device.csr -config device-csr.cnf
- ```
+ ```bash
+ cat > device-csr.cnf << 'EOF'
+ [req]
+ default_bits = 2048
+ prompt = no
+ distinguished_name = dn
+ attributes = req_attributes
- **3. Create a self-signed certificate for the sscep signing identity:**
+ [dn]
+ CN = my-device.example.com
- sscep requires a local signing certificate to sign the SCEP request envelope:
+ [req_attributes]
+ challengePassword = your-challenge-password
+ EOF
- ```bash
- openssl x509 -req -in device.csr -signkey device.key \
- -out device-selfsigned.pem -days 1
- ```
+ # Generate the key and CSR
+ openssl genrsa -out device.key 2048
+ openssl req -new -key device.key -out device.csr -config device-csr.cnf
+ ```
- **4. Enroll via SCEP:**
+ **3. Create a self-signed certificate for the sscep signing identity:**
- ```bash
- sscep enroll \
- -u https://app.infisical.com/scep/{profile_id}/pkiclient.exe \
- -c ca.pem-0 \
- -k device.key \
- -r device.csr \
- -l device-cert.pem \
- -K device.key \
- -O device-selfsigned.pem \
- -E aes256 \
- -S sha256
- ```
+ sscep requires a local signing certificate to sign the SCEP request envelope:
- On success, the issued certificate is written to `device-cert.pem`.
+ ```bash
+ openssl x509 -req -in device.csr -signkey device.key \
+ -out device-selfsigned.pem -days 1
+ ```
- <Note>
- Flag reference for the enroll command:
- - `-c ca.pem-0` is the RA certificate from step 1
- - `-K` / `-O` are the signing key and self-signed certificate used to sign the SCEP message envelope
- - `-E aes256` selects AES-256-CBC encryption
- - `-S sha256` selects SHA-256 for the message digest
- </Note>
+ **4. Enroll via SCEP:**
+
+ ```bash
+ sscep enroll \
+ -u https://app.infisical.com/scep/{profile_id}/pkiclient.exe \
+ -c ca.pem-0 \
+ -k device.key \
+ -r device.csr \
+ -l device-cert.pem \
+ -K device.key \
+ -O device-selfsigned.pem \
+ -E aes256 \
+ -S sha256
+ ```
+
+ On success, the issued certificate is written to `device-cert.pem`.
+
+ <Note>
+ Flag reference for the enroll command:
+ - `-c ca.pem-0` is the RA certificate from step 1
+ - `-K` / `-O` are the signing key and self-signed certificate used to sign the SCEP message envelope
+ - `-E aes256` selects AES-256-CBC encryption
+ - `-S sha256` selects SHA-256 for the message digest
+ </Note>
+ </Tab>
+ <Tab title="Dynamic Challenge">
+ For dynamic challenges, you first generate a one-time challenge password via the API, then use it as the challenge password in the SCEP enrollment.
+
+ **1. Generate a dynamic challenge:**
+
+ ```bash
+ curl -s -X POST \
+ https://app.infisical.com/scep/{profile_id}/challenge \
+ -H "Authorization: Bearer <machine-identity-access-token>"
+ ```
+
+ The response body is the plain-text challenge password. Save it for use in the enrollment.
+
+ **2. Use the challenge in your SCEP enrollment:**
+
+ Follow the same steps as the static challenge flow above, but use the dynamically generated challenge password instead of a fixed one.
+
+ <Note>
+ Each dynamic challenge can only be used once. If enrollment fails, generate a new challenge and retry.
+ </Note>
+
+ For MDM integrations (Jamf Pro, Ivanti, etc.), the MDM tool handles this automatically via webhook. See the [Jamf Pro integration guide](/documentation/platform/pki/integration-guides/jamf-pro-scep) for details.
+ </Tab>
+ </Tabs>
<Note>
SCEP uses CMS/PKCS#7 encrypted messages to protect the certificate request in transit. The challenge password is included inside the encrypted envelope and is never sent in plaintext over the network.
@@ -173,6 +248,11 @@ Infisical's SCEP server supports the following algorithms for the CMS message ex
<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.
</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.
+
+ Use **dynamic challenges** when integrating with MDM tools (Jamf Pro, Ivanti, Workspace ONE) that support fetching one-time challenges via webhook. Dynamic challenges provide stronger security since each challenge can only be used once and expires automatically.
+ </Accordion>
<Accordion title="Can devices renew their certificates without the challenge password?">
Yes, if **Allow Certificate-Based Renewal** is enabled on the certificate profile. Devices that already hold a valid certificate issued by the same CA can submit a renewal request (RenewalReq) signed with their existing certificate, without needing the challenge password.
</Accordion>
diff --git a/docs/documentation/platform/pki/integration-guides/jamf-pro-scep.mdx b/docs/documentation/platform/pki/integration-guides/jamf-pro-scep.mdx
index fcaea5d1aa..2a47e759c3 100644
--- a/docs/documentation/platform/pki/integration-guides/jamf-pro-scep.mdx
+++ b/docs/documentation/platform/pki/integration-guides/jamf-pro-scep.mdx
@@ -7,6 +7,8 @@ This guide demonstrates how to use Infisical to issue and distribute certificate
With this integration, Jamf Pro acts as the SCEP client on behalf of your managed devices, once a configuration profile is saved and scoped, enrolled devices automatically receive certificates issued by your Infisical Certificate Manager without any manual intervention on the device.
+Infisical supports both **static** and **dynamic** SCEP challenges with Jamf Pro. Dynamic challenges provide stronger security by generating a unique, one-time-use challenge password for each device enrollment.
+
## Prerequisites
Before you begin, make sure you have:
@@ -14,6 +16,7 @@ Before you begin, make sure you have:
- A [Jamf Pro](https://www.jamf.com/products/jamf-pro/) instance with administrative access.
- A [certificate profile](/documentation/platform/pki/certificates/profiles) configured with the [SCEP enrollment method](/documentation/platform/pki/enrollment-methods/scep) in Infisical. Refer to the [SCEP enrollment guide](/documentation/platform/pki/enrollment-methods/scep) for setup instructions.
- One or more computers or mobile devices enrolled in Jamf Pro.
+- For **dynamic challenges**: A [Machine Identity](/documentation/platform/identities/machine-identities) with access to the project containing the certificate profile.
## Guide
@@ -24,7 +27,34 @@ Before you begin, make sure you have:
From the certificate profile, gather the following values:
- **SCEP URL**: The SCEP endpoint URL for your certificate profile. This takes the form `https://app.infisical.com/scep/{profile_id}/pkiclient.exe`. For self-hosted instances, replace `app.infisical.com` with your instance's domain.
- - **Challenge Password**: The shared secret configured on the SCEP enrollment method.
+
+ <Tabs>
+ <Tab title="Static Challenge">
+ - **Challenge Password**: The shared secret configured on the SCEP enrollment method.
+ </Tab>
+ <Tab title="Dynamic Challenge">
+ - **Challenge Endpoint URL**: The authenticated endpoint for generating one-time challenges. This takes the form `https://app.infisical.com/scep/{profile_id}/challenge`.
+ - **Machine Identity Access Token**: An access token for a Machine Identity with permissions on the project. You can obtain this by authenticating a [Machine Identity](/documentation/platform/identities/machine-identities) configured with [Token Auth](/documentation/platform/identities/token-auth).
+
+ With dynamic challenges, Jamf Pro calls a webhook to fetch a one-time challenge password for each device enrollment. Configure this webhook now:
+
+ ![Jamf Pro webhook configuration for SCEP challenges](/images/platform/pki/integrations/jamf-pro/jamf-webhook-config.png)
+
+ 1. In Jamf Pro, navigate to **Settings** > **Global Management** > **Webhooks**.
+ 2. Click **+ New** to create a new webhook.
+ 3. Configure the webhook with the following settings:
+ - **Display Name**: A descriptive name (e.g., `Infisical SCEP Challenge`).
+ - **Enabled**: Check this box.
+ - **Webhook URL**: Enter the **Challenge Endpoint URL** from above.
+ - **Authentication Type**: Select **Header Authentication**.
+ - **Header Name**: Enter `Authorization`.
+ - **Header Value**: Enter `Bearer <your-machine-identity-access-token>`.
+ - **Content Type**: Select **JSON**.
+ - **Webhook Event**: Select **SCEPChallenge**.
+ 4. Click **Save**.
+ </Tab>
+ </Tabs>
+
</Step>
<Step title="Create a configuration profile in Jamf Pro">
@@ -70,6 +100,13 @@ Before you begin, make sure you have:
![SCEP configuration — Challenge and certificate options](/images/platform/pki/integrations/jamf-pro/scep-config-challenge.png)
</Tab>
+ <Tab title="Dynamic">
+ - **Challenge Type**: Select **Dynamic** from the dropdown.
+
+ No manual challenge password entry is needed, Jamf Pro automatically calls the webhook configured in step 1 to fetch a one-time challenge for each device enrollment.
+
+ ![SCEP configuration — Dynamic challenge type selected](/images/platform/pki/integrations/jamf-pro/scep-config-challenge-dynamic.png)
+ </Tab>
</Tabs>
Finally, configure the remaining certificate options:
diff --git a/docs/images/platform/pki/integrations/jamf-pro/jamf-webhook-config.png b/docs/images/platform/pki/integrations/jamf-pro/jamf-webhook-config.png
new file mode 100644
index 0000000000..1169a466b8
Binary files /dev/null and b/docs/images/platform/pki/integrations/jamf-pro/jamf-webhook-config.png differ
diff --git a/docs/images/platform/pki/integrations/jamf-pro/scep-config-challenge-dynamic.png b/docs/images/platform/pki/integrations/jamf-pro/scep-config-challenge-dynamic.png
new file mode 100644
index 0000000000..c6023bbec5
Binary files /dev/null and b/docs/images/platform/pki/integrations/jamf-pro/scep-config-challenge-dynamic.png differ
diff --git a/frontend/src/hooks/api/certificateProfiles/types.ts b/frontend/src/hooks/api/certificateProfiles/types.ts
index 76c432a91e..40ddde6952 100644
--- a/frontend/src/hooks/api/certificateProfiles/types.ts
+++ b/frontend/src/hooks/api/certificateProfiles/types.ts
@@ -10,6 +10,11 @@ export enum IssuerType {
SELF_SIGNED = "self-signed"
}
+export enum ScepChallengeType {
+ STATIC = "static",
+ DYNAMIC = "dynamic"
+}
+
export type TCertificateProfileDefaults = {
ttlDays?: number;
commonName?: string;
@@ -89,6 +94,10 @@ export type TCertificateProfileWithDetails = TCertificateProfile & {
raCertExpiresAt: string;
includeCaCertInResponse: boolean;
allowCertBasedRenewal: boolean;
+ challengeType: ScepChallengeType;
+ challengeEndpointUrl?: string;
+ dynamicChallengeExpiryMinutes: number;
+ dynamicChallengeMaxPending: number;
};
};
@@ -114,9 +123,12 @@ export type TCreateCertificateProfileDTO = {
skipEabBinding?: boolean;
};
scepConfig?: {
- challengePassword: string;
+ challengeType?: ScepChallengeType;
+ challengePassword?: string;
includeCaCertInResponse?: boolean;
allowCertBasedRenewal?: boolean;
+ dynamicChallengeExpiryMinutes?: number;
+ dynamicChallengeMaxPending?: number;
};
externalConfigs?: Record<string, unknown> | null;
defaults?: TCertificateProfileDefaults | null;
@@ -142,9 +154,12 @@ export type TUpdateCertificateProfileDTO = {
skipEabBinding?: boolean;
};
scepConfig?: {
+ challengeType?: ScepChallengeType;
challengePassword?: string;
includeCaCertInResponse?: boolean;
allowCertBasedRenewal?: boolean;
+ dynamicChallengeExpiryMinutes?: number;
+ dynamicChallengeMaxPending?: number;
};
externalConfigs?: Record<string, unknown> | null;
defaults?: TCertificateProfileDefaults | null;
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
index f79dfbaf8f..d7b9e11531 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/CreateProfileModal.tsx
@@ -44,6 +44,7 @@ import {
import {
EnrollmentType,
IssuerType,
+ ScepChallengeType,
TCertificateProfileDefaults,
TCertificateProfileWithDetails,
TCreateCertificateProfileDTO,
@@ -174,9 +175,12 @@ const createSchema = z
.optional(),
scepConfig: z
.object({
- challengePassword: z.string().min(8, "Challenge password must be at least 8 characters"),
+ challengeType: z.nativeEnum(ScepChallengeType).default(ScepChallengeType.STATIC),
+ challengePassword: z.string().optional(),
includeCaCertInResponse: z.boolean().optional(),
- allowCertBasedRenewal: z.boolean().optional()
+ allowCertBasedRenewal: z.boolean().optional(),
+ dynamicChallengeExpiryMinutes: z.number().min(1).max(1440).optional(),
+ dynamicChallengeMaxPending: z.number().min(1).max(1000).optional()
})
.optional(),
externalConfigs: z
@@ -230,6 +234,23 @@ const createSchema = z
message: "SCEP enrollment type requires SCEP configuration"
}
)
+ .refine(
+ (data) => {
+ if (
+ data.enrollmentType === EnrollmentType.SCEP &&
+ data.scepConfig &&
+ data.scepConfig.challengeType !== ScepChallengeType.DYNAMIC &&
+ (!data.scepConfig.challengePassword || data.scepConfig.challengePassword.length < 8)
+ ) {
+ return false;
+ }
+ return true;
+ },
+ {
+ message: "Challenge password must be at least 8 characters for static challenges",
+ path: ["scepConfig", "challengePassword"]
+ }
+ )
.refine(
(data) => {
if (data.enrollmentType === EnrollmentType.EST) {
@@ -360,9 +381,12 @@ const editSchema = z
.optional(),
scepConfig: z
.object({
- challengePassword: z.string().min(8, "Challenge password must be at least 8 characters"),
+ challengeType: z.nativeEnum(ScepChallengeType).default(ScepChallengeType.STATIC),
+ challengePassword: z.string().optional(),
includeCaCertInResponse: z.boolean().optional(),
- allowCertBasedRenewal: z.boolean().optional()
+ allowCertBasedRenewal: z.boolean().optional(),
+ dynamicChallengeExpiryMinutes: z.number().min(1).max(1440).optional(),
+ dynamicChallengeMaxPending: z.number().min(1).max(1000).optional()
})
.optional(),
externalConfigs: z
@@ -416,6 +440,25 @@ const editSchema = z
message: "SCEP enrollment type requires SCEP configuration"
}
)
+ .refine(
+ (data) => {
+ if (
+ data.enrollmentType === EnrollmentType.SCEP &&
+ data.scepConfig &&
+ data.scepConfig.challengeType !== ScepChallengeType.DYNAMIC &&
+ data.scepConfig.challengePassword &&
+ data.scepConfig.challengePassword.length > 0 &&
+ data.scepConfig.challengePassword.length < 8
+ ) {
+ return false;
+ }
+ return true;
+ },
+ {
+ message: "Challenge password must be at least 8 characters for static challenges",
+ path: ["scepConfig", "challengePassword"]
+ }
+ )
.refine(
(data) => {
if (data.enrollmentType === EnrollmentType.EST) {
@@ -732,9 +775,15 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
scepConfig:
profile.enrollmentType === EnrollmentType.SCEP
? {
+ challengeType:
+ (profile.scepConfig?.challengeType as ScepChallengeType) ??
+ ScepChallengeType.STATIC,
challengePassword: "",
includeCaCertInResponse: profile.scepConfig?.includeCaCertInResponse ?? true,
- allowCertBasedRenewal: profile.scepConfig?.allowCertBasedRenewal ?? true
+ allowCertBasedRenewal: profile.scepConfig?.allowCertBasedRenewal ?? true,
+ dynamicChallengeExpiryMinutes:
+ profile.scepConfig?.dynamicChallengeExpiryMinutes ?? 60,
+ dynamicChallengeMaxPending: profile.scepConfig?.dynamicChallengeMaxPending ?? 100
}
: undefined,
externalConfigs: profile.externalConfigs
@@ -777,6 +826,7 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
const watchedAutoRenew = watch("apiConfig.autoRenew");
const watchedSkipDnsOwnershipVerification = watch("acmeConfig.skipDnsOwnershipVerification");
const watchedSkipEabBinding = watch("acmeConfig.skipEabBinding");
+ const watchedChallengeType = watch("scepConfig.challengeType");
const watchedPolicyId = watch("certificatePolicyId");
const watchedDefaultsIsCA = watch("defaults.basicConstraints.isCA") || false;
@@ -925,9 +975,15 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
scepConfig:
profile.enrollmentType === EnrollmentType.SCEP
? {
+ challengeType:
+ (profile.scepConfig?.challengeType as ScepChallengeType) ??
+ ScepChallengeType.STATIC,
challengePassword: "",
includeCaCertInResponse: profile.scepConfig?.includeCaCertInResponse ?? true,
- allowCertBasedRenewal: profile.scepConfig?.allowCertBasedRenewal ?? true
+ allowCertBasedRenewal: profile.scepConfig?.allowCertBasedRenewal ?? true,
+ dynamicChallengeExpiryMinutes:
+ profile.scepConfig?.dynamicChallengeExpiryMinutes ?? 60,
+ dynamicChallengeMaxPending: profile.scepConfig?.dynamicChallengeMaxPending ?? 100
}
: undefined,
externalConfigs: profile.externalConfigs
@@ -1340,9 +1396,12 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
setValue("apiConfig", undefined);
setValue("acmeConfig", undefined);
setValue("scepConfig", {
+ challengeType: ScepChallengeType.STATIC,
challengePassword: "",
includeCaCertInResponse: true,
- allowCertBasedRenewal: true
+ allowCertBasedRenewal: true,
+ dynamicChallengeExpiryMinutes: 60,
+ dynamicChallengeMaxPending: 100
});
}
}}
@@ -1403,9 +1462,12 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
setValue("estConfig", undefined);
setValue("acmeConfig", undefined);
setValue("scepConfig", {
+ challengeType: ScepChallengeType.STATIC,
challengePassword: "",
includeCaCertInResponse: true,
- allowCertBasedRenewal: true
+ allowCertBasedRenewal: true,
+ dynamicChallengeExpiryMinutes: 60,
+ dynamicChallengeMaxPending: 100
});
}
onChange(value);
@@ -1614,25 +1676,129 @@ export const CreateProfileModal = ({ isOpen, onClose, profile, mode = "create" }
<div className="mb-4 space-y-4">
<Controller
control={control}
- name="scepConfig.challengePassword"
- render={({ field, fieldState: { error } }) => (
+ name="scepConfig.challengeType"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
- label="Challenge Password"
- isRequired
+ label="Challenge Type"
isError={Boolean(error)}
errorText={error?.message}
- helperText="The challenge password cannot be viewed after creation. Make sure to save it somewhere safe."
+ helperText={
+ value === ScepChallengeType.DYNAMIC
+ ? "Challenges are generated on-demand via an authenticated API endpoint. Ideal for MDM tools like JAMF."
+ : "A single shared challenge password is used for all enrollment requests."
+ }
>
- <Input
- {...field}
- type="password"
- placeholder="Enter SCEP challenge password"
+ <Select
+ value={value ?? ScepChallengeType.STATIC}
+ onValueChange={(val) => {
+ onChange(val);
+ if (val === ScepChallengeType.DYNAMIC) {
+ setValue("scepConfig.challengePassword", "");
+ }
+ }}
className="w-full"
- />
+ >
+ <SelectItem
+ value={ScepChallengeType.STATIC}
+ key={ScepChallengeType.STATIC}
+ >
+ Static Challenge
+ </SelectItem>
+ <SelectItem
+ value={ScepChallengeType.DYNAMIC}
+ key={ScepChallengeType.DYNAMIC}
+ >
+ Dynamic Challenge
+ </SelectItem>
+ </Select>
</FormControl>
)}
/>
+ {watchedChallengeType !== ScepChallengeType.DYNAMIC && (
+ <Controller
+ control={control}
+ name="scepConfig.challengePassword"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Challenge Password"
+ isRequired={!isEdit}
+ isError={Boolean(error)}
+ errorText={error?.message}
+ helperText="The challenge password cannot be viewed after creation. Make sure to save it somewhere safe."
+ >
+ <Input
+ {...field}
+ type="password"
+ placeholder={
+ isEdit
+ ? "Leave empty to keep current password"
+ : "Enter SCEP challenge password"
+ }
+ className="w-full"
+ />
+ </FormControl>
+ )}
+ />
+ )}
+
+ {watchedChallengeType === ScepChallengeType.DYNAMIC && (
+ <>
+ <Controller
+ control={control}
+ name="scepConfig.dynamicChallengeExpiryMinutes"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Challenge Expiry (minutes)"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ helperText="How long each generated challenge remains valid before expiring."
+ >
+ <Input
+ {...field}
+ type="number"
+ placeholder="60"
+ min="1"
+ max="1440"
+ className="w-full"
+ onChange={(e) => {
+ const val = e.target.value;
+ field.onChange(val === "" ? undefined : Number(val));
+ }}
+ value={field.value ?? ""}
+ />
+ </FormControl>
+ )}
+ />
+ <Controller
+ control={control}
+ name="scepConfig.dynamicChallengeMaxPending"
+ render={({ field, fieldState: { error } }) => (
+ <FormControl
+ label="Max Pending Challenges"
+ isError={Boolean(error)}
+ errorText={error?.message}
+ helperText="Maximum number of unused challenges that can exist at once."
+ >
+ <Input
+ {...field}
+ type="number"
+ placeholder="100"
+ min="1"
+ max="1000"
+ className="w-full"
+ onChange={(e) => {
+ const val = e.target.value;
+ field.onChange(val === "" ? undefined : Number(val));
+ }}
+ value={field.value ?? ""}
+ />
+ </FormControl>
+ )}
+ />
+ </>
+ )}
+
<Controller
control={control}
name="scepConfig.includeCaCertInResponse"
diff --git a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsx b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsx
index fc7950ca42..a194f75174 100644
--- a/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsx
+++ b/frontend/src/pages/cert-manager/PoliciesPage/components/CertificateProfilesTab/ScepDetailsModal.tsx
@@ -4,7 +4,10 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { FormLabel, IconButton, Input, Modal, ModalContent } from "@app/components/v2";
import { downloadFile } from "@app/helpers/download";
import { useToggle } from "@app/hooks";
-import { TCertificateProfileWithDetails } from "@app/hooks/api/certificateProfiles";
+import {
+ ScepChallengeType,
+ TCertificateProfileWithDetails
+} from "@app/hooks/api/certificateProfiles";
const RESET_COPIED_DELAY = 1 * 1000;
@@ -16,6 +19,7 @@ type Props = {
export const ScepDetailsModal = ({ isOpen, onClose, profile }: Props) => {
const [isUrlCopied, setIsUrlCopied] = useToggle(false);
+ const [isChallengeUrlCopied, setIsChallengeUrlCopied] = useToggle(false);
const { scepConfig } = profile;
const scepEndpointUrl = scepConfig?.scepEndpointUrl ?? "";
@@ -77,6 +81,35 @@ export const ScepDetailsModal = ({ isOpen, onClose, profile }: Props) => {
</IconButton>
</div>
+ {scepConfig.challengeType === ScepChallengeType.DYNAMIC &&
+ scepConfig.challengeEndpointUrl && (
+ <>
+ <FormLabel
+ label="Challenge Endpoint URL"
+ className="mt-4"
+ tooltipText="The authenticated API endpoint to generate dynamic SCEP challenges. Use this URL in your MDM webhook configuration (e.g., JAMF SCEPChallenge)."
+ />
+ <div className="flex gap-2">
+ <Input value={scepConfig.challengeEndpointUrl} isDisabled />
+ <IconButton
+ ariaLabel="copy"
+ variant="outline_bg"
+ colorSchema="secondary"
+ onClick={() => {
+ navigator.clipboard.writeText(scepConfig.challengeEndpointUrl!);
+ setIsChallengeUrlCopied.on();
+ setTimeout(() => {
+ setIsChallengeUrlCopied.off();
+ }, RESET_COPIED_DELAY);
+ }}
+ className="w-10"
+ >
+ <FontAwesomeIcon icon={isChallengeUrlCopied ? faCheck : faCopy} />
+ </IconButton>
+ </div>
+ </>
+ )}
+
<FormLabel
label="RA Certificate"
className="mt-4"