Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(pki): add IP address SAN support to ACME certificate issuance (#5771)
Saif Ur Rahman5d5fcbb295ec
diff --git a/backend/bdd/features/pki/acme/order.feature b/backend/bdd/features/pki/acme/order.featureindex 199cd4aa6e..4665bac584 100644--- a/backend/bdd/features/pki/acme/order.feature+++ b/backend/bdd/features/pki/acme/order.feature@@ -95,12 +95,11 @@ Feature: OrderThen the value response.status_code should be equal to 400And the value response with jq ".status" should be equal to 400And the value response with jq ".type" should be equal to "urn:ietf:params:acme:error:unsupportedIdentifier"- And the value response with jq ".detail" should be equal to "Only DNS identifiers are supported"+ And the value response with jq ".detail" should be equal to "Only DNS and IP identifiers are supported"Examples: Bad Identifier Types| identifier_type || bad |- | ip || email |Scenario Outline: Create an order with invalid identifier valuesdiff --git a/backend/src/ee/services/pki-acme/pki-acme-challenge-service.ts b/backend/src/ee/services/pki-acme/pki-acme-challenge-service.tsindex 52fd0efb56..2649e0a110 100644--- a/backend/src/ee/services/pki-acme/pki-acme-challenge-service.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-challenge-service.ts@@ -19,7 +19,7 @@ import {AcmeIncorrectResponseError,AcmeServerInternalError} from "./pki-acme-errors";-import { AcmeAuthStatus, AcmeChallengeStatus, AcmeChallengeType } from "./pki-acme-schemas";+import { AcmeAuthStatus, AcmeChallengeStatus, AcmeChallengeType, AcmeIdentifierType } from "./pki-acme-schemas";import { TPkiAcmeChallengeServiceFactory } from "./pki-acme-types";type TPkiAcmeChallengeServiceFactoryDep = {@@ -64,7 +64,7 @@ export const pkiAcmeChallengeServiceFactory = ({}const host = challenge.auth.identifierValue;// check if host is a private ip address- if (isPrivateIp(host)) {+ if (challenge.auth.identifierType === AcmeIdentifierType.IP && isPrivateIp(host)) {throw new BadRequestError({ message: "Private IP addresses are not allowed" });}if (challenge.type !== AcmeChallengeType.HTTP_01 && challenge.type !== AcmeChallengeType.DNS_01) {@@ -83,7 +83,12 @@ export const pkiAcmeChallengeServiceFactory = ({"Using ACME development HTTP-01 challenge host override");}- const challengeUrl = new URL(`/.well-known/acme-challenge/${challenge.auth.token}`, `http://${host}`);+ // IPv6 addresses need brackets in URLs (e.g., http://[::1]/)+ // Only bracket if the host is a raw IPv6 address (contains ":" but is a valid IP),+ // not if it's a hostname:port like "host.docker.internal:8087"+ const isIPv6 = host.includes(":") && isValidIp(host);+ const urlHost = isIPv6 ? `[${host}]` : host;+ const challengeUrl = new URL(`/.well-known/acme-challenge/${challenge.auth.token}`, `http://${urlHost}`);logger.info({ challengeUrl }, "Performing ACME HTTP-01 challenge validation");// TODO: read config from the profile to get the timeout instead@@ -94,7 +99,12 @@ export const pkiAcmeChallengeServiceFactory = ({const challengeResponse = await axios.get<string>(challengeUrl.toString(), {// In case if we override the host in the development mode, still provide the original host in the header// to help the upstream server to validate the request- headers: { Host: challenge.auth.identifierValue },+ headers: {+ Host:+ challenge.auth.identifierValue.includes(":") && isValidIp(challenge.auth.identifierValue)+ ? `[${challenge.auth.identifierValue}]`+ : challenge.auth.identifierValue+ },timeout: timeoutMs,responseType: "text",validateStatus: () => truediff --git a/backend/src/ee/services/pki-acme/pki-acme-fns.ts b/backend/src/ee/services/pki-acme/pki-acme-fns.tsindex 759e3cdf97..3780c18af7 100644--- a/backend/src/ee/services/pki-acme/pki-acme-fns.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-fns.ts@@ -2,6 +2,7 @@ import RE2 from "re2";import { z } from "zod";import { getConfig } from "@app/lib/config/env";+import { isValidIp } from "@app/lib/ip";import { AcmeAccountDoesNotExistError } from "./pki-acme-errors";@@ -19,6 +20,10 @@ export const extractAccountIdFromKid = (kid: string, profileId: string): stringreturn z.string().uuid().parse(kid.slice(kidPrefix.length));};+export const validateIpIdentifier = (identifier: string): boolean => {+ return isValidIp(identifier);+};+export const validateDnsIdentifier = (identifier: string): boolean => {// DNS label pattern: 1-63 chars, alphanumeric or hyphen, but not starting or ending with hyphenconst labelPattern = new RE2(/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/);diff --git a/backend/src/ee/services/pki-acme/pki-acme-schemas.ts b/backend/src/ee/services/pki-acme/pki-acme-schemas.tsindex ebd17c26a8..f2c7760d15 100644--- a/backend/src/ee/services/pki-acme/pki-acme-schemas.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-schemas.ts@@ -1,7 +1,8 @@import { z } from "zod";export enum AcmeIdentifierType {- DNS = "dns"+ DNS = "dns",+ IP = "ip"}export enum AcmeOrderStatus {diff --git a/backend/src/ee/services/pki-acme/pki-acme-service.ts b/backend/src/ee/services/pki-acme/pki-acme-service.tsindex 6cbcd0ca09..60d57fed97 100644--- a/backend/src/ee/services/pki-acme/pki-acme-service.ts+++ b/backend/src/ee/services/pki-acme/pki-acme-service.ts@@ -73,7 +73,7 @@ import {AcmeServerInternalError,AcmeUnsupportedIdentifierError} from "./pki-acme-errors";-import { buildUrl, extractAccountIdFromKid, validateDnsIdentifier } from "./pki-acme-fns";+import { buildUrl, extractAccountIdFromKid, validateDnsIdentifier, validateIpIdentifier } from "./pki-acme-fns";import { TPkiAcmeOrderAuthDALFactory } from "./pki-acme-order-auth-dal";import { TPkiAcmeOrderDALFactory } from "./pki-acme-order-dal";import { TPkiAcmeQueueServiceFactory } from "./pki-acme-queue";@@ -676,18 +676,29 @@ export const pkiAcmeServiceFactory = ({// if not, we may be able to reject it early with an unsupportedIdentifier error.// TODO: ideally, we should return an error with subproblems if we have multiple unsupported identifiers- if (payload.identifiers.some((identifier) => identifier.type !== AcmeIdentifierType.DNS)) {- throw new AcmeUnsupportedIdentifierError({ message: "Only DNS identifiers are supported" });- }- if (- payload.identifiers.some(- (identifier) =>+ for (const identifier of payload.identifiers) {+ if (identifier.type === AcmeIdentifierType.DNS) {+ if (!validateDnsIdentifier(identifier.value) ||isPrivateIp(identifier.value) ||(!getConfig().isDevelopmentMode && identifier.value.toLowerCase() === "localhost")- )- ) {- throw new AcmeUnsupportedIdentifierError({ message: "Invalid DNS identifier" });+ ) {+ throw new AcmeUnsupportedIdentifierError({ message: "Invalid DNS identifier" });+ }+ } else if (identifier.type === AcmeIdentifierType.IP) {+ if (!validateIpIdentifier(identifier.value)) {+ throw new AcmeUnsupportedIdentifierError({ message: "Invalid IP identifier" });+ }+ // Private IPs are allowed for IP identifiers only when ownership verification is skipped,+ // since HTTP-01 challenges can't reach private addresses. This is the common internal PKI use case.+ if (!skipDnsOwnershipVerification && isPrivateIp(identifier.value)) {+ throw new AcmeUnsupportedIdentifierError({+ message: "Private IP addresses are not allowed when ownership verification is enabled"+ });+ }+ } else {+ throw new AcmeUnsupportedIdentifierError({ message: "Only DNS and IP identifiers are supported" });+ }}const order = await acmeOrderDAL.transaction(async (tx) => {@@ -705,11 +716,18 @@ export const pkiAcmeServiceFactory = ({);const authorizations: TPkiAcmeAuths[] = await Promise.all(payload.identifiers.map(async (identifier) => {- if (identifier.type !== AcmeIdentifierType.DNS) {- throw new AcmeUnsupportedIdentifierError({ message: "Only DNS identifiers are supported" });- }- if (isPrivateIp(identifier.value)) {- throw new AcmeUnsupportedIdentifierError({ message: "Private IP addresses are not allowed" });+ if (identifier.type === AcmeIdentifierType.IP) {+ if (!skipDnsOwnershipVerification && isPrivateIp(identifier.value)) {+ throw new AcmeUnsupportedIdentifierError({+ message: "Private IP addresses are not allowed when ownership verification is enabled"+ });+ }+ } else if (identifier.type === AcmeIdentifierType.DNS) {+ if (isPrivateIp(identifier.value)) {+ throw new AcmeUnsupportedIdentifierError({ message: "Private IP addresses are not allowed" });+ }+ } else {+ throw new AcmeUnsupportedIdentifierError({ message: "Only DNS and IP identifiers are supported" });}const auth = await acmeAuthDAL.create({@@ -727,7 +745,12 @@ export const pkiAcmeServiceFactory = ({tx);if (!skipDnsOwnershipVerification) {- for (const challengeType of [AcmeChallengeType.HTTP_01, AcmeChallengeType.DNS_01]) {+ // IP identifiers only support HTTP-01 challenges (DNS-01 doesn't apply per RFC 8738)+ const challengeTypes =+ identifier.type === AcmeIdentifierType.IP+ ? [AcmeChallengeType.HTTP_01]+ : [AcmeChallengeType.HTTP_01, AcmeChallengeType.DNS_01];+ for (const challengeType of challengeTypes) {// eslint-disable-next-line no-await-in-loopawait acmeChallengeDAL.create({@@ -1000,27 +1023,47 @@ export const pkiAcmeServiceFactory = ({// Check and validate the CSRconst certificateRequest = extractCertificateRequestFromCSR(csr);- if (- certificateRequest.subjectAlternativeNames?.some(- (san) => san.type !== CertSubjectAlternativeNameType.DNS_NAME- )- ) {- throw new AcmeBadCSRError({ message: "Invalid CSR: Only DNS subject alternative names are supported" });+ const allowedSanTypes = new Set([+ CertSubjectAlternativeNameType.DNS_NAME,+ CertSubjectAlternativeNameType.IP_ADDRESS+ ]);+ if (certificateRequest.subjectAlternativeNames?.some((san) => !allowedSanTypes.has(san.type))) {+ throw new AcmeBadCSRError({+ message: "Invalid CSR: Only DNS and IP subject alternative names are supported"+ });}const orderWithAuthorizations = (await acmeOrderDAL.findByAccountAndOrderIdWithAuthorizations(accountId,orderId,tx))!;- const csrIdentifierValues = new Set(++ // Build a set of "type:value" pairs from CSR SANs to match against authorized identifiers+ const sanTypeToIdentifierType: Partial<Record<CertSubjectAlternativeNameType, AcmeIdentifierType>> = {+ [CertSubjectAlternativeNameType.DNS_NAME]: AcmeIdentifierType.DNS,+ [CertSubjectAlternativeNameType.IP_ADDRESS]: AcmeIdentifierType.IP+ };+ const csrIdentifierPairs = new Set((certificateRequest.subjectAlternativeNames ?? [])- .map((san) => san.value.toLowerCase())- .concat(certificateRequest.commonName ? [certificateRequest.commonName.toLowerCase()] : [])+ .map((san) => {+ const identifierType = sanTypeToIdentifierType[san.type];+ return identifierType ? `${identifierType}:${san.value.toLowerCase()}` : null;+ })+ .filter(Boolean));+ // ACME clients (e.g., lego) set the CN to the IP address for IP certificate requests.+ // We need to detect whether the CN is an IP to match it against the correct identifier type,+ // otherwise "ip:127.0.0.1" in the authorization won't match "dns:127.0.0.1" from the CN.+ if (certificateRequest.commonName) {+ const cnType = validateIpIdentifier(certificateRequest.commonName)+ ? AcmeIdentifierType.IP+ : AcmeIdentifierType.DNS;+ csrIdentifierPairs.add(`${cnType}:${certificateRequest.commonName.toLowerCase()}`);+ }if (- csrIdentifierValues.size !== orderWithAuthorizations.authorizations.length ||+ csrIdentifierPairs.size !== orderWithAuthorizations.authorizations.length ||!orderWithAuthorizations.authorizations.every((auth) =>- csrIdentifierValues.has(auth.identifierValue.toLowerCase())+ csrIdentifierPairs.has(`${auth.identifierType}:${auth.identifierValue.toLowerCase()}`))) {throw new AcmeBadCSRError({ message: "Invalid CSR: Common name + SANs mismatch with order identifiers" });