Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): name SSRF_ALLOWED_HOSTS entries that cannot match
Yudhi Armyndharisb1a35f7df360
diff --git a/src/common/security/ssrf-allowed-hosts.spec.ts b/src/common/security/ssrf-allowed-hosts.spec.tsnew file mode 100644index 000000000..3f31896b7--- /dev/null+++ b/src/common/security/ssrf-allowed-hosts.spec.ts@@ -0,0 +1,50 @@+import * as dnsPromises from 'dns/promises';+import { assertSafeFetchUrl, SsrfBlockedError } from './ssrf-guard';++jest.mock('dns/promises', () => {+ const actual = jest.requireActual<typeof import('dns/promises')>('dns/promises');+ return { __esModule: true, ...actual, lookup: jest.fn(actual.lookup) };+});++describe('SSRF_ALLOWED_HOSTS entries the guard can never match', () => {+ const original = process.env.SSRF_ALLOWED_HOSTS;+ let warn: jest.SpiedFunction<typeof console.warn>;++ beforeEach(() => {+ warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined);+ });++ afterEach(() => {+ warn.mockRestore();+ jest.mocked(dnsPromises.lookup).mockReset();+ if (original === undefined) delete process.env.SSRF_ALLOWED_HOSTS;+ else process.env.SSRF_ALLOWED_HOSTS = original;+ });++ const warnings = (): string[] => warn.mock.calls.map(([line]) => String(line));++ it('names an entry with a scheme, port, path or wildcard, once, and still refuses the destination', async () => {+ process.env.SSRF_ALLOWED_HOSTS = 'http://n8n-a:5678, n8n-b:5678, n8n-c.local/hooks, *.corp-a, minio';+ jest.mocked(dnsPromises.lookup).mockResolvedValue([{ address: '10.0.0.5', family: 4 }] as never);++ await expect(assertSafeFetchUrl('http://n8n-b:5678/hook')).rejects.toBeInstanceOf(SsrfBlockedError);+ await expect(assertSafeFetchUrl('http://n8n-b:5678/hook')).rejects.toBeInstanceOf(SsrfBlockedError);++ const lines = warnings().filter(line => line.includes('SSRF_ALLOWED_HOSTS'));+ expect(lines).toHaveLength(1);+ for (const entry of ['http://n8n-a:5678', 'n8n-b:5678', 'n8n-c.local/hooks', '*.corp-a']) {+ expect(lines[0]).toContain(entry);+ }+ expect(lines[0]).not.toContain('minio');+ });++ it('says nothing for host names and IP literals, whatever their case, brackets or underscores', async () => {+ process.env.SSRF_ALLOWED_HOSTS =+ 'Localhost, minio, my_service.internal, host.docker.internal, 10.0.0.9, [::1], ::2';+ jest.mocked(dnsPromises.lookup).mockResolvedValue([{ address: '127.0.0.1', family: 4 }] as never);++ await expect(assertSafeFetchUrl('http://localhost/')).resolves.toBeUndefined();++ expect(warnings().filter(line => line.includes('SSRF_ALLOWED_HOSTS'))).toEqual([]);+ });+});diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex cfb4612eb..e37efd085 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -3,6 +3,9 @@ import { lookup } from 'dns/promises';import { type LookupAddress, type LookupOptions } from 'dns';import { Agent, fetch as undiciFetch, Headers, type Dispatcher, type RequestInit, type Response } from 'undici';import { createProxyDispatcher } from './proxy-dispatcher';+import { createLogger } from '../services/logger.service';++const logger = createLogger('SsrfGuard');/** Thrown when an outbound URL is blocked by the SSRF guard. */export class SsrfBlockedError extends Error {@@ -58,7 +61,7 @@ export function isSsrfProtectionEnabled(): boolean {* bypass the block. Matched case-insensitively against the URL hostname.*/function getAllowedHosts(): Set<string> {- return new Set(+ const hosts = new Set((process.env.SSRF_ALLOWED_HOSTS ?? '').split(',')// Strip IPv6 brackets so an entry copied from a URL (e.g. "[::1]") matches the@@ -71,6 +74,30 @@ function getAllowedHosts(): Set<string> {).filter(Boolean),);+ warnUnusableAllowedHosts(hosts);+ return hosts;+}++/** What `url.hostname` can equal: a host name, with underscores for a container name, or an IP literal. */+const ALLOWED_HOST_PATTERN = /^[a-z0-9_]([a-z0-9_.-]*[a-z0-9_])?\.?$/;++let warnedUnusableHosts = '';++/**+ * An entry is compared with the hostname of the URL, so one with a scheme, port, path or wildcard never+ * matches, and the refusal it was meant to lift only says the destination is not allowed. Name such entries once.+ */+function warnUnusableAllowedHosts(hosts: ReadonlySet<string>): void {+ const unusable = [...hosts].filter(host => !isIPv4(host) && !isIPv6(host) && !ALLOWED_HOST_PATTERN.test(host));+ const key = unusable.join(',');+ if (key === warnedUnusableHosts) return;+ warnedUnusableHosts = key;+ if (unusable.length > 0) {+ logger.warn(+ 'SSRF_ALLOWED_HOSTS entries must be a bare host name or IP address, without a scheme, port, path or ' ++ `wildcard; these never match and are ignored: ${unusable.join(', ')}`,+ );+ }}// IPv4 ranges that must never be reachable by an outbound webhook (SSRF targets). Membership is