Skip to content

Commit c1d19ef

Browse files
Harden reverse-proxy IP handling and pin Remote-Upload to validated IPs
Reverse proxy (most deployments run behind nginx): - TRUST_PROXY env controls how the real client IP is derived from X-Forwarded-For (false / true / hop count / trusted subnets), feeding rate limiting, session IP tracking and audit logs. Previously this was implicitly "trust all in production". - API_HOST env binds the API (default 0.0.0.0); the wizard sets it to 127.0.0.1 and TRUST_PROXY=1 when it configures nginx, so the API isn't directly reachable and X-Forwarded-For can't be spoofed. SSRF (Remote-Upload) DNS-rebinding closed: - The fetcher now resolves and validates the host, then pins the connection to the exact validated IP via an undici dispatcher with a fixed lookup. TLS SNI and certificate validation still use the hostname. Verified: a host resolving to a private address is blocked, public downloads still work. Docs/compose updated; threat model reflects the closed rebinding gap and proxy guidance. New trust-proxy unit tests. Suite now 36 API tests.
1 parent 58b9b11 commit c1d19ef

13 files changed

Lines changed: 148 additions & 16 deletions

File tree

‎.env.example‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,15 @@ NODE_ENV=production
1010
APP_URL=http://localhost:3000
1111
# Port the API listens on (inside the container / process).
1212
API_PORT=4000
13+
# Address the API binds to. Behind an nginx reverse proxy set this to 127.0.0.1 so the API
14+
# cannot be reached directly (which would let clients spoof X-Forwarded-For).
15+
API_HOST=0.0.0.0
1316
# Port the web app listens on.
1417
WEB_PORT=3000
18+
# Reverse-proxy trust for deriving the real client IP from X-Forwarded-For (rate limiting,
19+
# session IP tracking, audit logs). "false" = no proxy; "1" = one nginx hop in front;
20+
# "true" = trust the whole chain; or a comma-separated list of trusted proxy IPs/subnets.
21+
TRUST_PROXY=false
1522

1623
# ── Database (PostgreSQL) ────────────────────────────────────────────────────
1724
POSTGRES_USER=opencoperlock

‎TEST-CHECKLIST.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,4 +113,22 @@ Versioning (text-like files: txt, md, csv, json, log, yml, …):
113113
account and all files, then signs you out. The only administrator cannot delete
114114
themselves.
115115

116+
## Reverse-proxy IP handling & SSRF pinning (lot 5)
117+
118+
Most operators run behind nginx, so client-IP handling and the Remote-Upload SSRF guard
119+
were hardened.
120+
121+
- [ ] **Behind nginx**: with `TRUST_PROXY=1` (and `API_HOST=127.0.0.1`), the IP shown for a
122+
session (Account → Active sessions) and in the admin audit log is the **real client
123+
IP**, not the nginx address. The setup wizard sets these automatically when it
124+
configures nginx.
125+
- [ ] **No proxy**: with `TRUST_PROXY=false` (default), the socket address is used. The app
126+
must not trust `X-Forwarded-For` from clients in this mode.
127+
- [ ] **SSRF rebinding**: a Remote-Upload of a host that resolves to a private address
128+
(e.g. a domain pointing at 127.0.0.1) is rejected; a normal public URL still
129+
downloads. (Verified automatically: the fetcher pins the connection to the validated
130+
IP.)
131+
- [ ] **Direct API access blocked**: when `API_HOST=127.0.0.1`, the API port is not
132+
reachable from outside the host — only nginx can reach it.
133+
116134
<!-- New features are appended below as they are built. -->

