Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(security): match IPv6 trusted proxies and strip hop ports

Yudhi Armyndharisdfbd44c8e2fb
diff --git a/.env.example b/.env.example
index 3418bbb3a..1fa77c595 100644
--- a/.env.example
+++ b/.env.example
@@ -99,6 +99,8 @@ STATUS_SEED_ON_READY=false
# address, which prevents IP spoofing. If you run behind a reverse proxy AND use
# per-key allowedIps restrictions, set this to the proxy's address/subnet, e.g.:
# TRUSTED_PROXIES=172.18.0.0/16
+# IPv4 and IPv6 addresses and CIDRs are accepted (e.g. fd00::/8); an entry that is neither is
+# ignored with a boot warning.
# Docker daemon endpoint used to manage the built-in datastore containers (POSTGRES_BUILTIN,
# REDIS_BUILTIN, MINIO_BUILTIN — each in its own section below). Unset means /var/run/docker.sock.
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index 0d4b76dc0..0e34a448e 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -158,9 +158,11 @@ sub-resource, no per-entry `active` flag. Enforcement lives in two places:
### IPv6 Support
-CIDR matching is IPv4-only: an IPv6 range in `allowedIps` never matches. An exact IPv6 address still
-works, by literal comparison — IPv4-mapped forms (`::ffff:203.0.113.50`) are normalized to their bare
-IPv4 address first.
+`allowedIps` accepts IPv4 addresses and IPv4 CIDR ranges only; the API rejects an IPv6 entry. An
+IPv4-mapped client address (`::ffff:203.0.113.50`) is normalized to its bare IPv4 address before
+matching. `TRUSTED_PROXIES` accepts IPv4 and IPv6 addresses and CIDR ranges (for example `fd00::/8`);
+an entry that is neither is ignored, with a warning at boot. A trusted proxy that appends a port to
+an `X-Forwarded-For` hop (`203.0.113.7:51000`, `[2001:db8::1]:443`) resolves to the bare address.
## 4.4 Data Encryption
diff --git a/src/common/utils/ip.spec.ts b/src/common/utils/ip.spec.ts
index 56eb8302e..86fe6c995 100644
--- a/src/common/utils/ip.spec.ts
+++ b/src/common/utils/ip.spec.ts
@@ -1,4 +1,4 @@
-import { normalizeIp, ipMatches, limiterKeyForIp } from './ip';
+import { normalizeIp, ipMatches, limiterKeyForIp, resolveClientIp, isIpOrCidrEntry, invalidTrustedProxies } from './ip';
describe('normalizeIp', () => {
it('strips an IPv4-mapped IPv6 prefix', () => {
@@ -58,3 +58,78 @@ describe('ipMatches', () => {
expect(ipMatches('10.0.0.1', 'garbage/99')).toBe(false);
});
});
+
+describe('ipMatches with IPv6', () => {
+ it('matches within an IPv6 CIDR range', () => {
+ expect(ipMatches('fd00:10:244::7', 'fd00::/8')).toBe(true);
+ expect(ipMatches('fe80::1', 'fd00::/8')).toBe(false);
+ expect(ipMatches('2001:db8:1:2::a', '2001:db8:1::/48')).toBe(true);
+ expect(ipMatches('2001:db8:2::a', '2001:db8:1::/48')).toBe(false);
+ });
+
+ it('matches an exact IPv6 address in compressed or expanded form, in any case', () => {
+ expect(ipMatches('2001:db8::1', '2001:0db8:0000:0000:0000:0000:0000:0001')).toBe(true);
+ expect(ipMatches('2001:DB8::1', '2001:db8::1')).toBe(true);
+ expect(ipMatches('2001:db8::2', '2001:db8::1')).toBe(false);
+ });
+
+ it('never matches across address families', () => {
+ expect(ipMatches('10.0.0.1', '::/0')).toBe(false);
+ expect(ipMatches('2001:db8::1', '0.0.0.0/0')).toBe(false);
+ });
+
+ it('returns false for a malformed IPv6 target or prefix', () => {
+ expect(ipMatches('fd00::1', 'fd00::/129')).toBe(false);
+ expect(ipMatches('fd00::1', 'fd00::zz/8')).toBe(false);
+ expect(ipMatches('fd00::1', 'fd00::/8/1')).toBe(false);
+ expect(ipMatches('fd00::1', 'fd00::/')).toBe(false);
+ });
+});
+
+describe('isIpOrCidrEntry / invalidTrustedProxies', () => {
+ it('accepts IPv4 and IPv6 addresses and CIDRs', () => {
+ for (const entry of ['10.0.0.1', '172.18.0.0/16', '2001:db8::1', 'fd00::/8', '::ffff:10.0.0.1']) {
+ expect(isIpOrCidrEntry(entry)).toBe(true);
+ }
+ });
+
+ it('lists only the entries that are neither an IP nor a CIDR', () => {
+ expect(invalidTrustedProxies(' 10.0.0.1, proxy.internal ,fd00::/8,, 10.0.0.0/33 ')).toEqual([
+ 'proxy.internal',
+ '10.0.0.0/33',
+ ]);
+ expect(invalidTrustedProxies(undefined)).toEqual([]);
+ });
+});
+
+describe('resolveClientIp', () => {
+ const req = (socketIp: string, xff?: string) => ({
+ socket: { remoteAddress: socketIp },
+ headers: xff === undefined ? {} : { 'x-forwarded-for': xff },
+ });
+
+ it('honors X-Forwarded-For from a proxy inside an IPv6 CIDR', () => {
+ expect(resolveClientIp(req('fd00:10:244::7', '198.51.100.20'), ['fd00::/8'])).toBe('198.51.100.20');
+ });
+
+ it('strips a port from an IPv4 hop, so one client resolves to one address', () => {
+ const a = resolveClientIp(req('10.0.0.2', '198.51.100.20:51000'), ['10.0.0.0/8']);
+ const b = resolveClientIp(req('10.0.0.2', '198.51.100.20:51001'), ['10.0.0.0/8']);
+ expect(a).toBe('198.51.100.20');
+ expect(b).toBe('198.51.100.20');
+ expect(ipMatches(a, '198.51.100.20')).toBe(true);
+ });
+
+ it('strips brackets and a port from an IPv6 hop', () => {
+ expect(resolveClientIp(req('10.0.0.2', '[2001:db8::1]:443'), ['10.0.0.0/8'])).toBe('2001:db8::1');
+ expect(resolveClientIp(req('10.0.0.2', '[2001:db8::1]'), ['10.0.0.0/8'])).toBe('2001:db8::1');
+ });
+
+ it('leaves a bare IPv6 hop untouched', () => {
+ expect(resolveClientIp(req('10.0.0.2', '2001:db8::1:443'), ['10.0.0.0/8'])).toBe('2001:db8::1:443');
+ });
+
+ it('skips a trusted hop that carries a port', () => {
+ expect(resolveClientIp(req('10.0.0.2', '198.51.100.20, 10.0.0.9:8080'), ['10.0.0.0/8'])).toBe('198.51.100.20');
+ });
+});
diff --git a/src/common/utils/ip.ts b/src/common/utils/ip.ts
index 5ae9205d1..75f1cf827 100644
--- a/src/common/utils/ip.ts
+++ b/src/common/utils/ip.ts
@@ -1,3 +1,4 @@
+import { BlockList, isIP } from 'net';
import { normalizeIp as maskIpv6Subnet } from '@nestjs/throttler';
/**
@@ -45,7 +46,7 @@ export function resolveClientIp(req: RequestLike, trustedProxies: string[]): str
const hops = (Array.isArray(forwarded) ? forwarded.join(',') : forwarded)
.split(',')
- .map(hop => normalizeIp(hop.trim()))
+ .map(hop => normalizeIp(stripHopPort(hop.trim())))
.filter(Boolean);
// Walk right-to-left and return the first hop that is not a trusted proxy:
@@ -59,6 +60,18 @@ export function resolveClientIp(req: RequestLike, trustedProxies: string[]): str
return socketIp;
}
+/**
+ * Drop a port some proxies append to an X-Forwarded-For hop: `203.0.113.7:51000` and
+ * `[2001:db8::1]:443` (or bracketed without a port). A bare IPv6 address is left alone, since its
+ * last group cannot be told apart from a port.
+ */
+function stripHopPort(hop: string): string {
+ const v4 = /^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/.exec(hop);
+ if (v4) return v4[1];
+ const v6 = /^\[([0-9a-f:.]+)\](?::\d+)?$/i.exec(hop);
+ return v6 ? v6[1] : hop;
+}
+
/**
* Key for a per-client limiter, budget or counter: an IPv6 address is masked to its /64 (the
* `@nestjs/throttler` default the global guard uses), so a client holding a /64 cannot rotate
@@ -71,41 +84,61 @@ export function limiterKeyForIp(ip: string): string {
return maskIpv6Subnet(ip, 64);
}
-function ipv4ToInt(ip: string): number | null {
- const parts = ip.split('.');
- if (parts.length !== 4) return null;
- let result = 0;
- for (const part of parts) {
- if (!/^\d{1,3}$/.test(part)) return null;
- const octet = Number(part);
- if (octet > 255) return null;
- result = result * 256 + octet;
- }
- return result >>> 0;
+interface IpTarget {
+ address: string;
+ type: 'ipv4' | 'ipv6';
+ /** Prefix length for a CIDR; absent for an exact address. */
+ bits?: number;
+}
+
+/** Parse an exact IPv4/IPv6 address or CIDR; null when `entry` is neither. */
+function parseIpTarget(entry: string): IpTarget | null {
+ const ref = (entry || '').trim();
+ const slash = ref.indexOf('/');
+ const address = normalizeIp(slash === -1 ? ref : ref.slice(0, slash));
+ const family = isIP(address);
+ if (family === 0) return null;
+ const type = family === 6 ? 'ipv6' : 'ipv4';
+ if (slash === -1) return { address, type };
+ const bitsRaw = ref.slice(slash + 1);
+ if (!/^\d{1,3}$/.test(bitsRaw)) return null;
+ const bits = Number(bitsRaw);
+ if (bits > (family === 6 ? 128 : 32)) return null;
+ return { address, type, bits };
+}
+
+/** True if `entry` is an exact IPv4/IPv6 address or a CIDR range. */
+export function isIpOrCidrEntry(entry: string): boolean {
+ return parseIpTarget(entry) !== null;
}
/**
- * True if `ip` equals or falls within `target`, where `target` is either an
- * exact IP or an IPv4 CIDR (e.g. `172.18.0.0/16`). IPv4-mapped IPv6 inputs are
- * normalized first. Malformed input yields `false` rather than throwing.
+ * The TRUSTED_PROXIES entries (comma-separated) that are neither an IP nor a CIDR. Such an entry
+ * never matches a peer, so the proxy it was meant to name is treated as a direct client.
+ */
+export function invalidTrustedProxies(raw: string | undefined): string[] {
+ return (raw || '')
+ .split(',')
+ .map(entry => entry.trim())
+ .filter(entry => entry && !isIpOrCidrEntry(entry));
+}
+
+/**
+ * True if `ip` equals or falls within `target`, where `target` is an exact IP or a CIDR range, IPv4
+ * (`172.18.0.0/16`) or IPv6 (`fd00::/8`). IPv4-mapped IPv6 inputs are normalized first, an address
+ * never matches a target of the other family, and compressed and expanded IPv6 forms compare equal.
+ * Malformed input yields `false` rather than throwing.
*/
export function ipMatches(ip: string, target: string): boolean {
const candidate = normalizeIp((ip || '').trim());
- const ref = (target || '').trim();
-
- if (!ref.includes('/')) {
- return normalizeIp(ref) === candidate;
+ const parsed = parseIpTarget(target);
+ if (!parsed || isIP(candidate) !== (parsed.type === 'ipv6' ? 6 : 4)) return false;
+ try {
+ const list = new BlockList();
+ if (parsed.bits === undefined) list.addAddress(parsed.address, parsed.type);
+ else list.addSubnet(parsed.address, parsed.bits, parsed.type);
+ return list.check(candidate, parsed.type);
+ } catch {
+ return false;
}
-
- const [range, bitsRaw] = ref.split('/');
- const bits = Number(bitsRaw);
- if (!Number.isInteger(bits) || bits < 0 || bits > 32) return false;
-
- const ipInt = ipv4ToInt(candidate);
- const rangeInt = ipv4ToInt(normalizeIp(range));
- if (ipInt === null || rangeInt === null) return false;
-
- if (bits === 0) return true;
- const mask = (0xffffffff << (32 - bits)) >>> 0;
- return (ipInt & mask) === (rangeInt & mask);
}
diff --git a/src/main.ts b/src/main.ts
index ecb1c6248..7010b6a29 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -24,6 +24,7 @@ import {
isNodeEnvUnset,
} from './config/bootstrap-security';
import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';
+import { invalidTrustedProxies } from './common/utils/ip';
import { AuthService } from './modules/auth/auth.service';
import { AuditService } from './modules/audit/audit.service';
import { Request, Response, NextFunction } from 'express';
@@ -94,6 +95,15 @@ async function bootstrap() {
);
}
+ // Advisory (not enforced): a TRUSTED_PROXIES entry that is not an IP or CIDR never matches, so the
+ // proxy it meant to name is treated as a client. Failing the boot would break configs that run today.
+ const badTrustedProxies = invalidTrustedProxies(process.env.TRUSTED_PROXIES);
+ if (badTrustedProxies.length > 0) {
+ bootstrapLogger.warn(
+ `TRUSTED_PROXIES entries that are not an IP address or CIDR range are ignored: ${badTrustedProxies.join(', ')}`,
+ );
+ }
+
// Fail fast on a media storage root the app cannot write to, BEFORE Nest builds the module graph:
// StorageService only checks that the root EXISTS, so a root owned by another user passes boot and
// fails later on the first media write instead (#1065). Runs ahead of NestFactory.create so
diff --git a/src/modules/auth/dto/is-ip-or-cidr.validator.spec.ts b/src/modules/auth/dto/is-ip-or-cidr.validator.spec.ts
index 7584d2939..f7ccb7469 100644
--- a/src/modules/auth/dto/is-ip-or-cidr.validator.spec.ts
+++ b/src/modules/auth/dto/is-ip-or-cidr.validator.spec.ts
@@ -27,11 +27,10 @@ describe('isIpOrCidr', () => {
expect(isIpOrCidr(v)).toBe(false);
});
- // IPv6 is rejected on purpose: the allowedIps matcher (auth.service) is IPv4-only, so an IPv6
- // CIDR would either lock out its own client (/128) or match every IPv6 client (/<=32). The
- // validator must not bless an entry the matcher can't enforce. allowedIps is IPv4-only.
+ // IPv6 is rejected on purpose: allowedIps is documented as IPv4-only. Widening it is a separate
+ // change, even though the shared matcher handles IPv6.
it.each(['::1', '2001:db8::1', '::/0', '2001:db8::/32', '::1/128', 'fe80::1%eth0', '::ffff:10.0.0.1'])(
- 'rejects IPv6 (unsupported by the matcher) %s',
+ 'rejects IPv6 (allowedIps is IPv4-only) %s',
v => {
expect(isIpOrCidr(v)).toBe(false);
},
@@ -55,7 +54,7 @@ describe('CreateApiKeyDto allowedIps (@Validate each)', () => {
expect(msgs.length).toBeGreaterThan(0);
});
- it('rejects an IPv6 element (matcher is IPv4-only)', async () => {
+ it('rejects an IPv6 element (allowedIps is IPv4-only)', async () => {
expect((await errorsFor(['2001:db8::/32'])).length).toBeGreaterThan(0);
});
diff --git a/src/modules/auth/dto/is-ip-or-cidr.validator.ts b/src/modules/auth/dto/is-ip-or-cidr.validator.ts
index 238fdd565..7d9edb173 100644
--- a/src/modules/auth/dto/is-ip-or-cidr.validator.ts
+++ b/src/modules/auth/dto/is-ip-or-cidr.validator.ts
@@ -4,10 +4,8 @@ import { isIP } from 'net';
/**
* Whether a string is a valid IPv4 address or IPv4 CIDR range (/0-32).
*
- * IPv4-only on purpose: the allowedIps matcher (auth.service `isIpAllowed`/`ipInCidr`) is IPv4-only,
- * so an IPv6 entry can't be enforced — a /128 host-lock would never match its own client, and an
- * IPv6 /<=32 CIDR would match EVERY IPv6 client (an over-broad grant). The validator must not bless
- * an entry the matcher can't honor, so it rejects IPv6 (`allowedIps` is documented as IPv4-only).
+ * IPv4-only on purpose: `allowedIps` is documented as IPv4-only (docs/04, IPv6 Support). The shared
+ * `ipMatches` helper also handles IPv6, so widening this validator is a separate, deliberate change.
*/
export function isIpOrCidr(value: unknown): boolean {
if (typeof value !== 'string') return false;