Elffuss BraidHub

kikocis/osiris public

master · 9.1 KiBRawPermalink
1import { lookup } from 'node:dns/promises';
2import { isIP } from 'node:net';
3
4/**
5 * SSRF guard shared by route handlers that take a user-controlled host / IP
6 * and turn it into a network request.
7 *
8 * Defense is two-layered:
9 * 1. Canonicalise the input. Reject non-dotted-quad IPv4 forms and any
10 * IPv6 address that falls inside a reserved range.
11 * 2. For hostnames, resolve A + AAAA records and reject if *any* answer
12 * lands in a reserved range. Total Time-Of-Check / Time-Of-Use defence
13 * requires IP pinning at the socket layer, but rejecting at lookup time
14 * blocks every non-rebinding attack and forces a rebinder to win a
15 * TTL=0 race against the downstream consumer.
16 */
17
18const IPV4_BLOCKS_TEXT: Array<[string, number]> = [
19 ['0.0.0.0', 8], // "this" network
20 ['10.0.0.0', 8], // RFC1918
21 ['100.64.0.0', 10], // CGNAT / Tailscale
22 ['127.0.0.0', 8], // loopback
23 ['169.254.0.0', 16], // link-local (incl. cloud metadata 169.254.169.254)
24 ['172.16.0.0', 12], // RFC1918
25 ['192.0.0.0', 24], // IETF protocol assignments
26 ['192.0.2.0', 24], // TEST-NET-1
27 ['192.168.0.0', 16], // RFC1918
28 ['198.18.0.0', 15], // benchmarking
29 ['198.51.100.0', 24], // TEST-NET-2
30 ['203.0.113.0', 24], // TEST-NET-3
31 ['224.0.0.0', 4], // multicast
32 ['240.0.0.0', 4], // reserved (incl. 255.255.255.255 broadcast)
33];
34
35const IPV6_BLOCK_PREFIXES = [
36 '::', // unspecified
37 '::1', // loopback
38 '::ffff:', // IPv4-mapped (covers ::ffff:127.0.0.1, ::ffff:10.x, etc.)
39 '64:ff9b::', // NAT64
40 '64:ff9b:1:', // local NAT64
41 '100::', // discard prefix
42 '2001:db8:', // documentation
43 'fc', // unique-local (fc00::/7) — any addr starting with fc/fd
44 'fd',
45 'fe8', 'fe9', 'fea', 'feb', // link-local fe80::/10
46 'fec', 'fed', 'fee', 'fef', // site-local fec0::/10 (deprecated but still routable to internal hosts on some stacks)
47 'ff', // multicast ff00::/8
48];
49
50function ipv4ToInt(ip: string): number {
51 const parts = ip.split('.').map(Number);
52 // Build the 32-bit value via multiplication so the intermediate stays a
53 // safe positive integer; bitwise OR would coerce to a signed int32.
54 return parts[0] * 0x1000000 + parts[1] * 0x10000 + parts[2] * 0x100 + parts[3];
55}
56
57function ipv4InBlocked(ip: string): boolean {
58 const ipInt = ipv4ToInt(ip);
59 for (const [net, bits] of IPV4_BLOCKS_TEXT) {
60 const netInt = ipv4ToInt(net);
61 // 2^(32-bits) is the size of the block; the "network address" must match
62 // after stripping the host bits.
63 const blockSize = bits === 0 ? 0x100000000 : Math.pow(2, 32 - bits);
64 if (Math.floor(ipInt / blockSize) === Math.floor(netInt / blockSize)) return true;
65 }
66 return false;
67}
68
69function ipv6InBlocked(ip: string): boolean {
70 const lower = ip.toLowerCase().replace(/^\[/, '').replace(/\]$/, '');
71 // Exact-match singletons first
72 if (lower === '::' || lower === '::1') return true;
73 for (const prefix of IPV6_BLOCK_PREFIXES) {
74 if (lower.startsWith(prefix)) return true;
75 }
76 return false;
77}
78
79/**
80 * Returns the canonical dotted-quad form if `s` looks like an IPv4 address in
81 * any common notation (dotted-quad, dotted-octal, dotted-hex, decimal, hex
82 * single-int), otherwise null. Non-canonical forms (e.g. `2130706433`,
83 * `0177.0.0.1`, `0x7f.0.0.1`) get rejected at the parse step so callers can
84 * decline them rather than try to figure out what the kernel will resolve.
85 */
86export function parseIPv4(s: string): string | null {
87 // Strict dotted-quad first — fast path
88 if (/^(\d{1,3}\.){3}\d{1,3}$/.test(s)) {
89 const parts = s.split('.').map(Number);
90 if (parts.some(p => p < 0 || p > 255)) return null;
91 return parts.join('.');
92 }
93 // Non-canonical forms (decimal, hex, octal, short notation) — reject. The
94 // call sites here only ever want canonical dotted-quad; anything else is
95 // either an attacker probe or a bug upstream.
96 if (/^\d+$/.test(s)) return null;
97 if (/^0x[0-9a-fA-F]+$/.test(s)) return null;
98 if (/^(\d+\.){0,3}\d+$/.test(s) && s.includes('.')) {
99 // Mixed forms — explicitly reject rather than coerce
100 return null;
101 }
102 return null;
103}
104
105export interface ValidationResult {
106 ok: boolean;
107 reason?: string;
108 /** Resolved IPs (literal input or DNS answers). Empty if validation failed before resolution. */
109 resolved?: string[];
110}
111
112/**
113 * Validate that `host` (either an IP literal or a hostname) is safe to use as
114 * a network target. Returns ok=false when the literal IP is in a blocked
115 * range, the IP literal uses a non-canonical form, or any resolved A/AAAA
116 * answer lands in a blocked range.
117 */
118export async function validateHost(host: string): Promise<ValidationResult> {
119 const trimmed = host.trim();
120 if (!trimmed) return { ok: false, reason: 'empty host' };
121
122 // Strip brackets for IPv6 literals like [::1]
123 const bracketed = trimmed.replace(/^\[|\]$/g, '');
124
125 // Reject obvious metadata-style hostnames before they ever hit DNS. These
126 // are independent of which IP they resolve to; the names alone are not
127 // legitimate scan / probe targets.
128 const lowerHost = trimmed.toLowerCase();
129 const NAME_BLOCKLIST = [
130 /^localhost$/i,
131 /\.localhost$/i,
132 /^host\.docker\.internal$/i,
133 /\.local$/i,
134 /\.internal$/i,
135 /^metadata\.google\.internal$/i,
136 ];
137 if (NAME_BLOCKLIST.some(re => re.test(lowerHost))) {
138 return { ok: false, reason: 'hostname matches reserved name pattern' };
139 }
140
141 // Literal IP path
142 const ipFamily = isIP(bracketed);
143 if (ipFamily === 4) {
144 const canonical = parseIPv4(bracketed);
145 if (!canonical) return { ok: false, reason: 'non-canonical IPv4 form rejected' };
146 if (ipv4InBlocked(canonical)) return { ok: false, reason: 'IPv4 in reserved range' };
147 return { ok: true, resolved: [canonical] };
148 }
149 if (ipFamily === 6) {
150 if (ipv6InBlocked(bracketed)) return { ok: false, reason: 'IPv6 in reserved range' };
151 return { ok: true, resolved: [bracketed] };
152 }
153
154 // Hostname — basic syntax check then resolve and re-check
155 if (!/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/.test(trimmed)) {
156 return { ok: false, reason: 'invalid hostname syntax' };
157 }
158
159 let answers: Array<{ address: string; family: number }> = [];
160 try {
161 answers = await lookup(trimmed, { all: true });
162 } catch (err) {
163 return { ok: false, reason: `DNS lookup failed: ${(err as Error).message}` };
164 }
165 if (answers.length === 0) {
166 return { ok: false, reason: 'hostname has no A/AAAA records' };
167 }
168 for (const a of answers) {
169 if (a.family === 4) {
170 if (ipv4InBlocked(a.address)) return { ok: false, reason: `hostname resolves to reserved IPv4 ${a.address}` };
171 } else if (a.family === 6) {
172 if (ipv6InBlocked(a.address)) return { ok: false, reason: `hostname resolves to reserved IPv6 ${a.address}` };
173 }
174 }
175 return { ok: true, resolved: answers.map(a => a.address) };
176}
177
178/**
179 * Wrap a fetch call so that:
180 * - the URL's host is validated before the request (block private targets)
181 * - redirects are followed manually, with each hop re-validated (block a
182 * redirect to a private host from a public-looking original)
183 */
184export async function safeFetch(
185 inputUrl: string,
186 init: RequestInit & { maxRedirects?: number } = {},
187): Promise<Response> {
188 const maxRedirects = init.maxRedirects ?? 3;
189 // Spread into a new init we mutate, then explicitly drop our extra prop
190 // so it isn't passed through to fetch().
191 const passInit: RequestInit & { maxRedirects?: number } = { ...init };
192 delete passInit.maxRedirects;
193 let currentUrl = inputUrl;
194 for (let i = 0; i <= maxRedirects; i++) {
195 let parsed: URL;
196 try { parsed = new URL(currentUrl); } catch { throw new Error('safeFetch: invalid URL'); }
197 if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
198 throw new Error(`safeFetch: blocked protocol ${parsed.protocol}`);
199 }
200 const check = await validateHost(parsed.hostname);
201 if (!check.ok) {
202 throw new Error(`safeFetch: blocked target — ${check.reason}`);
203 }
204 const res = await fetch(currentUrl, { ...passInit, redirect: 'manual' });
205 if (res.status >= 300 && res.status < 400) {
206 const loc = res.headers.get('location');
207 if (!loc) return res;
208 const nextUrl = new URL(loc, currentUrl).toString();
209 currentUrl = nextUrl;
210 continue;
211 }
212 return res;
213 }
214 throw new Error('safeFetch: too many redirects');
215}
216
217// ── SHARED RATE LIMITER ──
218// In-memory rate limiting per-isolate for basic proxy abuse prevention
219const rateMap = new Map<string, { count: number; resetAt: number }>();
220
221export function isRateLimited(ip: string, limit: number = 20, windowMs: number = 60_000): boolean {
222 const now = Date.now();
223 for (const [key, entry] of rateMap) {
224 if (now > entry.resetAt) rateMap.delete(key);
225 }
226 const entry = rateMap.get(ip);
227 if (!entry || now > entry.resetAt) {
228 rateMap.set(ip, { count: 1, resetAt: now + windowMs });
229 return false;
230 }
231 entry.count++;
232 return entry.count > limit;
233}
234
235export function getClientIp(req: Request): string {
236 const forwarded = req.headers.get('x-forwarded-for');
237 return forwarded?.split(',')[0]?.trim() || req.headers.get('x-real-ip') || 'unknown';
238}