diff --git a/.env.example b/.env.example index b893b8b..e6ebc23 100644 --- a/.env.example +++ b/.env.example @@ -131,3 +131,24 @@ ISMALICIOUS_KEY= # (e.g. a Discord bot on your private network). # GITHUB_WEBHOOK_SECRET= # GITHUB_WEBHOOK_FORWARD_URL=http://:/github/webhook + +# RECON scanner access (OWASP A01). /api/scanner makes this server probe +# arbitrary public hosts, so production builds refuse remote callers (403) +# unless one of these is set. `npm run dev` / `npm run osiris` on localhost +# works without either. +# SCANNER_ACCESS_TOKEN — shared secret for trusted users; the RECON panel +# prompts for it once per browser tab (sessionStorage) and sends it as the +# X-Scanner-Token header. Generate with: openssl rand -hex 32 +# SCANNER_ALLOW_ANONYMOUS=true — let ANY visitor run scans. Not recommended: +# your server becomes a public scan relay that targets see as your IP. +# SCANNER_ACCESS_TOKEN= +# SCANNER_ALLOW_ANONYMOUS=false + +# Client-IP trust for rate limits + audit log. Next.js passes a client-sent +# X-Forwarded-For through unchanged, so forwarding headers are ignored (all +# clients share one rate-limit bucket) unless you run behind a proxy that +# sets them AND the app port is reachable only through that proxy: +# true one proxy (e.g. the bundled nginx): rightmost X-Forwarded-For +# N proxies in a chain: Nth X-Forwarded-For entry from the right +# cloudflare use CF-Connecting-IP (origin must accept only Cloudflare IPs) +# TRUST_PROXY_HEADERS= diff --git a/DOCKER.md b/DOCKER.md index 75ca942..db435d4 100644 --- a/DOCKER.md +++ b/DOCKER.md @@ -137,10 +137,29 @@ Copy `.env.template` to `.env` and fill in only what you need. |----------|---------|--------------| | `SCANNER_URL` | RECON scanner backend base URL (e.g. `http://scanner:7700`) | RECON toolkit (quick/ssl/headers/rdns/subdomains/tech/whois/geoloc/vuln) | | `SCANNER_KEY` | Shared secret; **must equal the backend's `OSIRIS_KEY`** | RECON toolkit | +| `SCANNER_ACCESS_TOKEN` | Token trusted users enter in the RECON panel (sent as `X-Scanner-Token`) | RECON toolkit on any production/Docker deployment | +| `SCANNER_ALLOW_ANONYMOUS` | `true` lets **any** visitor run scans (not recommended) | Public scanner, deliberately | +| `TRUST_PROXY_HEADERS` | `true` / `` / `cloudflare` — honour forwarding headers for client IP | Per-client rate limits behind a reverse proxy | Without `SCANNER_URL`/`SCANNER_KEY` the RECON endpoints return `503` and the rest of OSIRIS works normally. Generate a key with `openssl rand -hex 32`. +**Scanner access (closed by default).** The scanner makes your server probe +arbitrary public hosts, so a production build — including this Docker image — +answers `403` to RECON scans unless you set `SCANNER_ACCESS_TOKEN` (the RECON +panel prompts for it once per browser tab) or, deliberately, +`SCANNER_ALLOW_ANONYMOUS=true`. Only `npm run dev` on localhost works without +either. *Upgrading:* if you used the RECON panel on a Docker/public host, set +`SCANNER_ACCESS_TOKEN` or it stops working. + +**Client IP behind nginx.** Next.js forwards a client-supplied +`X-Forwarded-For` unchanged, so OSIRIS ignores forwarding headers by default +(all clients then share one rate-limit bucket). Behind the bundled nginx, set +`TRUST_PROXY_HEADERS=true` — OSIRIS then uses the rightmost `X-Forwarded-For` +entry, which nginx appends from the real socket address. Only do this if the +app port (`OSIRIS_PORT`, 3000) is not reachable except through the proxy; +otherwise clients can connect directly and forge the header. + ### Optional keys (reserved / for higher rate limits) These are documented for completeness and forward-compatibility. The current diff --git a/README.md b/README.md index c373ba0..dde0039 100644 --- a/README.md +++ b/README.md @@ -340,6 +340,12 @@ Place the `osiris-scanner` sidecar as a sibling folder, then: npm run osiris # starts scanner (:7700) + dashboard (:3000) ``` +The dev server allows RECON scans from `localhost` with no extra setup. A +production build (`npm start`, Docker, any public host) refuses them until you +set `SCANNER_ACCESS_TOKEN` (the RECON panel prompts for it once per tab) or, +not recommended, `SCANNER_ALLOW_ANONYMOUS=true`. See +[DOCKER.md](DOCKER.md#3-api-keys--data-sources). + Build for production: ```bash @@ -356,6 +362,8 @@ npm run build && npm start |----------|---------|--------| | `GEMINI_API_KEY_1..8` | AI Intelligence Analyst (Gemini 2.5 Flash + web search) | [Google AI Studio](https://aistudio.google.com/apikey) (free) | | `SCANNER_URL`, `SCANNER_KEY` | RECON toolkit (port scan, SSL, DNS, WHOIS, vuln) | Generate a key, match in `osiris-scanner` sidecar | +| `SCANNER_ACCESS_TOKEN` / `SCANNER_ALLOW_ANONYMOUS` | RECON scans on production/public hosts (closed by default) | `openssl rand -hex 32`; give the token to trusted users | +| `TRUST_PROXY_HEADERS` | Per-client rate limits behind a reverse proxy (`true`, hop count, or `cloudflare`) | Set only when the app port is reachable solely via the proxy | | `URLHAUS_KEY` | URLhaus malware lookups | [abuse.ch auth](https://auth.abuse.ch/) (free) | | `ISMALICIOUS_KEY`, `ISMALICIOUS_SECRET` | IsMalicious threat lookups (auth = base64 key:secret) | [IsMalicious](https://ismalicious.com/) | | `NVD_API_KEY` (scanner) | Faster vuln-scan CVE lookups (50 req/30s vs ~5) | [NVD](https://nvd.nist.gov/developers/request-an-api-key) (free) | @@ -554,7 +562,8 @@ Every data domain gets its own isolated route under `src/app/api/`: - **🔄 Stateless API** — Backend routes are stateless and cache-friendly, enabling horizontal scaling - **🛡️ SSRF protection** — `ssrf-guard.ts` validates all outbound URLs against private IP ranges before fetching - **🔒 Proxy security** — CCTV proxies enforce strict host allowlists and content-type validation; HLS proxy includes CORS-aware origin headers -- **📦 Rate-limited endpoints** — AI analysis, IP sweep, and scanner endpoints all have per-IP rate limiting +- **📦 Rate-limited endpoints** — AI analysis, IP sweep, and scanner endpoints all have per-IP rate limiting (forwarding headers are trusted only with `TRUST_PROXY_HEADERS`) +- **🔑 Scanner access gate** — the RECON scanner proxy is closed to remote callers on production builds unless the operator sets `SCANNER_ACCESS_TOKEN` (or explicitly `SCANNER_ALLOW_ANONYMOUS=true`) - **🔗 Entity linking** — Sanctions cross-checking and OFAC/SDN matching is built into WHOIS and IP intel routes --- diff --git a/nginx/nginx.conf b/nginx/nginx.conf index 6a09a1a..f31bc72 100644 --- a/nginx/nginx.conf +++ b/nginx/nginx.conf @@ -54,6 +54,10 @@ http { proxy_pass http://osiris:3000; proxy_set_header Host $host; + # X-Real-IP is overwritten and X-Forwarded-For has $remote_addr + # APPENDED, so the rightmost XFF entry is the real client. OSIRIS + # reads it only when TRUST_PROXY_HEADERS=true (see .env.example); + # anything to its left is client-supplied and never trusted. proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; diff --git a/src/app/api/scanner-access.test.ts b/src/app/api/scanner-access.test.ts new file mode 100644 index 0000000..cf3930c --- /dev/null +++ b/src/app/api/scanner-access.test.ts @@ -0,0 +1,166 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; + +// OWASP A01: the scanner proxy must be closed to anonymous remote callers by +// default. Every test records what the route tries to fetch upstream. +let calls: string[] = []; +function stubFetch() { + calls = []; + vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL) => { + calls.push(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url); + return Response.json({ ok: true, scanned: true }); + })); +} + +const ENV_KEYS = ['SCANNER_URL', 'SCANNER_KEY', 'SCANNER_ACCESS_TOKEN', 'SCANNER_ALLOW_ANONYMOUS', 'TRUST_PROXY_HEADERS'] as const; + +function setEnv(vars: Partial>) { + for (const k of ENV_KEYS) vi.stubEnv(k, undefined as unknown as string); + vi.stubEnv('SCANNER_URL', 'http://scanner.test:7700'); + vi.stubEnv('SCANNER_KEY', 'sidecar-secret'); + for (const [k, v] of Object.entries(vars)) vi.stubEnv(k, v); +} + +// The route reads SCANNER_URL/KEY at module load and ssrf-guard keeps its +// rate-limit map in module state, so import a fresh copy per test. +async function route() { + vi.resetModules(); + return import('./scanner/route'); +} + +const PUBLIC_IP = '93.184.215.14'; // literal → no DNS in tests +function req(qs: string, headers: Record = {}) { + return new Request(`http://osiris.example.com/api/scanner?${qs}`, { + headers: { host: 'osiris.example.com', ...headers }, + }); +} + +beforeEach(() => stubFetch()); +afterEach(() => { + vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +describe('scanner: access gate', () => { + it('default config (no token, no opt-in, production) → 403 and no upstream fetch', async () => { + setEnv({ NODE_ENV: 'production' }); + const { GET } = await route(); + const res = await GET(req(`target=${PUBLIC_IP}&type=quick`)); + expect(res.status).toBe(403); + expect(calls).toHaveLength(0); + }); + + it('token configured but missing → 401 (prompts the UI), no fetch', async () => { + setEnv({ NODE_ENV: 'production', SCANNER_ACCESS_TOKEN: 'correct-horse' }); + const { GET } = await route(); + const res = await GET(req(`target=${PUBLIC_IP}`)); + expect(res.status).toBe(401); + expect((await res.json()).auth).toBe('token'); + expect(calls).toHaveLength(0); + }); + + it('wrong token → 401, no fetch', async () => { + setEnv({ NODE_ENV: 'production', SCANNER_ACCESS_TOKEN: 'correct-horse' }); + const { GET } = await route(); + const res = await GET(req(`target=${PUBLIC_IP}`, { 'x-scanner-token': 'correct-hors' })); + expect(res.status).toBe(401); + expect(calls).toHaveLength(0); + }); + + it('correct token → proxied to the sidecar', async () => { + setEnv({ NODE_ENV: 'production', SCANNER_ACCESS_TOKEN: 'correct-horse' }); + const { GET } = await route(); + const res = await GET(req(`target=${PUBLIC_IP}&type=ssl`, { 'x-scanner-token': 'correct-horse' })); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + expect(calls[0].startsWith('http://scanner.test:7700/scan/ssl?')).toBe(true); + }); + + it('SCANNER_ALLOW_ANONYMOUS=true → proxied without a token', async () => { + setEnv({ NODE_ENV: 'production', SCANNER_ALLOW_ANONYMOUS: 'true' }); + const { GET } = await route(); + const res = await GET(req(`target=${PUBLIC_IP}`)); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + }); + + it('next dev + loopback request → proxied with zero config', async () => { + setEnv({ NODE_ENV: 'development' }); + const { GET } = await route(); + const res = await GET(req(`target=${PUBLIC_IP}`, { host: 'localhost:3000', 'x-forwarded-for': '::1', 'sec-fetch-site': 'same-origin' })); + expect(res.status).toBe(200); + expect(calls).toHaveLength(1); + }); + + it.each([ + ['production build, localhost Host', 'production', { host: 'localhost:3000', 'x-forwarded-for': '::1' }], + ['dev, public Host (LAN / DNS rebinding)', 'development', { host: 'osiris.example.com', 'x-forwarded-for': '::1' }], + ['dev, non-loopback X-Forwarded-For (proxy)', 'development', { host: 'localhost:3000', 'x-forwarded-for': '203.0.113.9' }], + ['dev, cross-site browser request', 'development', { host: 'localhost:3000', 'x-forwarded-for': '::1', 'sec-fetch-site': 'cross-site' }], + ])('not treated as local: %s → 403, no fetch', async (_name, nodeEnv, headers) => { + setEnv({ NODE_ENV: nodeEnv }); + const { GET } = await route(); + const res = await GET(req(`target=${PUBLIC_IP}`, headers)); + expect(res.status).toBe(403); + expect(calls).toHaveLength(0); + }); + + it('unconfigured scanner still answers 503', async () => { + setEnv({ NODE_ENV: 'production', SCANNER_ALLOW_ANONYMOUS: 'true' }); + vi.stubEnv('SCANNER_KEY', ''); + const { GET } = await route(); + expect((await GET(req(`target=${PUBLIC_IP}`))).status).toBe(503); + expect(calls).toHaveLength(0); + }); +}); + +describe('scanner: SSRF + scan-type allowlist unchanged for authorised callers', () => { + const auth = { 'x-scanner-token': 'correct-horse' }; + + it.each(['127.0.0.1', '169.254.169.254', '10.0.0.1', '::1', 'localhost', '2130706433'])('blocks internal target %s', async (target) => { + setEnv({ NODE_ENV: 'production', SCANNER_ACCESS_TOKEN: 'correct-horse' }); + const { GET } = await route(); + const res = await GET(req(`target=${encodeURIComponent(target)}`, auth)); + expect(res.status).toBe(403); + expect((await res.json()).error).toBe('Target blocked'); + expect(calls).toHaveLength(0); + }); + + it.each(['deep', 'ports', 'banner', 'traceroute', 'constructor'])('refuses restricted scan type %s', async (type) => { + setEnv({ NODE_ENV: 'production', SCANNER_ACCESS_TOKEN: 'correct-horse' }); + const { GET } = await route(); + const res = await GET(req(`target=${PUBLIC_IP}&type=${type}`, auth)); + expect(res.status).toBe(403); + expect(calls).toHaveLength(0); + }); + + it('missing target → 400', async () => { + setEnv({ NODE_ENV: 'production', SCANNER_ACCESS_TOKEN: 'correct-horse' }); + const { GET } = await route(); + expect((await GET(req('type=quick', auth))).status).toBe(400); + }); +}); + +describe('scanner: rate limit cannot be dodged with forged forwarding headers', () => { + it('rotating X-Forwarded-For does not reset the limit when proxy headers are untrusted', async () => { + setEnv({ NODE_ENV: 'production', SCANNER_ALLOW_ANONYMOUS: 'true' }); + const { GET } = await route(); + const statuses: number[] = []; + for (let i = 1; i <= 6; i++) { + const res = await GET(req(`target=${PUBLIC_IP}`, { 'x-forwarded-for': `198.51.100.${i}`, 'x-real-ip': `198.51.100.${i}` })); + statuses.push(res.status); + } + expect(statuses).toEqual([200, 200, 200, 200, 200, 429]); + }); + + it('with TRUST_PROXY_HEADERS=true, distinct proxy-reported clients get separate buckets', async () => { + setEnv({ NODE_ENV: 'production', SCANNER_ALLOW_ANONYMOUS: 'true', TRUST_PROXY_HEADERS: 'true' }); + const { GET } = await route(); + const statuses: number[] = []; + for (let i = 1; i <= 6; i++) { + // client-forged first entry stays constant; the proxy-appended last entry varies + const res = await GET(req(`target=${PUBLIC_IP}`, { 'x-forwarded-for': `1.1.1.1, 203.0.113.${i}` })); + statuses.push(res.status); + } + expect(statuses).toEqual([200, 200, 200, 200, 200, 200]); + }); +}); diff --git a/src/app/api/scanner/route.ts b/src/app/api/scanner/route.ts index 63cdcd4..fb952cf 100644 --- a/src/app/api/scanner/route.ts +++ b/src/app/api/scanner/route.ts @@ -1,9 +1,10 @@ import { NextResponse } from 'next/server'; import { validateHost, isRateLimited, getClientIp } from '@/lib/ssrf-guard'; +import { checkScannerAccess } from '@/lib/scanner-access'; /** * OSIRIS — Scanner Proxy (Hardened) - * Rate-limited, target-validated, scope-restricted + * Access-gated, rate-limited, target-validated, scope-restricted */ const SCANNER_URL = process.env.SCANNER_URL || ''; @@ -51,6 +52,15 @@ export async function GET(req: Request) { }, { status: 429 }); } + // 2b. Access gate (OWASP A01): closed on public hosts unless the operator + // issues SCANNER_ACCESS_TOKEN or opts in with SCANNER_ALLOW_ANONYMOUS. + // Runs after the rate limit so token guesses are throttled too. See + // src/lib/scanner-access.ts for the threat model. + const access = checkScannerAccess(req); + if (!access.ok) { + return NextResponse.json(access.body, { status: access.status }); + } + // 3. Validate params const { searchParams } = new URL(req.url); const target = searchParams.get('target')?.trim(); @@ -72,7 +82,8 @@ export async function GET(req: Request) { } // 5. Validate scan type (only safe scans allowed) - const scanConfig = ALLOWED_SCANS[scanType]; + // Own keys only: `type=constructor` must not resolve via Object.prototype. + const scanConfig = Object.hasOwn(ALLOWED_SCANS, scanType) ? ALLOWED_SCANS[scanType] : undefined; if (!scanConfig) { return NextResponse.json({ error: 'Scan type not available', diff --git a/src/components/OsintPanel.tsx b/src/components/OsintPanel.tsx index 0d5a1d2..51f3b08 100644 --- a/src/components/OsintPanel.tsx +++ b/src/components/OsintPanel.tsx @@ -13,6 +13,40 @@ import { } from 'lucide-react'; import { ipToNumber, numberToIp, calculateSubnetStart, classifyDevice, assessRisk, batchFetch, ShodanInternetDBResponse, SweepDevice } from '@/lib/osint-utils'; +// ── Scanner access token (OWASP A01) ── +// On public deployments /api/scanner answers 401 unless the request carries +// the operator-issued SCANNER_ACCESS_TOKEN. Prompt once on a 401 and keep the +// token for this browser tab only (sessionStorage, not localStorage). +const SCANNER_TOKEN_STORAGE_KEY = 'osiris.scannerAccessToken'; + +function readScannerToken(): string { + try { return sessionStorage.getItem(SCANNER_TOKEN_STORAGE_KEY) || ''; } catch { return ''; } +} + +function writeScannerToken(token: string | null): void { + try { + if (token) sessionStorage.setItem(SCANNER_TOKEN_STORAGE_KEY, token); + else sessionStorage.removeItem(SCANNER_TOKEN_STORAGE_KEY); + } catch { /* storage unavailable: token lives for this request only */ } +} + +async function fetchScanner(url: string): Promise { + const send = (token: string) => fetch(url, token ? { headers: { 'X-Scanner-Token': token } } : undefined); + const stored = readScannerToken(); + const res = await send(stored); + if (res.status !== 401) return res; + writeScannerToken(null); + const entered = window.prompt( + stored + ? 'The saved scanner access token was rejected. Enter the SCANNER_ACCESS_TOKEN for this OSIRIS instance:' + : 'This OSIRIS instance requires a scanner access token. Enter the SCANNER_ACCESS_TOKEN issued by its operator:', + )?.trim(); + if (!entered) return res; + const retry = await send(entered); + if (retry.status !== 401) writeScannerToken(entered); + return retry; +} + const TABS = [ { id: 'scanner', label: 'PORT SCAN', icon: Radar, placeholder: 'IP or hostname', color: '#1A73E8' }, { id: 'vuln', label: 'VULN SWEEP', icon: Bug, placeholder: 'IP or hostname', color: '#FF3D3D' }, @@ -223,7 +257,9 @@ function OsintPanelInner({ isMobile, onSweepVisualize, onScanGeolocate, onReconF break; } } - const res = await fetch(url, activeTab === 'shodan' ? { cache: 'no-store' } : undefined); + const res = url.startsWith('/api/scanner') + ? await fetchScanner(url) + : await fetch(url, activeTab === 'shodan' ? { cache: 'no-store' } : undefined); if (activeTab === 'shodan' && res.status === 404) { setResults({ ip: query, status: 'No Shodan InternetDB records found', ports: [], cpes: [], hostnames: [], tags: [], vulns: [] }); setLoading(false); diff --git a/src/lib/client-ip.test.ts b/src/lib/client-ip.test.ts new file mode 100644 index 0000000..bf65a5f --- /dev/null +++ b/src/lib/client-ip.test.ts @@ -0,0 +1,50 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { clientIp as guardClientIp } from './guard'; +import { getClientIp } from './ssrf-guard'; + +const forged = { + 'x-forwarded-for': '6.6.6.6', + 'x-real-ip': '7.7.7.7', + 'cf-connecting-ip': '8.8.8.8', +}; +const r = (headers: Record) => new Request('http://x/', { headers }); + +afterEach(() => vi.unstubAllEnvs()); + +describe.each([ + ['guard.clientIp', guardClientIp], + ['ssrf-guard.getClientIp', getClientIp], +])('%s', (_name, ip) => { + it.each([undefined, '', 'false', '0', 'nonsense'])('ignores forwarding headers when TRUST_PROXY_HEADERS=%s', (v) => { + vi.stubEnv('TRUST_PROXY_HEADERS', v as string); + expect(ip(r(forged))).toBe('unknown'); + }); + + it('TRUST_PROXY_HEADERS=true uses the rightmost X-Forwarded-For entry (the one our proxy appended)', () => { + vi.stubEnv('TRUST_PROXY_HEADERS', 'true'); + expect(ip(r({ 'x-forwarded-for': '6.6.6.6, 203.0.113.7' }))).toBe('203.0.113.7'); + expect(ip(r({ 'x-forwarded-for': '203.0.113.7' }))).toBe('203.0.113.7'); + }); + + it('TRUST_PROXY_HEADERS=2 skips one more proxy hop', () => { + vi.stubEnv('TRUST_PROXY_HEADERS', '2'); + expect(ip(r({ 'x-forwarded-for': '6.6.6.6, 203.0.113.7, 10.0.0.2' }))).toBe('203.0.113.7'); + }); + + it('falls back to X-Real-IP from a trusted proxy that only sets that', () => { + vi.stubEnv('TRUST_PROXY_HEADERS', '1'); + expect(ip(r({ 'x-real-ip': '2001:db8::5' }))).toBe('2001:db8::5'); + }); + + it('TRUST_PROXY_HEADERS=cloudflare uses CF-Connecting-IP only', () => { + vi.stubEnv('TRUST_PROXY_HEADERS', 'cloudflare'); + expect(ip(r(forged))).toBe('8.8.8.8'); + expect(ip(r({ 'x-forwarded-for': '6.6.6.6' }))).toBe('unknown'); + }); + + it('rejects values that are not IP addresses even when trusted', () => { + vi.stubEnv('TRUST_PROXY_HEADERS', 'true'); + expect(ip(r({ 'x-forwarded-for': 'not-an-ip; DROP' }))).toBe('unknown'); + expect(ip(r({ 'x-forwarded-for': '203.0.113.7:51234' }))).toBe('203.0.113.7'); + }); +}); diff --git a/src/lib/client-ip.ts b/src/lib/client-ip.ts new file mode 100644 index 0000000..3bb4dcc --- /dev/null +++ b/src/lib/client-ip.ts @@ -0,0 +1,61 @@ +import { isIP } from 'node:net'; + +/** + * Client IP for rate limiting and audit logging. + * + * Threat model: app-router route handlers never see the socket address. + * `next start` / the standalone server only *fill in* `x-forwarded-for` from + * the socket when the request lacks one (`headers['x-forwarded-for'] ??= + * socket.remoteAddress` in next/dist/server/base-server.js); a value the + * client sends is passed through untouched. `x-real-ip` and + * `cf-connecting-ip` are never set by Next at all. So every one of these + * headers is attacker-controlled unless a reverse proxy we trust overwrites + * or appends to it — trusting them by default let anyone dodge per-IP rate + * limits (rotate a fake IP per request) and forge the audit-log IP. + * + * TRUST_PROXY_HEADERS (operator setting): + * unset / false → ignore forwarding headers; every client maps to + * 'unknown', so per-IP limits become one shared bucket per + * endpoint (fails closed rather than bypassable). + * true / 1 → one trusted proxy (e.g. the bundled nginx): use the + * RIGHTMOST x-forwarded-for entry — the address our proxy + * saw. Earlier entries are whatever the client sent. + * N (integer) → N trusted proxies in a chain: use the Nth entry from + * the right. + * cloudflare → use cf-connecting-ip (origin must only accept + * connections from Cloudflare). + * Only enable it when the app port is reachable solely through that proxy. + */ +export function trustedProxyHops(): number | 'cloudflare' { + const raw = (process.env.TRUST_PROXY_HEADERS || '').trim().toLowerCase(); + if (raw === 'cloudflare') return 'cloudflare'; + if (raw === 'true' || raw === 'yes') return 1; + if (/^\d+$/.test(raw)) return Math.min(Number(raw), 32); + return 0; +} + +function normalise(value: string | null | undefined): string | null { + if (!value) return null; + let ip = value.trim(); + // "[2001:db8::1]:443" / "203.0.113.7:51234" → bare address + const bracketed = ip.match(/^\[([^\]]+)\](?::\d+)?$/); + if (bracketed) ip = bracketed[1]; + else if (/^\d{1,3}(\.\d{1,3}){3}:\d+$/.test(ip)) ip = ip.slice(0, ip.lastIndexOf(':')); + return isIP(ip) ? ip : null; +} + +export function clientIp(req: Request): string { + const trust = trustedProxyHops(); + if (trust === 0) return 'unknown'; + const h = req.headers; + if (trust === 'cloudflare') return normalise(h.get('cf-connecting-ip')) || 'unknown'; + + const chain = (h.get('x-forwarded-for') || '').split(',').map(s => s.trim()).filter(Boolean); + if (chain.length > 0) { + // Fewer entries than trusted hops means the request skipped part of the + // chain; the leftmost entry is then the furthest address we have. + return normalise(chain[Math.max(0, chain.length - trust)]) || 'unknown'; + } + // A trusted proxy that only sets X-Real-IP (overwriting any client value). + return normalise(h.get('x-real-ip')) || 'unknown'; +} diff --git a/src/lib/guard.ts b/src/lib/guard.ts index af572f6..09c9239 100644 --- a/src/lib/guard.ts +++ b/src/lib/guard.ts @@ -1,16 +1,11 @@ import { NextResponse } from 'next/server'; import { limit, LIMITS } from './rateLimit'; import { audit } from './audit'; +import { clientIp } from './client-ip'; -export function clientIp(req: Request): string { - const h = req.headers; - return ( - h.get('x-forwarded-for')?.split(',')[0]?.trim() || - h.get('x-real-ip') || - h.get('cf-connecting-ip') || - 'unknown' - ); -} +// Forwarding headers are only honoured when TRUST_PROXY_HEADERS is set — see +// ./client-ip for the threat model. +export { clientIp }; /** * Rate-limit + audit guard for Node-runtime route handlers. diff --git a/src/lib/scanner-access.ts b/src/lib/scanner-access.ts new file mode 100644 index 0000000..6653eb5 --- /dev/null +++ b/src/lib/scanner-access.ts @@ -0,0 +1,97 @@ +import { createHash, timingSafeEqual } from 'node:crypto'; + +/** + * Who may drive the RECON scanner proxy (/api/scanner)? OWASP A01. + * + * The scanner makes *this server* probe arbitrary public hosts (ports, TLS, + * headers, whois, vuln fingerprinting). OSIRIS has no user accounts, so on a + * public deployment every anonymous visitor could otherwise use it as a scan + * relay that attributes the traffic to the operator's IP. + * + * Access is granted, in order, when: + * 1. SCANNER_ALLOW_ANONYMOUS=true — operator explicitly opts in to a public + * scanner (not recommended). + * 2. SCANNER_ACCESS_TOKEN is set and the request carries it in the + * X-Scanner-Token header (constant-time compare). A custom header cannot + * be attached cross-origin without a CORS preflight, so a third-party + * page cannot ride on a token holder's browser. + * 3. Local development: `next dev` (NODE_ENV=development — the documented + * `npm run osiris` flow) AND the request looks loopback-originated. + * Anything else is refused: 401 when a token would help, 403 when the + * operator has configured no way in for remote clients. + * + * Why rule 3 is limited to `next dev`: route handlers cannot see the socket + * address, and Next only fills in X-Forwarded-For when the client did not + * send one, so "is this request from loopback?" is answered purely from + * client-supplied headers. The Host / X-Forwarded-For / Sec-Fetch-Site checks + * stop browser-borne abuse (DNS rebinding, a LAN visitor's browser, a + * cross-site page firing requests at localhost) but not a deliberate non- + * browser client on the same network that forges them. That is acceptable + * only for the dev server, which must never be exposed publicly anyway; + * production builds (`next start`, Docker, standalone) always need rule 1 or 2. + */ + +export const SCANNER_TOKEN_HEADER = 'x-scanner-token'; + +export type ScannerAccess = + | { ok: true; via: 'anonymous' | 'token' | 'local-dev' } + | { ok: false; status: 401 | 403; body: { error: string; detail: string; auth?: 'token' } }; + +function sha256(s: string): Buffer { + return createHash('sha256').update(s, 'utf8').digest(); +} + +/** Constant-time string compare (hashing first equalises lengths). */ +export function tokensMatch(given: string, expected: string): boolean { + return timingSafeEqual(sha256(given), sha256(expected)); +} + +const LOOPBACK_HOST = /^(localhost|127(?:\.\d{1,3}){3}|\[::1\])(?::\d+)?$/i; +const LOOPBACK_IP = /^(127(?:\.\d{1,3}){3}|::1|::ffff:127(?:\.\d{1,3}){3})$/i; + +export function looksLikeLocalDevRequest(req: Request): boolean { + if (process.env.NODE_ENV !== 'development') return false; + const h = req.headers; + if (!LOOPBACK_HOST.test(h.get('host') || '')) return false; + // Next fills X-Forwarded-For from the socket when absent; anything other + // than a single loopback address means a proxy (or a forger) is involved. + const xff = h.get('x-forwarded-for'); + if (xff !== null && !LOOPBACK_IP.test(xff.trim())) return false; + if (h.get('x-real-ip') !== null || h.get('cf-connecting-ip') !== null || h.get('forwarded') !== null) return false; + // Browsers send Sec-Fetch-Site; refuse requests initiated by another site. + const site = h.get('sec-fetch-site'); + if (site !== null && site !== 'same-origin' && site !== 'none') return false; + return true; +} + +export function checkScannerAccess(req: Request): ScannerAccess { + if ((process.env.SCANNER_ALLOW_ANONYMOUS || '').trim().toLowerCase() === 'true') { + return { ok: true, via: 'anonymous' }; + } + + const expected = process.env.SCANNER_ACCESS_TOKEN || ''; + const given = req.headers.get(SCANNER_TOKEN_HEADER) || ''; + if (expected && given && tokensMatch(given, expected)) return { ok: true, via: 'token' }; + + if (looksLikeLocalDevRequest(req)) return { ok: true, via: 'local-dev' }; + + if (expected) { + return { + ok: false, + status: 401, + body: { + error: given ? 'Invalid scanner access token' : 'Scanner access token required', + detail: 'Send the operator-issued SCANNER_ACCESS_TOKEN in the X-Scanner-Token header.', + auth: 'token', + }, + }; + } + return { + ok: false, + status: 403, + body: { + error: 'Scanner disabled for remote clients', + detail: 'The operator must set SCANNER_ACCESS_TOKEN (or SCANNER_ALLOW_ANONYMOUS=true) to enable RECON scans on this host.', + }, + }; +} diff --git a/src/lib/ssrf-guard.ts b/src/lib/ssrf-guard.ts index e85b8de..1fd23c5 100644 --- a/src/lib/ssrf-guard.ts +++ b/src/lib/ssrf-guard.ts @@ -232,7 +232,6 @@ export function isRateLimited(ip: string, limit: number = 20, windowMs: number = return entry.count > limit; } -export function getClientIp(req: Request): string { - const forwarded = req.headers.get('x-forwarded-for'); - return forwarded?.split(',')[0]?.trim() || req.headers.get('x-real-ip') || 'unknown'; -} +// Forwarding headers are only honoured when TRUST_PROXY_HEADERS is set — see +// ./client-ip for the threat model. +export { clientIp as getClientIp } from './client-ip';