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(security): implement outbound HTTP & SSRF protection using safeRequest helper
Victor Hugo dos Santos4e50b14f535c
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.mdindex e525ad3114..d3a1d8901e 100644--- a/backend/CLAUDE.md+++ b/backend/CLAUDE.md@@ -209,6 +209,38 @@ logger.info(`getPlan: Process done for [orgId=${orgId}] [projectId=${projectId}]logger.error({ sessionId, err }, "Failed to get connection details");```+### Outbound HTTP & SSRF Protection++Anywhere the backend issues an HTTP request to a URL derived from user input (webhooks, integrations, app connections, OIDC/JWKS, audit log streams, ACME, etc.), use the `safeRequest` helper from `@app/lib/validator` instead of the raw `request` (Axios) client.++```ts+import { safeRequest } from "@app/lib/validator";++// Replace:+// await blockLocalAndPrivateIpAddresses(url);+// await request.post(url, body, { headers, timeout });+// With:+const res = await safeRequest.post<TResponse>(url, body, { headers, timeout });+```++`safeRequest.{get,post}` (in `src/lib/validator/validate-url.ts`) does three things in one call:+1. **Validates** the URL — rejects local/private IPs, Infisical's own DB/Redis hosts, URLs with embedded credentials.+2. **Pins** the connection — resolves the hostname once, then installs a custom `lookup` on a per-request `http(s).Agent` so the connect-time DNS call returns the validated IP. This closes the DNS-rebinding TOCTOU between the validation lookup and Axios's connect lookup.+3. **Disables redirects** (`maxRedirects: 0`). For redirect-following GETs that need to validate each hop, use `ssrfSafeGet` instead — it loops on top of the same pinned-agent dispatcher.++**When to use what:**+- `safeRequest.post` / `safeRequest.get` — most outbound HTTP. URL comes from user/admin config or stored data.+- `ssrfSafeGet` — when redirects must be followed (e.g. fetching JWKS or OIDC discovery docs that may 302).+- `ssrfSafePost` — POSTs that need to opt into `allowPrivateIps` (rare, used by AI MCP server).+- `blockLocalAndPrivateIpAddresses` directly — only for non-Axios clients (LDAP, SSH, SMB, ssh2, ldapjs, kubernetes client, etc.) where you can't install a `lookup` on the agent. The TOCTOU still exists in those paths; they're each a per-library follow-up.++**Opt-outs that skip pinning:**+- `NODE_ENV=development` — validation is bypassed entirely (returns `undefined`).+- `isGateway = true` argument — gateway-routed traffic doesn't go through Axios DNS, so pinning would do nothing.+- `allowPrivateIps: true` option — caller explicitly opts into private-IP destinations.++In all three opt-out cases, `safeRequest` falls back to Axios's default agent behavior. **Don't add `allowPrivateIps: true` without thinking** — it disables both the IP check and the rebinding pin.+### Enterprise (EE) FeaturesEnterprise code lives in `src/ee/`:diff --git a/backend/src/lib/validator/index.ts b/backend/src/lib/validator/index.tsindex 7ac495d51b..7f75f843f5 100644--- a/backend/src/lib/validator/index.ts+++ b/backend/src/lib/validator/index.ts@@ -10,5 +10,11 @@ export {validateSmbPassword,validateWindowsUsername} from "./validate-smb";-export { blockLocalAndPrivateIpAddresses, ssrfSafeGet, ssrfSafePost, validateSsrfUrl } from "./validate-url";+export {+ blockLocalAndPrivateIpAddresses,+ safeRequest,+ ssrfSafeGet,+ ssrfSafePost,+ validateSsrfUrl+} from "./validate-url";export { isUuidV4 } from "./validate-uuid";diff --git a/backend/src/lib/validator/validate-url.ts b/backend/src/lib/validator/validate-url.tsindex d7127de1d7..e889d78139 100644--- a/backend/src/lib/validator/validate-url.ts+++ b/backend/src/lib/validator/validate-url.ts@@ -1,5 +1,10 @@+import { LookupAddress } from "node:dns";import dns from "node:dns/promises";+import http from "node:http";+import https from "node:https";+import { LookupFunction } from "node:net";+import { AxiosRequestConfig } from "axios";import { isIP } from "net";import RE2 from "re2";@@ -10,10 +15,18 @@ import { request } from "@app/lib/config/request";import { BadRequestError } from "../errors";import { isPrivateIp } from "../ip/ipRange";-export const blockLocalAndPrivateIpAddresses = async (url: string, isGateway = false) => {+export type TValidatedHost = {+ hostname: string;+ entries: LookupAddress[];+};++export const blockLocalAndPrivateIpAddresses = async (+ url: string,+ isGateway = false+): Promise<TValidatedHost | undefined> => {const appCfg = getConfig();- if (appCfg.isDevelopmentMode || isGateway) return;+ if (appCfg.isDevelopmentMode || isGateway) return undefined;const validUrl = new URL(url);@@ -21,24 +34,25 @@ export const blockLocalAndPrivateIpAddresses = async (url: string, isGateway = fthrow new BadRequestError({ message: "URLs with user credentials (e.g., user:pass@) are not allowed" });}- const inputHostIps: string[] = [];+ let entries: LookupAddress[];if (isIP(validUrl.hostname)) {- inputHostIps.push(validUrl.hostname);+ entries = [{ address: validUrl.hostname, family: isIP(validUrl.hostname) }];} else {if (validUrl.hostname === "localhost" || validUrl.hostname === "host.docker.internal") {throw new BadRequestError({ message: "Local IPs not allowed as URL" });}- const entries = await dns.lookup(validUrl.hostname, { all: true });+ const lookups = await dns.lookup(validUrl.hostname, { all: true });- if (!entries || entries.length === 0) {+ if (!lookups || lookups.length === 0) {throw new BadRequestError({ message: "Could not resolve hostname to any IP address" });}-- inputHostIps.push(...entries.map(({ address }) => address));+ entries = lookups;}- const isInternalIp = inputHostIps.some((el) => isPrivateIp(el));+ const isInternalIp = entries.some((e) => isPrivateIp(e.address));if (isInternalIp && !appCfg.ALLOW_INTERNAL_IP_CONNECTIONS)throw new BadRequestError({ message: "Local IPs not allowed as URL" });++ return { hostname: validUrl.hostname, entries };};type FQDNOptions = {@@ -151,34 +165,100 @@ type SsrfSafeRequestOptions = {validateStatus?: (status: number) => boolean;};+/**+ * Builds a `dns.lookup`-shaped function that always returns the pre-validated+ * IPs from `entries`. Installed onto an http(s).Agent so the connect-time DNS+ * call cannot re-resolve and land on a different IP than the one validation+ * approved (DNS rebinding TOCTOU defense).+ */+type TLookupOneCallback = (err: NodeJS.ErrnoException | null, address: string, family: number) => void;+type TLookupAllCallback = (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void;++const makePinnedLookup = (entries: LookupAddress[]): LookupFunction =>+ ((_hostname: string, optionsOrCb: unknown, maybeCb?: unknown) => {+ // Node may invoke `lookup(hostname, callback)` (2-arg) or `lookup(hostname, options, callback)` (3-arg).+ const first: LookupAddress = entries[0];+ if (typeof optionsOrCb === "function") {+ (optionsOrCb as TLookupOneCallback)(null, first.address, first.family);+ return;+ }+ const opts = (optionsOrCb ?? {}) as { all?: boolean };+ if (opts.all) {+ (maybeCb as TLookupAllCallback)(null, entries);+ } else {+ (maybeCb as TLookupOneCallback)(null, first.address, first.family);+ }+ }) as LookupFunction;++const buildPinnedAgent = (+ validated: TValidatedHost | undefined,+ protocol: string+): http.Agent | https.Agent | undefined => {+ if (!validated) return undefined;+ const lookup = makePinnedLookup(validated.entries);+ return protocol === "https:"+ ? new https.Agent({ lookup, keepAlive: false })+ : new http.Agent({ lookup, keepAlive: false });+};+/*** Validates a URL for SSRF protection.* Blocks:* - Local/private IPs (loopback, link-local, RFC 1918 addresses)* - Infisical's own infrastructure (DB, Redis, etc.)+ *+ * Returns the resolved IPs so the caller can pin the subsequent connection+ * to those IPs, preventing DNS rebinding between validation and connect.*/export const validateSsrfUrl = async (url: string,options?: Pick<SsrfSafeRequestOptions, "allowPrivateIps">-): Promise<void> => {+): Promise<TValidatedHost | undefined> => {if (options?.allowPrivateIps) {- return;+ return undefined;}const parsedUrl = new URL(url);- // Block local/private IPs- await blockLocalAndPrivateIpAddresses(url, false);+ // Block local/private IPs and capture the resolved IPs for pinning+ const validated = await blockLocalAndPrivateIpAddresses(url, false);// Also block Infisical's own infrastructure (DB, Redis, etc.)await verifyHostInputValidity({ host: parsedUrl.hostname, isGateway: false, isDynamicSecret: false });++ return validated;+};++type TSafeRequestConfig = Omit<AxiosRequestConfig, "httpAgent" | "httpsAgent" | "maxRedirects" | "url" | "method">;++const dispatch = async <T>(+ method: "GET" | "POST",+ url: string,+ data: unknown,+ options: TSafeRequestConfig & Pick<SsrfSafeRequestOptions, "allowPrivateIps"> = {}+) => {+ const { allowPrivateIps, ...axiosOpts } = options;+ const validated = await validateSsrfUrl(url, { allowPrivateIps });+ const { protocol } = new URL(url);+ const agent = buildPinnedAgent(validated, protocol);++ return request.request<T>({+ ...axiosOpts,+ method,+ url,+ data,+ maxRedirects: 0,+ httpAgent: protocol === "http:" ? (agent as http.Agent | undefined) : undefined,+ httpsAgent: protocol === "https:" ? (agent as https.Agent | undefined) : undefined+ });};/*** Makes an HTTP GET request with SSRF-safe redirect handling.* Disables automatic redirects and manually follows them while validating each hop.* This prevents redirect-based SSRF bypasses where the initial URL is valid but- * redirects to an internal/private IP address.+ * redirects to an internal/private IP address. Each hop also pins its connection+ * to the validated IP, blocking DNS rebinding between validation and connect.*/export const ssrfSafeGet = async <T>(url: string,@@ -188,13 +268,9 @@ export const ssrfSafeGet = async <T>(let redirectCount = 0;while (redirectCount <= MAX_SAFE_REDIRECTS) {- // Validate URL before each request (including redirects)// eslint-disable-next-line no-await-in-loop- await validateSsrfUrl(currentUrl, options);-- // eslint-disable-next-line no-await-in-loop- const response = await request.get<T>(currentUrl, {- maxRedirects: 0,+ const response = await dispatch<T>("GET", currentUrl, undefined, {+ allowPrivateIps: options?.allowPrivateIps,validateStatus: options?.validateStatus ?? ((status) => status >= 200 && status < 400)});@@ -229,17 +305,41 @@ export const ssrfSafeGet = async <T>(/*** Makes an HTTP POST request with SSRF protection.- * Validates the URL before making the request and disables redirects.+ * Validates the URL, pins the connection to the validated IP (DNS rebinding+ * defense), and disables redirects.*/export const ssrfSafePost = async <T>(url: string,data: unknown,options?: Pick<SsrfSafeRequestOptions, "allowPrivateIps"> & { headers?: Record<string, string> }): Promise<{ data: T }> => {- await validateSsrfUrl(url, options);-- return request.post<T>(url, data, {- headers: options?.headers,- maxRedirects: 0+ return dispatch<T>("POST", url, data, {+ allowPrivateIps: options?.allowPrivateIps,+ headers: options?.headers});};++/**+ * Drop-in replacement for `request.post` / `request.get` that validates the URL+ * and pins the connection to the validated IP. Use this anywhere the URL is+ * user-supplied and the caller currently does:+ *+ * await blockLocalAndPrivateIpAddresses(url);+ * await request.post(url, ...);+ *+ * Replace with:+ *+ * await safeRequest.post(url, ...);+ *+ * which collapses the two DNS resolutions into one, eliminating the rebinding+ * window.+ */+export const safeRequest = {+ get: <T>(url: string, options?: TSafeRequestConfig & Pick<SsrfSafeRequestOptions, "allowPrivateIps">) =>+ dispatch<T>("GET", url, undefined, options),+ post: <T>(+ url: string,+ data: unknown,+ options?: TSafeRequestConfig & Pick<SsrfSafeRequestOptions, "allowPrivateIps">+ ) => dispatch<T>("POST", url, data, options)+};diff --git a/backend/src/services/webhook/webhook-fns.ts b/backend/src/services/webhook/webhook-fns.tsindex 57fd7d464d..35a01bca3d 100644--- a/backend/src/services/webhook/webhook-fns.ts+++ b/backend/src/services/webhook/webhook-fns.ts@@ -3,13 +3,12 @@ import picomatch from "picomatch";import { TWebhooks } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory, WebhookTriggeredEvent } from "@app/ee/services/audit-log/audit-log-types";-import { request } from "@app/lib/config/request";import { crypto } from "@app/lib/crypto/cryptography";import { NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import { requestMemoKeys } from "@app/lib/request-context/memo-keys";import { requestMemoize } from "@app/lib/request-context/request-memoizer";-import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";+import { safeRequest } from "@app/lib/validator";import { ActorType } from "@app/services/auth/auth-type";import { TProjectDALFactory } from "../project/project-dal";@@ -43,7 +42,6 @@ export const triggerWebhookRequest = async (const headers: Record<string, string> = {};const payload = { ...data, timestamp: Date.now() };const { secretKey, url } = decryptWebhookDetails(webhook, decryptor);- await blockLocalAndPrivateIpAddresses(url);if (secretKey) {const webhookSign = crypto.nativeCrypto.createHmac("sha256", secretKey)@@ -52,11 +50,10 @@ export const triggerWebhookRequest = async (headers["x-infisical-signature"] = `t=${payload.timestamp};${webhookSign}`;}- const req = await request.post(url, payload, {+ const req = await safeRequest.post(url, payload, {headers,timeout: WEBHOOK_TRIGGER_TIMEOUT,- signal: AbortSignal.timeout(WEBHOOK_TRIGGER_TIMEOUT),- maxRedirects: 0+ signal: AbortSignal.timeout(WEBHOOK_TRIGGER_TIMEOUT)});return req;diff --git a/docs/self-hosting/guides/production-hardening.mdx b/docs/self-hosting/guides/production-hardening.mdxindex 750516d82e..c3016ce94c 100644--- a/docs/self-hosting/guides/production-hardening.mdx+++ b/docs/self-hosting/guides/production-hardening.mdx@@ -90,6 +90,24 @@ ALLOW_INTERNAL_IP_CONNECTIONS=false- **Principle**: Default deny incoming, allow only required traffic- **Implementation**: See your deployment-specific section below for exact configuration+#### Reverse Proxy Configuration++If Infisical is deployed behind a reverse proxy (Nginx, AWS ALB, Cloudflare, GCP Load Balancer, etc.), configure the trusted proxy CIDR list so that client IP detection cannot be spoofed by attackers forging `X-Forwarded-For` headers:++```bash+# Comma-separated list of reverse-proxy CIDR ranges whose forwarded-IP headers Infisical will trust.+# Accepts IPv4/IPv6 CIDR notation or the named aliases `loopback`, `linklocal`, `uniquelocal`.+TRUSTED_PROXY_CIDRS="10.0.0.0/8,172.16.0.0/12,192.168.0.0/16"+```++When set, only requests arriving from a socket address inside the listed CIDRs will have their forwarded-IP headers respected. Requests from any other source fall back to the raw socket IP.++When unset, Infisical trusts all forwarded-IP headers (legacy behavior, preserved for backwards compatibility). On a deployment reachable directly from the internet, this lets a client supply any value in `X-Forwarded-For` — bypassing per-IP rate limits (including login/MFA throttles) and any IP allowlists.++<Warning>+ Set `TRUSTED_PROXY_CIDRS` on any deployment that is reachable from the internet through a reverse proxy. Leaving it unset is only safe when Infisical is not directly internet-facing.+</Warning>+### Application Security#### Site Configuration