Repository navigation
Expand file tree
/
Copy pathsecurity.js
More file actions
1409 lines (1273 loc) · 51.5 KB
/
Copy pathsecurity.js
File metadata and controls
1409 lines (1273 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @module security
* @description DNS-rebinding-safe SSRF outbound URL validator & `safeFetch` client plus
* bounded-memory fixed-window HTTP/Edge rate limiter (`INV-LEGO-13`, `INV-LEGO-01`, `INV-LEGO-03`).
*/
import net from 'node:net';
import dns from 'node:dns';
import { okEnvelope, errorEnvelope } from './http.js';
import { edgeErrorResponse } from './edge.js';
let UndiciAgent = null;
let undiciFetch = null;
try {
const undiciMod = await import('undici');
UndiciAgent = undiciMod.Agent ?? null;
undiciFetch = undiciMod.fetch ?? null;
} catch {
UndiciAgent = null;
undiciFetch = null;
}
const NATIVE_GLOBAL_FETCH = globalThis.fetch;
const CANONICAL_IPV4_RE =
/^(?:0|[1-9]\d{0,2})\.(?:0|[1-9]\d{0,2})\.(?:0|[1-9]\d{0,2})\.(?:0|[1-9]\d{0,2})$/;
const HEX_GROUP_RE = /^[0-9a-fA-F]{1,4}$/;
const PURE_DIGITS_RE = /^\d+$/;
const PURE_HEX_RE = /^0x[0-9a-f]+$/i;
const REDIRECT_STATUS_CODES = new Set([301, 302, 303, 307, 308]);
const FORBIDDEN_HEADER_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const CROSS_ORIGIN_SENSITIVE_HEADERS = new Set([
'authorization',
'cookie',
'cookie2',
'proxy-authorization',
]);
const BODY_SPECIFIC_HEADERS = new Set([
'content-encoding',
'content-language',
'content-length',
'content-location',
'content-type',
'transfer-encoding',
]);
/** @type {Map<string, any>} */
const CACHED_SSRF_AGENTS = new Map();
/**
* Parse a strict canonical dotted-decimal IPv4 string into four `0..255` octets, or `null` if non-canonical.
*
* @param {string} candidate - Candidate IPv4 string
* @returns {[number, number, number, number] | null}
*/
function parseCanonicalIpv4(candidate) {
if (!CANONICAL_IPV4_RE.test(candidate)) return null;
const parts = candidate.split('.');
const a = Number(parts[0]);
const b = Number(parts[1]);
const c = Number(parts[2]);
const d = Number(parts[3]);
if (a > 255 || b > 255 || c > 255 || d > 255) return null;
return [a, b, c, d];
}
/**
* Expand a valid IPv6 string (already verified via `net.isIP(addr) === 6`) into 8 16-bit hextets.
* Returns `null` on any malformed representation so callers fail closed.
*
* @param {string} ipv6 - Raw IPv6 address without brackets or `%zone`
* @returns {number[] | null}
*/
function parseIpv6Hextets(ipv6) {
let normalized = ipv6;
if (normalized.includes('.')) {
const lastColon = normalized.lastIndexOf(':');
if (lastColon === -1) return null;
const ipv4Octets = parseCanonicalIpv4(normalized.slice(lastColon + 1));
if (!ipv4Octets) return null;
const hiHex = ((ipv4Octets[0] << 8) | ipv4Octets[1]).toString(16);
const loHex = ((ipv4Octets[2] << 8) | ipv4Octets[3]).toString(16);
normalized = `${normalized.slice(0, lastColon + 1)}${hiHex}:${loHex}`;
}
const doubleColonParts = normalized.split('::');
if (doubleColonParts.length > 2) return null;
let groups;
if (doubleColonParts.length === 2) {
const left = doubleColonParts[0] ? doubleColonParts[0].split(':') : [];
const right = doubleColonParts[1] ? doubleColonParts[1].split(':') : [];
const missing = 8 - (left.length + right.length);
if (missing < 1) return null;
groups = [...left, ...new Array(missing).fill('0'), ...right];
} else {
groups = normalized.split(':');
if (groups.length !== 8) return null;
}
if (groups.length !== 8) return null;
const hextets = new Array(8);
for (let i = 0; i < 8; i += 1) {
const group = groups[i];
if (!HEX_GROUP_RE.test(group)) return null;
const parsed = Number.parseInt(group, 16);
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 0xffff) return null;
hextets[i] = parsed;
}
return hextets;
}
/**
* Fail-closed classifier for private, loopback, link-local, cloud metadata, CGNAT/Tailscale,
* multicast, documentation, benchmarking, IPv4-mapped/compatible/6to4/Teredo/NAT64 IPv6, and
* non-canonical IP literals (`INV-LEGO-13`).
*
* @param {string} [ipString=''] - Candidate IPv4 or IPv6 literal
* @param {object} [options={}] - Policy overrides
* @param {boolean} [options.allowPrivateLan=false] - Allow RFC1918 (`10/8`, `172.16/12`, `192.168/16`) and IPv6 ULA (`fc00::/7`)
* @param {boolean} [options.allowTailscale=false] - Allow Tailscale CGNAT (`100.64.0.0/10`)
* @returns {boolean} `true` if private, reserved, or malformed (blocked); `false` if globally routable/permitted
*/
export function isPrivateOrReservedIp(ipString = '', options = {}) {
if (typeof ipString !== 'string') return true;
const trimmed = ipString.trim();
if (!trimmed || trimmed.includes('%')) return true;
let clean = trimmed;
if (clean.startsWith('[') || clean.endsWith(']')) {
if (!clean.startsWith('[') || !clean.endsWith(']')) return true;
clean = clean.slice(1, -1);
}
if (!clean || clean.includes('%')) return true;
const opts = options && typeof options === 'object' ? options : {};
const allowPrivateLan = opts.allowPrivateLan === true;
const allowTailscale = opts.allowTailscale === true;
const ipv4 = parseCanonicalIpv4(clean);
if (ipv4 !== null) {
const [a, b, c] = ipv4;
// 0.0.0.0/8 ("This network") & 127.0.0.0/8 (Loopback)
if (a === 0 || a === 127) return true;
// 169.254.0.0/16 (Link-local & AWS/GCP/Azure Cloud Metadata 169.254.169.254 — ALWAYS blocked)
if (a === 169 && b === 254) return true;
// 100.64.0.0/10 (RFC 6598 Shared CGNAT / Tailscale)
if (a === 100 && b >= 64 && b <= 127) {
return !allowTailscale;
}
// RFC 1918 Private LAN (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
if (
a === 10 ||
(a === 172 && b >= 16 && b <= 31) ||
(a === 192 && b === 168)
) {
return !allowPrivateLan;
}
// 192.0.0.0/24 (IETF Protocol Assignments) & 192.0.2.0/24 (TEST-NET-1)
if (a === 192 && b === 0 && (c === 0 || c === 2)) return true;
// 198.18.0.0/15 (Benchmarking)
if (a === 198 && (b === 18 || b === 19)) return true;
// 198.51.100.0/24 (TEST-NET-2)
if (a === 198 && b === 51 && c === 100) return true;
// 203.0.113.0/24 (TEST-NET-3)
if (a === 203 && b === 0 && c === 113) return true;
// 224.0.0.0/4 (Multicast) + 240.0.0.0/4 (Reserved) + 255.255.255.255 (Broadcast)
if (a >= 224) return true;
return false;
}
if (net.isIP(clean) === 6) {
const h = parseIpv6Hextets(clean);
if (!h) return true;
const zero0To4 = h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0;
// Unspecified (::), Loopback (::1), and deprecated IPv4-compatible IPv6 (::/96) — ALWAYS blocked
if (zero0To4 && h[5] === 0) {
return true;
}
// IPv4-mapped IPv6 (::ffff:0:0/96) & SIIT IPv4-translated IPv6 (::ffff:0:0:0/96) — ALWAYS blocked
if (
(zero0To4 && h[5] === 0xffff) ||
(h[0] === 0 && h[1] === 0 && h[2] === 0 && h[3] === 0 && h[4] === 0xffff && h[5] === 0)
) {
return true;
}
// NAT64 well-known (64:ff9b::/96) and local-use (64:ff9b:1::/48) — ALWAYS blocked
if (
h[0] === 0x0064 &&
h[1] === 0xff9b &&
((h[2] === 0 && h[3] === 0 && h[4] === 0 && h[5] === 0) || h[2] === 0x0001)
) {
return true;
}
// Discard-Only Prefix (100::/64, RFC 6666) — ALWAYS blocked
if (h[0] === 0x0100 && h[1] === 0 && h[2] === 0 && h[3] === 0) {
return true;
}
// 6to4 (2002::/16) — ALWAYS blocked per INV-LEGO-13
if (h[0] === 0x2002) {
return true;
}
// IETF Protocol Assignments (2001::/23: Teredo 2001:0000::/32, Benchmarking 2001:2::/48, ORCHID/v2 2001:10::/28, 2001:20::/28) & Documentation (2001:db8::/32, 3fff::/20)
if (h[0] === 0x2001 && (h[1] <= 0x01ff || h[1] === 0x0db8)) {
return true;
}
if (h[0] === 0x3fff && (h[1] & 0xf000) === 0x0000) {
return true;
}
// Link-local (fe80::/10), deprecated Site-local (fec0::/10), and Multicast (ff00::/8)
if ((h[0] & 0xffc0) === 0xfe80 || (h[0] & 0xffc0) === 0xfec0 || (h[0] & 0xff00) === 0xff00) {
return true;
}
// Unique Local Addresses (fc00::/7), unconditionally blocking AWS EC2 IPv6 IMDS (fd00:ec2::254)
if ((h[0] & 0xfe00) === 0xfc00) {
if (
h[0] === 0xfd00 &&
h[1] === 0x0ec2 &&
h[2] === 0 &&
h[3] === 0 &&
h[4] === 0 &&
h[5] === 0 &&
h[6] === 0 &&
h[7] === 0x0254
) {
return true;
}
return !allowPrivateLan;
}
// Only IANA Global Unicast (2000::/3) is globally routable; all other IETF reserved prefixes fail closed
return (h[0] & 0xe000) !== 0x2000;
}
// Any non-canonical IPv4 (octal, hex, shorthand, single-integer) or non-IP string fails closed
return true;
}
/**
* Extract the un-canonicalized host token from a raw URL string prior to WHATWG `new URL()` rewriting.
*
* @param {string} urlStr - Raw URL string
* @returns {string}
*/
function extractRawAuthorityHost(urlStr) {
const match = /^[a-zA-Z][a-zA-Z0-9+.-]*:[\/\\]{2}([^\/\\?#]*)/.exec(urlStr);
if (!match) return '';
let authority = match[1];
const atIdx = authority.lastIndexOf('@');
if (atIdx !== -1) {
authority = authority.slice(atIdx + 1);
}
if (authority.startsWith('[')) {
const closeIdx = authority.indexOf(']');
return closeIdx !== -1 ? authority.slice(1, closeIdx) : authority;
}
const colonIdx = authority.indexOf(':');
const hostPart = colonIdx !== -1 ? authority.slice(0, colonIdx) : authority;
try {
return decodeURIComponent(hostPart);
} catch {
return hostPart;
}
}
/**
* Detect non-canonical numeric/hex/octal IP obfuscation hostnames (e.g. `2130706433`, `0x7f000001`,
* `0177.0.0.1`, `127.1`) before DNS resolution.
*
* @param {string} candidate - Lowercased or raw non-IPv6 hostname
* @returns {boolean}
*/
function isSuspiciousNumericHost(candidate) {
if (!candidate || candidate.includes(':')) return false;
const stripped = candidate.trim().toLowerCase().replace(/\.+$/, '');
if (!stripped) return false;
if (parseCanonicalIpv4(stripped) !== null) return false;
if (PURE_DIGITS_RE.test(stripped) || PURE_HEX_RE.test(stripped)) return true;
const segments = stripped.split('.');
if (
segments.length >= 2 &&
segments.every((seg) => seg.length > 0 && (PURE_DIGITS_RE.test(seg) || PURE_HEX_RE.test(seg)))
) {
return true;
}
return false;
}
/**
* Normalize `dns.lookup` / custom `lookupFn` outputs into `{ address, family }[]`.
*
* @param {unknown} rawResult - Lookup output
* @returns {Array<{ address: string, family: number }>}
*/
function normalizeLookupResult(rawResult) {
if (rawResult === null || rawResult === undefined) return [];
const list = Array.isArray(rawResult) ? rawResult : [rawResult];
const entries = [];
for (const item of list) {
if (typeof item === 'string') {
const addr = item.trim();
entries.push({ address: addr, family: net.isIP(addr) || 4 });
} else if (item && typeof item === 'object') {
const addr = typeof item.address === 'string' ? item.address.trim() : '';
const fam = Number.isInteger(item.family) ? item.family : net.isIP(addr) || 4;
entries.push({ address: addr, family: fam });
} else {
entries.push({ address: '', family: 0 });
}
}
return entries;
}
/**
* Validate an outbound URL against SSRF protocol, credential, allowlist, reserved-hostname,
* IP-obfuscation, and multi-record DNS rules (`INV-LEGO-13`, `INV-LEGO-01`).
* Never throws; always resolves to an `okEnvelope` or `errorEnvelope`.
*
* @param {string|URL} rawUrl - Outbound target URL
* @param {object} [options={}] - Validation options
* @param {string[]} [options.allowedProtocols=['https:', 'http:']] - Allowed URL schemes
* @param {boolean} [options.allowPrivateLan=false] - Allow RFC1918 / ULA / `.local` targets
* @param {boolean} [options.allowTailscale=false] - Allow Tailscale `100.64.0.0/10` targets
* @param {string[]|Set<string>|null} [options.allowedHosts=null] - Optional exact host allowlist
* @param {Function|null} [options.lookupFn=null] - Optional async DNS resolver override `(hostname) => Promise<...>`
* @param {string} [options.tool='security.ssrf'] - Originating tool identifier
* @returns {Promise<{ ok: boolean, tool: string, summary: string, data?: { url: string, hostname: string, port: string, resolvedAddresses: string[] }, error?: { code: string, message: string, details?: unknown } }>}
*/
export async function validateOutboundUrl(rawUrl, options = {}) {
const opts = options && typeof options === 'object' ? options : {};
const safeTool =
typeof opts.tool === 'string' && opts.tool.trim().length > 0
? opts.tool.trim()
: 'security.ssrf';
const allowedProtocols = opts.allowedProtocols ?? ['https:', 'http:'];
const allowPrivateLan = opts.allowPrivateLan === true;
const allowTailscale = opts.allowTailscale === true;
const allowedHosts = opts.allowedHosts ?? null;
const lookupFn = typeof opts.lookupFn === 'function' ? opts.lookupFn : null;
try {
if (typeof rawUrl !== 'string' && !(rawUrl instanceof URL)) {
return errorEnvelope('SSRF_INVALID_URL', 'Outbound URL must be a non-empty string', null, safeTool);
}
const urlStr = String(rawUrl).trim();
if (!urlStr || /[\r\n\0]/.test(urlStr)) {
return errorEnvelope('SSRF_INVALID_URL', 'Malformed or empty outbound URL', null, safeTool);
}
let parsed;
try {
parsed = new URL(urlStr);
} catch {
return errorEnvelope('SSRF_INVALID_URL', 'Invalid URL syntax', { url: urlStr }, safeTool);
}
const normalizedProtocols = Array.isArray(allowedProtocols)
? allowedProtocols
.filter((p) => typeof p === 'string' && p.trim().length > 0)
.map((p) => {
const lower = p.trim().toLowerCase();
return lower.endsWith(':') ? lower : `${lower}:`;
})
: [];
if (!normalizedProtocols.includes(parsed.protocol.toLowerCase())) {
return errorEnvelope(
'SSRF_BLOCKED_PROTOCOL',
`Outbound protocol "${parsed.protocol}" is not permitted`,
{ protocol: parsed.protocol },
safeTool
);
}
if (
parsed.username ||
parsed.password ||
/^[a-zA-Z][a-zA-Z0-9+.-]*:[\/\\]{2}[^\/\\?#]*@/.test(urlStr)
) {
return errorEnvelope(
'SSRF_CREDENTIALS_FORBIDDEN',
'Embedded URL credentials (username/password) are forbidden',
null,
safeTool
);
}
const rawAuthorityHost = extractRawAuthorityHost(urlStr);
const bracketStrippedHost = parsed.hostname.replace(/^\[|\]$/g, '').toLowerCase();
const hostname = bracketStrippedHost.replace(/\.+$/, '');
if (!hostname || hostname.startsWith('.') || hostname.includes('..')) {
return errorEnvelope('SSRF_INVALID_URL', 'Outbound URL hostname is invalid', { hostname }, safeTool);
}
if (allowedHosts !== null && allowedHosts !== undefined) {
if (!Array.isArray(allowedHosts) && !(allowedHosts instanceof Set)) {
return errorEnvelope(
'SSRF_HOST_NOT_ALLOWED',
'Invalid allowedHosts allowlist configuration',
{ hostname },
safeTool
);
}
const allowedSet = new Set();
for (const entry of allowedHosts) {
if (typeof entry === 'string' && entry.trim().length > 0) {
allowedSet.add(entry.trim().replace(/^\[|\]$/g, '').toLowerCase().replace(/\.+$/, ''));
}
}
if (!allowedSet.has(hostname)) {
return errorEnvelope(
'SSRF_HOST_NOT_ALLOWED',
`Outbound host "${hostname}" is not in allowedHosts`,
{ hostname },
safeTool
);
}
}
// Cloud metadata hostnames are ALWAYS forbidden, even when allowPrivateLan === true
if (
hostname === 'metadata.google.internal' ||
hostname.endsWith('.metadata.google.internal') ||
hostname === 'metadata.goog'
) {
return errorEnvelope(
'SSRF_PRIVATE_IP',
`Outbound access to cloud metadata host "${hostname}" is forbidden`,
{ hostname },
safeTool
);
}
// Localhost / mDNS / generic metadata hostnames are blocked unless allowPrivateLan === true
if (
!allowPrivateLan &&
(hostname === 'localhost' ||
hostname.endsWith('.localhost') ||
hostname.endsWith('.local') ||
hostname === 'metadata' ||
hostname === 'instance-data')
) {
return errorEnvelope(
'SSRF_PRIVATE_IP',
`Outbound access to reserved host "${hostname}" is forbidden`,
{ hostname },
safeTool
);
}
// Reject octal, hex, shorthand, or single-integer IP obfuscation before DNS resolution
if (isSuspiciousNumericHost(rawAuthorityHost) || isSuspiciousNumericHost(hostname)) {
return errorEnvelope(
'SSRF_PRIVATE_IP',
`Non-canonical numeric/hex/octal IP hostname "${rawAuthorityHost || hostname}" is forbidden`,
{ hostname: rawAuthorityHost || hostname },
safeTool
);
}
if (bracketStrippedHost.includes('%') || rawAuthorityHost.includes('%')) {
return errorEnvelope(
'SSRF_PRIVATE_IP',
'IPv6 zone indices are forbidden in outbound URLs',
{ hostname },
safeTool
);
}
const defaultPort =
parsed.protocol === 'https:' ? '443' : parsed.protocol === 'http:' ? '80' : '';
const port = parsed.port || defaultPort;
const ipPolicy = { allowPrivateLan, allowTailscale };
if (net.isIP(hostname) !== 0) {
if (isPrivateOrReservedIp(hostname, ipPolicy)) {
return errorEnvelope(
'SSRF_PRIVATE_IP',
`Outbound IP "${hostname}" is private or reserved`,
{ hostname, blockedAddress: hostname },
safeTool
);
}
return okEnvelope(safeTool, 'Outbound URL validated', {
url: parsed.toString(),
hostname,
port,
resolvedAddresses: [hostname],
});
}
const resolveHost =
lookupFn || ((host) => dns.promises.lookup(host, { all: true, verbatim: true }));
let rawResolved;
try {
rawResolved = await resolveHost(hostname);
} catch (err) {
return errorEnvelope(
'SSRF_DNS_FAILED',
`DNS resolution failed for "${hostname}": ${err?.message || 'lookup error'}`,
{ hostname },
safeTool
);
}
const entries = normalizeLookupResult(rawResolved);
if (entries.length === 0) {
return errorEnvelope(
'SSRF_DNS_FAILED',
`DNS resolution returned zero addresses for "${hostname}"`,
{ hostname },
safeTool
);
}
const resolvedAddresses = [];
for (const entry of entries) {
if (isPrivateOrReservedIp(entry.address, ipPolicy)) {
return errorEnvelope(
'SSRF_PRIVATE_IP',
`Host "${hostname}" resolved to private or reserved IP "${entry.address}"`,
{ hostname, blockedAddress: entry.address },
safeTool
);
}
resolvedAddresses.push(entry.address);
}
return okEnvelope(safeTool, 'Outbound URL validated', {
url: parsed.toString(),
hostname,
port,
resolvedAddresses,
});
} catch (err) {
return errorEnvelope(
'SSRF_INVALID_URL',
err?.message || 'Failed to validate outbound URL',
null,
safeTool
);
}
}
/**
* Build a socket-connect `lookup` callback enforcing `isPrivateOrReservedIp` right at TCP/TLS connect time
* so TOCTOU DNS rebinding between `validateOutboundUrl` and `fetch` cannot reach internal IPs.
*
* @param {object} params - Lookup policy
* @param {boolean} params.allowPrivateLan - Allow RFC1918/ULA
* @param {boolean} params.allowTailscale - Allow Tailscale CGNAT
* @param {Function|null} params.lookupFn - Optional injected async resolver
* @returns {(hostname: string, opts: any, cb: Function) => void}
*/
function createSsrfConnectLookup({ allowPrivateLan, allowTailscale, lookupFn }) {
const ipPolicy = { allowPrivateLan, allowTailscale };
const resolveHost =
lookupFn || ((host) => dns.promises.lookup(host, { all: true, verbatim: true }));
return (rawHostname, lookupOpts, callback) => {
const cb = typeof lookupOpts === 'function' ? lookupOpts : callback;
const opts = typeof lookupOpts === 'object' && lookupOpts !== null ? lookupOpts : {};
const cleanHost = String(rawHostname || '')
.trim()
.replace(/^\[|\]$/g, '')
.toLowerCase()
.replace(/\.+$/, '');
const failSsrf = (blockedAddress, message) => {
const err = new Error(message);
err.code = 'SSRF_PRIVATE_IP';
err.hostname = cleanHost;
err.blockedAddress = blockedAddress;
cb(err);
};
if (
!cleanHost ||
cleanHost === 'metadata.google.internal' ||
cleanHost.endsWith('.metadata.google.internal') ||
cleanHost === 'metadata.goog'
) {
failSsrf(cleanHost, `Outbound connect to cloud metadata host "${cleanHost}" is forbidden`);
return;
}
if (net.isIP(cleanHost) !== 0) {
if (isPrivateOrReservedIp(cleanHost, ipPolicy)) {
failSsrf(cleanHost, `Outbound connect to private or reserved IP "${cleanHost}" is forbidden`);
return;
}
const family = net.isIP(cleanHost);
if (opts.all) {
cb(null, [{ address: cleanHost, family }]);
} else {
cb(null, cleanHost, family);
}
return;
}
Promise.resolve()
.then(() => resolveHost(cleanHost))
.then((rawResolved) => {
const entries = normalizeLookupResult(rawResolved);
if (entries.length === 0) {
const dnsErr = new Error(`DNS resolution returned zero addresses for "${cleanHost}"`);
dnsErr.code = 'SSRF_DNS_FAILED';
dnsErr.hostname = cleanHost;
cb(dnsErr);
return;
}
for (const entry of entries) {
if (isPrivateOrReservedIp(entry.address, ipPolicy)) {
failSsrf(
entry.address,
`DNS rebinding blocked: "${cleanHost}" resolved to "${entry.address}"`
);
return;
}
}
const requestedFamily = opts.family === 4 || opts.family === 6 ? opts.family : 0;
const matching = requestedFamily
? entries.filter((e) => e.family === requestedFamily)
: entries;
const finalEntries = matching.length > 0 ? matching : entries;
if (opts.all) {
cb(null, finalEntries);
} else {
cb(null, finalEntries[0].address, finalEntries[0].family);
}
})
.catch((err) => {
const dnsErr = new Error(
`DNS resolution failed for "${cleanHost}": ${err?.message || 'lookup error'}`
);
dnsErr.code = err?.code === 'SSRF_PRIVATE_IP' ? 'SSRF_PRIVATE_IP' : 'SSRF_DNS_FAILED';
dnsErr.hostname = cleanHost;
cb(dnsErr);
});
};
}
/**
* Retrieve a cached module-level `undici` `Agent` when `!lookupFn`, or create a short-keepalive
* per-call `Agent` when a custom `lookupFn` is supplied (so response body streams stay readable
* after `safeFetch` resolves without premature `agent.close()`).
*
* @param {object} params - Agent options
* @param {boolean} params.allowPrivateLan - Allow RFC1918/ULA
* @param {boolean} params.allowTailscale - Allow Tailscale CGNAT
* @param {Function|null} params.lookupFn - Optional injected async resolver
* @returns {any}
*/
function getSsrfDispatcher({ allowPrivateLan, allowTailscale, lookupFn }) {
if (!UndiciAgent) return null;
if (lookupFn) {
return new UndiciAgent({
keepAliveTimeout: 1,
keepAliveMaxTimeout: 1,
connect: {
lookup: createSsrfConnectLookup({ allowPrivateLan, allowTailscale, lookupFn }),
},
});
}
const cacheKey = `${Boolean(allowPrivateLan)}:${Boolean(allowTailscale)}`;
let cached = CACHED_SSRF_AGENTS.get(cacheKey);
if (!cached) {
cached = new UndiciAgent({
keepAliveTimeout: 5_000,
keepAliveMaxTimeout: 15_000,
connect: {
lookup: createSsrfConnectLookup({ allowPrivateLan, allowTailscale, lookupFn: null }),
},
});
CACHED_SSRF_AGENTS.set(cacheKey, cached);
}
return cached;
}
/**
* Clone arbitrary `RequestInit['headers']` (`Headers`, tuple array, or plain object) into a plain object.
*
* @param {Headers|Array<[string, string]>|Record<string, string>|undefined|null} rawHeaders - Input headers
* @returns {Record<string, string>}
*/
function cloneRequestHeaders(rawHeaders) {
const out = {};
if (!rawHeaders) return out;
if (typeof Headers !== 'undefined' && rawHeaders instanceof Headers) {
for (const [k, v] of rawHeaders.entries()) {
out[k] = v;
}
return out;
}
if (Array.isArray(rawHeaders)) {
for (const entry of rawHeaders) {
if (Array.isArray(entry) && entry.length >= 2 && entry[0] != null && entry[1] != null) {
const key = String(entry[0]);
if (!FORBIDDEN_HEADER_KEYS.has(key)) {
out[key] = String(entry[1]);
}
}
}
return out;
}
if (typeof rawHeaders === 'object') {
for (const [k, v] of Object.entries(rawHeaders)) {
if (v !== undefined && v !== null && !FORBIDDEN_HEADER_KEYS.has(k)) {
out[k] = String(v);
}
}
}
return out;
}
/**
* Remove headers matching a lowercase name set without mutating the source object.
*
* @param {Record<string, string>} headersObj - Cloned headers record
* @param {Set<string>} lowerNamesToRemove - Lowercase header names to strip
* @returns {Record<string, string>}
*/
function stripHeaderNames(headersObj, lowerNamesToRemove) {
const next = {};
for (const [k, v] of Object.entries(headersObj)) {
if (!lowerNamesToRemove.has(k.toLowerCase())) {
next[k] = v;
}
}
return next;
}
/**
* Read a single response header case-insensitively across `Headers`, `Map`, and plain object mocks.
*
* @param {any} headers - Response headers container
* @param {string} name - Header name
* @returns {string|null}
*/
function getResponseHeader(headers, name) {
if (!headers || typeof headers !== 'object') return null;
if (typeof headers.get === 'function') {
const val = headers.get(name);
if (val !== undefined && val !== null) return String(val);
const lowerVal = headers.get(name.toLowerCase());
return lowerVal !== undefined && lowerVal !== null ? String(lowerVal) : null;
}
const target = name.toLowerCase();
for (const [k, v] of Object.entries(headers)) {
if (k.toLowerCase() === target && v !== undefined && v !== null) {
return String(v);
}
}
return null;
}
/**
* Convert response headers into a plain `Record<string, string>`.
*
* @param {any} headers - Response headers container
* @returns {Record<string, string>}
*/
function serializeResponseHeaders(headers) {
if (!headers || typeof headers !== 'object') return {};
if (typeof headers.entries === 'function') {
return Object.fromEntries(headers.entries());
}
const out = {};
for (const [k, v] of Object.entries(headers)) {
if (v !== undefined && v !== null && !FORBIDDEN_HEADER_KEYS.has(k)) {
out[k.toLowerCase()] = String(v);
}
}
return out;
}
/**
* Perform a DNS-rebinding-safe, redirect-validated outbound HTTP fetch (`INV-LEGO-13`, `INV-LEGO-03`).
* Never throws; returns a deterministic `INV-LEGO-01` `okEnvelope` or `errorEnvelope`.
*
* @param {string|URL} rawUrl - Outbound target URL
* @param {RequestInit} [init={}] - Standard `fetch` request init
* @param {object} [options={}] - Security & transport options
* @param {number} [options.maxRedirects=3] - Maximum validated redirect hops (`0` disables redirects)
* @param {number} [options.timeoutMs=15000] - Total request timeout across redirects in milliseconds
* @param {string[]} [options.allowedProtocols=['https:', 'http:']] - Allowed URL schemes
* @param {boolean} [options.allowPrivateLan=false] - Allow RFC1918 / ULA / `.local` targets
* @param {boolean} [options.allowTailscale=false] - Allow Tailscale `100.64.0.0/10` targets
* @param {string[]|Set<string>|null} [options.allowedHosts=null] - Optional exact host allowlist
* @param {Function|null} [options.lookupFn=null] - Optional async DNS resolver override
* @param {typeof fetch} [options.fetchImpl=globalThis.fetch] - Fetch implementation override for testing
* @param {string} [options.tool='security.fetch'] - Originating tool identifier
* @returns {Promise<{ ok: boolean, tool: string, summary: string, data?: { status: number, url: string, redirected: boolean, redirects: number, headers: Record<string, string>, response: Response }, error?: { code: string, message: string, details?: unknown } }>}
*/
export async function safeFetch(rawUrl, init = {}, options = {}) {
const opts = options && typeof options === 'object' ? options : {};
const safeTool =
typeof opts.tool === 'string' && opts.tool.trim().length > 0
? opts.tool.trim()
: 'security.fetch';
const rawMaxRedirects = opts.maxRedirects !== undefined ? Number(opts.maxRedirects) : 3;
const safeMaxRedirects = Number.isFinite(rawMaxRedirects)
? Math.max(0, Math.trunc(rawMaxRedirects))
: 3;
const rawTimeoutMs = opts.timeoutMs !== undefined ? Number(opts.timeoutMs) : 15_000;
const safeTimeoutMs =
Number.isFinite(rawTimeoutMs) && rawTimeoutMs > 0 ? Math.max(1, Math.trunc(rawTimeoutMs)) : 15_000;
const allowedProtocols = opts.allowedProtocols ?? ['https:', 'http:'];
const allowPrivateLan = opts.allowPrivateLan === true;
const allowTailscale = opts.allowTailscale === true;
const allowedHosts = opts.allowedHosts ?? null;
const lookupFn = typeof opts.lookupFn === 'function' ? opts.lookupFn : null;
const fetchImpl = opts.fetchImpl !== undefined ? opts.fetchImpl : globalThis.fetch;
if (typeof fetchImpl !== 'function') {
return errorEnvelope('FETCH_FAILED', 'fetchImpl must be a function', null, safeTool);
}
const baseInit = init && typeof init === 'object' ? init : {};
const {
signal: callerSignal,
redirect: _ignoredRedirect,
dispatcher: _ignoredDispatcher,
headers: initialHeaders,
...restInit
} = /** @type {Record<string, any>} */ (baseInit);
const controller = new AbortController();
let timedOut = false;
const onCallerAbort = () => {
if (!controller.signal.aborted) {
controller.abort(
callerSignal?.reason ?? new DOMException('The operation was aborted.', 'AbortError')
);
}
};
if (callerSignal) {
if (callerSignal.aborted) {
onCallerAbort();
} else if (typeof callerSignal.addEventListener === 'function') {
callerSignal.addEventListener('abort', onCallerAbort, { once: true });
}
}
const timer = setTimeout(() => {
timedOut = true;
if (!controller.signal.aborted) {
controller.abort(
new DOMException(`Outbound fetch timed out after ${safeTimeoutMs}ms`, 'TimeoutError')
);
}
}, safeTimeoutMs);
timer.unref?.();
const useNativeUndici =
fetchImpl === globalThis.fetch &&
fetchImpl === NATIVE_GLOBAL_FETCH &&
typeof undiciFetch === 'function' &&
Boolean(UndiciAgent);
const dispatcher =
fetchImpl === globalThis.fetch
? getSsrfDispatcher({ allowPrivateLan, allowTailscale, lookupFn })
: null;
const activeFetch = useNativeUndici ? undiciFetch : fetchImpl;
let currentUrl = typeof rawUrl === 'string' || rawUrl instanceof URL ? String(rawUrl) : '';
let currentHeaders = cloneRequestHeaders(initialHeaders);
let currentInit = { ...restInit };
let hops = 0;
try {
while (hops <= safeMaxRedirects) {
if (controller.signal.aborted) {
return errorEnvelope(
'FETCH_ABORTED',
timedOut
? `Outbound fetch timed out after ${safeTimeoutMs}ms`
: 'Outbound fetch was aborted',
{ url: currentUrl, timedOut },
safeTool
);
}
const check = await validateOutboundUrl(currentUrl, {
allowedProtocols,
allowPrivateLan,
allowTailscale,
allowedHosts,
lookupFn,
tool: safeTool,
});
if (!check.ok) {
return check;
}
currentUrl = check.data.url;
const requestInit = {
...currentInit,
...(Object.keys(currentHeaders).length > 0 ? { headers: { ...currentHeaders } } : {}),
redirect: 'manual',
signal: controller.signal,
...(dispatcher ? { dispatcher } : {}),
};
const res = await activeFetch(currentUrl, requestInit);
const status = Number(res?.status) || 0;
if (REDIRECT_STATUS_CODES.has(status)) {
res?.body?.cancel?.().catch(() => {});
const location = getResponseHeader(res?.headers, 'location');
if (!location || !location.trim() || /[\r\n]/.test(location)) {
return errorEnvelope(
'SSRF_INVALID_REDIRECT',
`Redirect response (${status}) is missing a valid Location header`,
{ status, url: currentUrl },
safeTool
);
}
if (hops >= safeMaxRedirects) {
return errorEnvelope(
'SSRF_TOO_MANY_REDIRECTS',
`Exceeded maximum redirect hops (${safeMaxRedirects})`,
{ maxRedirects: safeMaxRedirects, url: currentUrl, location },
safeTool
);
}
let nextParsed;
let currentParsed;
try {
currentParsed = new URL(currentUrl);
nextParsed = new URL(location, currentUrl);
} catch {
return errorEnvelope(
'SSRF_INVALID_REDIRECT',
`Malformed redirect Location URL "${location}"`,
{ status, url: currentUrl, location },
safeTool
);
}
if (nextParsed.origin !== currentParsed.origin) {
currentHeaders = stripHeaderNames(currentHeaders, CROSS_ORIGIN_SENSITIVE_HEADERS);
}
const currentMethod = String(currentInit.method || 'GET').toUpperCase();
if (
(status === 303 && currentMethod !== 'GET' && currentMethod !== 'HEAD') ||
((status === 301 || status === 302) && currentMethod === 'POST')
) {
currentInit = { ...currentInit, method: 'GET' };
delete currentInit.body;
currentHeaders = stripHeaderNames(currentHeaders, BODY_SPECIFIC_HEADERS);
}
currentUrl = nextParsed.toString();
hops += 1;
continue;
}
return okEnvelope(safeTool, `Fetched ${currentUrl} (${status})`, {
status,
url: currentUrl,
redirected: hops > 0,
redirects: hops,
headers: serializeResponseHeaders(res?.headers),