‎apps/api/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"fastify-plugin": "^5.0.1",
3333
"pino": "^9.5.0",
3434
"qrcode": "^1.5.4",
35+
"undici": "^6.21.0",
3536
"zod": "^3.24.1"
3637
},
3738
"devDependencies": {

‎apps/api/src/env.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,20 @@ import { loadMasterKey } from '@opencoperlock/shared';
99
const envSchema = z.object({
1010
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
1111
API_PORT: z.coerce.number().int().positive().default(4000),
12+
// Address the API binds to. Set to 127.0.0.1 when an nginx reverse proxy is in front,
13+
// so the API can't be reached directly (which would allow X-Forwarded-For spoofing).
14+
API_HOST: z.string().default('0.0.0.0'),
1215
APP_URL: z.string().url().default('http://localhost:3000'),
1316

17+
// Reverse-proxy trust. Controls how req.ip is derived from X-Forwarded-For, which feeds
18+
// rate limiting, session IP tracking and audit logs. Values:
19+
// "false" (default) — no proxy; use the socket address.
20+
// "true" — trust the whole X-Forwarded-For chain (only if the API is not
21+
// directly reachable).
22+
// a number — trust that many proxy hops (e.g. "1" for a single nginx).
23+
// IPs/subnets — comma-separated trusted proxy addresses (e.g. "127.0.0.1,::1").
24+
TRUST_PROXY: z.string().default('false'),
25+
1426
DATABASE_URL: z.string().min(1),
1527

1628
MASTER_KEY: z.string().min(1),

‎apps/api/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ async function main(): Promise<void> {
3333
process.on('SIGTERM', () => void shutdown('SIGTERM'));
3434
process.on('SIGINT', () => void shutdown('SIGINT'));
3535

36-
await app.listen({ host: '0.0.0.0', port: env.API_PORT });
36+
await app.listen({ host: env.API_HOST, port: env.API_PORT });
3737
}
3838

3939
main().catch((err) => {
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { parseTrustProxy } from './trust-proxy.js';
3+
4+
describe('parseTrustProxy', () => {
5+
it('treats empty/false as no trust', () => {
6+
expect(parseTrustProxy('')).toBe(false);
7+
expect(parseTrustProxy('false')).toBe(false);
8+
expect(parseTrustProxy('FALSE')).toBe(false);
9+
});
10+
it('treats true as full trust', () => {
11+
expect(parseTrustProxy('true')).toBe(true);
12+
});
13+
it('parses a hop count', () => {
14+
expect(parseTrustProxy('1')).toBe(1);
15+
expect(parseTrustProxy('3')).toBe(3);
16+
});
17+
it('parses a list of subnets', () => {
18+
expect(parseTrustProxy('127.0.0.1, ::1 , 10.0.0.0/8')).toEqual(['127.0.0.1', '::1', '10.0.0.0/8']);
19+
});
20+
});

‎apps/api/src/lib/trust-proxy.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* Parse the TRUST_PROXY env value into the form Fastify's `trustProxy` option expects.
3+
* See env.ts for the accepted values and why correct client-IP derivation matters behind
4+
* an nginx reverse proxy.
5+
*/
6+
export function parseTrustProxy(value: string): boolean | number | string[] {
7+
const v = value.trim();
8+
if (v === '' || v.toLowerCase() === 'false') return false;
9+
if (v.toLowerCase() === 'true') return true;
10+
if (/^\d+$/.test(v)) return Number(v);
11+
// Comma-separated list of trusted proxy IPs / subnets.
12+
return v
13+
.split(',')
14+
.map((s) => s.trim())
15+
.filter(Boolean);
16+
}

‎apps/api/src/server.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import multipart from '@fastify/multipart';
66
import rateLimit from '@fastify/rate-limit';
77
import type { AppContext } from './context.js';
88
import { getHealth } from './services/health.js';
9+
import { parseTrustProxy } from './lib/trust-proxy.js';
910
import authPlugin from './plugins/auth.js';
1011
import { authRoutes } from './routes/auth.js';
1112
import { folderRoutes } from './routes/folders.js';
@@ -33,8 +34,9 @@ export async function buildServer(ctx: AppContext): Promise<FastifyInstance> {
3334
? { target: 'pino-pretty', options: { translateTime: 'HH:MM:ss', ignore: 'pid,hostname' } }
3435
: undefined,
3536
},
36-
// We sit behind a reverse proxy in production; trust X-Forwarded-* for client IPs.
37-
trustProxy: ctx.env.NODE_ENV === 'production',
37+
// Derive the client IP from X-Forwarded-* according to the TRUST_PROXY policy. Behind
38+
// nginx this must be set (e.g. TRUST_PROXY=1) or req.ip would be the proxy's address.
39+
trustProxy: parseTrustProxy(ctx.env.TRUST_PROXY),
3840
bodyLimit: 1_048_576, // 1 MiB for JSON bodies; file uploads use multipart streaming.
3941
});
4042

‎apps/api/src/services/remote.ts‎

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,27 +3,55 @@
33
* 4G/5G never has to relay the bytes. Security-critical: this is an SSRF sink, so we
44
* - allow only http/https,
55
* - manually follow redirects, re-validating every hop,
6-
* - DNS-resolve each host and reject any private/reserved address,
6+
* - DNS-resolve each host, reject any private/reserved address, and then PIN the
7+
* connection to the exact validated IP (closing the DNS-rebinding window between
8+
* our lookup and the connect),
79
* - cap the response size.
8-
*
9-
* (DNS rebinding between our lookup and fetch remains a theoretical risk; documented
10-
* in THREAT_MODEL.md. Deployments needing stronger guarantees can run behind an egress
11-
* proxy that enforces the same allowlist.)
1210
*/
1311
import { lookup } from 'node:dns/promises';
12+
import { isIP } from 'node:net';
1413
import { Readable } from 'node:stream';
14+
import { Agent } from 'undici';
1515
import { assertAllowedUrl, isPrivateAddress, SsrfError } from '@opencoperlock/shared';
1616

1717
const MAX_REDIRECTS = 5;
1818

19-
async function assertHostResolvesPublic(hostname: string): Promise<void> {
20-
// Literal IPs are already checked by assertAllowedUrl; this covers DNS names.
19+
/**
20+
* Resolve a host, ensure every address is public, and return one validated address to
21+
* connect to. Literal IPs are returned as-is (already checked by assertAllowedUrl).
22+
*/
23+
async function resolvePublicAddress(hostname: string): Promise<string> {
24+
if (isIP(hostname)) return hostname;
2125
const records = await lookup(hostname, { all: true });
26+
if (records.length === 0) throw new SsrfError('Host does not resolve');
2227
for (const record of records) {
2328
if (isPrivateAddress(record.address)) {
2429
throw new SsrfError('Host resolves to a private or reserved address');
2530
}
2631
}
32+
return records[0]!.address;
33+
}
34+
35+
/**
36+
* An undici dispatcher whose DNS lookup is pinned to a single, pre-validated IP. The TLS
37+
* SNI / Host header still use the original hostname, so certificate validation is intact;
38+
* only the TCP target is fixed — a rebinding response after our check cannot redirect us
39+
* to an internal address.
40+
*/
41+
function pinnedDispatcher(ip: string): Agent {
42+
const family = isIP(ip);
43+
return new Agent({
44+
connect: {
45+
// undici calls this dns.lookup-style; honour both the `all` and single-result forms.
46+
lookup(_hostname, options, callback) {
47+
if (options && (options as { all?: boolean }).all) {
48+
callback(null, [{ address: ip, family }] as never);
49+
} else {
50+
(callback as (err: Error | null, address: string, family: number) => void)(null, ip, family);
51+
}
52+
},
53+
},
54+
});
2755
}
2856

2957
export interface RemoteSource {
@@ -65,12 +93,14 @@ export async function openRemoteSource(
6593
let current = assertAllowedUrl(rawUrl);
6694

6795
for (let hop = 0; hop <= MAX_REDIRECTS; hop += 1) {
68-
await assertHostResolvesPublic(current.hostname);
96+
const pinnedIp = await resolvePublicAddress(current.hostname);
97+
// `dispatcher` is an undici extension to global fetch; not in the DOM RequestInit type.
6998
const res = await fetch(current, {
7099
redirect: 'manual',
71100
headers: { 'user-agent': 'OpenCoperLock-RemoteUpload/0.1' },
72101
signal,
73-
});
102+
dispatcher: pinnedDispatcher(pinnedIp),
103+
} as RequestInit & { dispatcher: Agent });
74104

75105
// Manual redirect handling so we re-validate each Location.
76106
if (res.status >= 300 && res.status < 400) {

‎docs/THREAT_MODEL.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,10 @@ software that overpromises is worse than software that is clear about its bounda
4242

4343
- **Operator access to SERVER files.** SERVER mode is encryption *at rest*, not against the
4444
operator. Use a ZK vault for content the operator must not read.
45-
- **DNS rebinding** between the SSRF guard's DNS lookup and the actual fetch is a known
46-
theoretical gap. Deployments needing strong guarantees should place the API behind an
47-
egress proxy enforcing the same allowlist.
45+
- **DNS rebinding** for Remote-Upload is mitigated: after resolving and validating that a
46+
host's addresses are all public, the fetcher pins the connection to the validated IP (via
47+
an undici dispatcher with a fixed lookup), so a rebinding response cannot redirect the
48+
connect to an internal address. TLS SNI / certificate validation still use the hostname.
4849
- **Streaming AEAD ordering.** AES-GCM verifies the auth tag only after the final block, so
4950
a tampered/truncated blob surfaces as a stream error at the end of a download rather than
5051
before the first byte. Storage integrity is the first line of defence.
@@ -60,6 +61,9 @@ software that overpromises is worse than software that is clear about its bounda
6061

6162
- Set a unique, secret `MASTER_KEY` and `SESSION_SECRET`; store them outside the repo/DB.
6263
- Terminate TLS at a reverse proxy and set `APP_URL` to the `https://` origin.
64+
- Behind nginx, set `TRUST_PROXY=1` (or the proxy's IP/subnet) so client IPs are accurate,
65+
and `API_HOST=127.0.0.1` so the API is only reachable through the proxy (preventing
66+
`X-Forwarded-For` spoofing). The setup wizard does both automatically.
6367
- Keep ClamAV enabled and its signatures updated.
6468
- Back up Postgres **and** the storage volume together (they are useless apart).
6569
- Restrict who can reach the Postgres and clamav ports (they are internal to the compose network by default).

0 commit comments

Comments
 (0)