Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(security): name unusable SSRF_ALLOWED_HOSTS entries at boot

Yudhi Armyndharise1cfd1d0027f
diff --git a/src/common/security/ssrf-allowed-hosts.spec.ts b/src/common/security/ssrf-allowed-hosts.spec.ts
index 3f31896b7..2553b1871 100644
--- a/src/common/security/ssrf-allowed-hosts.spec.ts
+++ b/src/common/security/ssrf-allowed-hosts.spec.ts
@@ -1,5 +1,5 @@
import * as dnsPromises from 'dns/promises';
-import { assertSafeFetchUrl, SsrfBlockedError } from './ssrf-guard';
+import { assertSafeFetchUrl, SsrfBlockedError, warnUnusableAllowedHosts } from './ssrf-guard';
jest.mock('dns/promises', () => {
const actual = jest.requireActual<typeof import('dns/promises')>('dns/promises');
@@ -21,30 +21,60 @@ describe('SSRF_ALLOWED_HOSTS entries the guard can never match', () => {
else process.env.SSRF_ALLOWED_HOSTS = original;
});
- const warnings = (): string[] => warn.mock.calls.map(([line]) => String(line));
+ const warnings = (): string[] =>
+ warn.mock.calls.map(([line]) => String(line)).filter(line => line.includes('SSRF_ALLOWED_HOSTS'));
- 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';
+ it('names each entry by position and reason, once, without echoing it, and still refuses the destination', async () => {
+ process.env.SSRF_ALLOWED_HOSTS =
+ 'https://user:token@n8n-a:5678, n8n-b:5678, n8n-c.local/hooks, *.corp-a, minio, 127.1, 0:0:0:0:0:0:0:1, 2130706433';
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'));
+ const lines = warnings();
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);
+ for (const named of [
+ 'entry 1 (a scheme or credentials)',
+ 'entry 2 (a port)',
+ 'entry 3 (a path)',
+ 'entry 4 (a wildcard)',
+ 'entry 6 (a spelling the URL parser rewrites)',
+ 'entry 7 (a spelling the URL parser rewrites)',
+ 'entry 8 (a spelling the URL parser rewrites)',
+ ]) {
+ expect(lines[0]).toContain(named);
}
- expect(lines[0]).not.toContain('minio');
+ expect(lines[0]).not.toContain('entry 5');
+ expect(lines[0]).not.toMatch(/token|user|n8n|corp|hooks|minio/);
+ });
+
+ // The URL parser rewrites these hosts, and the guard compares the rewritten hostname, so the spelling written in
+ // the entry never equals it; the same address written as the parser prints it does.
+ it('is right that a non-canonical IP address entry never matches, and that the canonical one does', async () => {
+ process.env.SSRF_ALLOWED_HOSTS = '127.1';
+ await expect(assertSafeFetchUrl('http://127.1/')).rejects.toBeInstanceOf(SsrfBlockedError);
+
+ process.env.SSRF_ALLOWED_HOSTS = '0:0:0:0:0:0:0:1';
+ await expect(assertSafeFetchUrl('http://[::1]/')).rejects.toBeInstanceOf(SsrfBlockedError);
+
+ process.env.SSRF_ALLOWED_HOSTS = '127.0.0.1, ::1';
+ jest
+ .mocked(dnsPromises.lookup)
+ .mockImplementation(((host: string) =>
+ Promise.resolve([{ address: host, family: host.includes(':') ? 6 : 4 }])) as never);
+ await expect(assertSafeFetchUrl('http://127.1/')).resolves.toBeUndefined();
+ await expect(assertSafeFetchUrl('http://[0:0:0:0:0:0:0:1]/')).resolves.toBeUndefined();
});
- it('says nothing for host names and IP literals, whatever their case, brackets or underscores', async () => {
+ it('says nothing for host names and IP literals the parser keeps as written', async () => {
process.env.SSRF_ALLOWED_HOSTS =
- 'Localhost, minio, my_service.internal, host.docker.internal, 10.0.0.9, [::1], ::2';
+ 'Localhost, minio, my_service.internal, host.docker.internal, minio., 10.0.0.9, [::1], ::2, fe80::1, ,';
jest.mocked(dnsPromises.lookup).mockResolvedValue([{ address: '127.0.0.1', family: 4 }] as never);
await expect(assertSafeFetchUrl('http://localhost/')).resolves.toBeUndefined();
+ warnUnusableAllowedHosts();
- expect(warnings().filter(line => line.includes('SSRF_ALLOWED_HOSTS'))).toEqual([]);
+ expect(warnings()).toEqual([]);
});
});
diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.ts
index e37efd085..fd3bedf71 100644
--- a/src/common/security/ssrf-guard.ts
+++ b/src/common/security/ssrf-guard.ts
@@ -61,7 +61,14 @@ export function isSsrfProtectionEnabled(): boolean {
* bypass the block. Matched case-insensitively against the URL hostname.
*/
function getAllowedHosts(): Set<string> {
- const hosts = new Set(
+ const entries = allowedHostEntries();
+ warnUnusableAllowedHosts(entries);
+ return new Set(entries.filter(Boolean));
+}
+
+/** The SSRF_ALLOWED_HOSTS entries in written order, blanks kept so an entry's position is the one the operator sees. */
+function allowedHostEntries(): string[] {
+ return (
(process.env.SSRF_ALLOWED_HOSTS ?? '')
.split(',')
// Strip IPv6 brackets so an entry copied from a URL (e.g. "[::1]") matches the
@@ -72,30 +79,49 @@ function getAllowedHosts(): Set<string> {
.replace(/^\[|\]$/g, '')
.toLowerCase(),
)
- .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_])?\.?$/;
+/** What the URL parser makes of an entry used as a host, brackets stripped; undefined when it is no host at all. */
+function parsedHostname(entry: string): string | undefined {
+ try {
+ return new URL(`http://${entry.includes(':') ? `[${entry}]` : entry}/`).hostname.replace(/^\[|\]$/g, '');
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * Why an entry can never equal the hostname of a URL, or undefined when it can. The reason is a shape and never the
+ * value, which may carry credentials. An IP address has to be written the way the URL parser prints it: `http://127.1/`
+ * is compared as `127.0.0.1`, so the entry `127.1` (or `0:0:0:0:0:0:0:1` for `::1`) is never equal.
+ */
+function unusableAllowedHostReason(entry: string): string | undefined {
+ if (entry.includes('@') || entry.includes('://')) return 'a scheme or credentials';
+ if (entry.includes('*')) return 'a wildcard';
+ if (/[/?#]/.test(entry)) return 'a path';
+ if (/^[^:]+:\d*$/.test(entry)) return 'a port';
+ return parsedHostname(entry) === entry ? undefined : 'a spelling the URL parser rewrites';
+}
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.
+ * An entry is compared with the hostname of the URL, so one the check above names never matches, and the refusal it
+ * was meant to lift only says the destination is not allowed. Name such entries once, by position and reason.
*/
-function warnUnusableAllowedHosts(hosts: ReadonlySet<string>): void {
- const unusable = [...hosts].filter(host => !isIPv4(host) && !isIPv6(host) && !ALLOWED_HOST_PATTERN.test(host));
- const key = unusable.join(',');
+export function warnUnusableAllowedHosts(entries: readonly string[] = allowedHostEntries()): void {
+ const problems = entries.flatMap((entry, index) => {
+ const reason = entry ? unusableAllowedHostReason(entry) : undefined;
+ return reason ? [`entry ${index + 1} (${reason})`] : [];
+ });
+ const key = problems.join(', ');
if (key === warnedUnusableHosts) return;
warnedUnusableHosts = key;
- if (unusable.length > 0) {
+ if (problems.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(', ')}`,
+ 'SSRF_ALLOWED_HOSTS entries must be a bare host name or an IP address written as the URL parser prints it ' +
+ `(127.0.0.1, ::1); these never match and are ignored: ${key}`,
);
}
}
diff --git a/src/main.ts b/src/main.ts
index fec4fa8b8..2f9102be7 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -18,6 +18,7 @@ import {
import { registerUncaughtExceptionMonitor, registerUnhandledRejectionHandler } from './config/process-error-monitor';
import { runBootstrapOrExit } from './config/bootstrap-fatal';
import { s3EndpointError, validateEnv } from './config/env.validation';
+import { warnUnusableAllowedHosts } from './common/security/ssrf-guard';
import { resolveStorageRoot } from './config/storage-root';
import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';
import { applyGlobalValidation } from './config/app-validation';
@@ -76,6 +77,9 @@ async function bootstrap() {
);
}
+ // Reported at boot, where the operator reads the log, rather than at the first outbound request.
+ warnUnusableAllowedHosts();
+
// Advisory (not enforced): an unset/blank NODE_ENV is the deliberate local-dev default, but it
// silently degrades four controls to their dev posture (the default-secret guard, wildcard CORS,
// Swagger UI, validation error detail) — warn so a production deployment that simply forgot the