-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathssrf.js
More file actions
157 lines (138 loc) · 4.98 KB
/
ssrf.js
File metadata and controls
157 lines (138 loc) · 4.98 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
/**
* SSRF Protection Utilities
* Validates URLs before making external requests to prevent Server-Side Request Forgery
*/
import { isIP } from 'net';
import dns from 'dns/promises';
/**
* Check if an IP address is private/internal
* Blocks: localhost, private ranges, link-local, loopback, etc.
* @param {string} ip - IP address to check
* @returns {boolean} - true if private/internal
*/
export function isPrivateIP(ip) {
// IPv4 private/reserved ranges
const privateRanges = [
/^127\./, // Loopback (127.0.0.0/8)
/^10\./, // Private Class A (10.0.0.0/8)
/^172\.(1[6-9]|2[0-9]|3[0-1])\./, // Private Class B (172.16.0.0/12)
/^192\.168\./, // Private Class C (192.168.0.0/16)
/^169\.254\./, // Link-local (169.254.0.0/16) - AWS/cloud metadata!
/^0\./, // Current network (0.0.0.0/8)
/^100\.(6[4-9]|[7-9][0-9]|1[0-1][0-9]|12[0-7])\./, // Shared address space (100.64.0.0/10)
/^192\.0\.0\./, // IETF Protocol Assignments (192.0.0.0/24)
/^192\.0\.2\./, // TEST-NET-1 (192.0.2.0/24)
/^198\.51\.100\./, // TEST-NET-2 (198.51.100.0/24)
/^203\.0\.113\./, // TEST-NET-3 (203.0.113.0/24)
/^224\./, // Multicast (224.0.0.0/4)
/^240\./, // Reserved (240.0.0.0/4)
/^255\.255\.255\.255$/, // Broadcast
];
// IPv6 private/reserved
const ipv6Private = [
/^::1$/, // Loopback
/^fe80:/i, // Link-local
/^fc00:/i, // Unique local (fc00::/7)
/^fd00:/i, // Unique local
/^ff00:/i, // Multicast
/^::ffff:(127\.|10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.|169\.254\.)/i, // IPv4-mapped
];
// Check IPv4
for (const range of privateRanges) {
if (range.test(ip)) {
return true;
}
}
// Check IPv6
for (const range of ipv6Private) {
if (range.test(ip)) {
return true;
}
}
return false;
}
/**
* Validate a URL for safe external fetching
* @param {string} urlString - URL to validate
* @param {object} options - Validation options
* @param {boolean} options.requireHttps - Require HTTPS (default true)
* @param {boolean} options.blockPrivateIPs - Block private IPs (default true)
* @param {boolean} options.resolveDNS - Resolve hostname to check IP (default true)
* @returns {Promise<{valid: boolean, error: string|null, url: URL|null}>}
*/
export async function validateExternalUrl(urlString, options = {}) {
const {
requireHttps = true,
blockPrivateIPs = true,
resolveDNS = true,
} = options;
let url;
try {
url = new URL(urlString);
} catch {
return { valid: false, error: 'Invalid URL format', url: null };
}
// Check protocol
if (requireHttps && url.protocol !== 'https:') {
return { valid: false, error: 'URL must use HTTPS', url: null };
}
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
return { valid: false, error: 'URL must use HTTP or HTTPS', url: null };
}
const hostname = url.hostname;
// Block localhost variants
const localhostPatterns = ['localhost', '127.0.0.1', '::1', '[::1]', '0.0.0.0'];
if (localhostPatterns.includes(hostname.toLowerCase())) {
return { valid: false, error: 'localhost URLs are not allowed', url: null };
}
// If hostname is an IP, check directly
if (isIP(hostname)) {
if (blockPrivateIPs && isPrivateIP(hostname)) {
return { valid: false, error: 'Private/internal IP addresses are not allowed', url: null };
}
return { valid: true, error: null, url };
}
// Resolve DNS to check for private IPs (DNS rebinding protection)
if (resolveDNS && blockPrivateIPs) {
try {
const addresses = await dns.resolve4(hostname).catch(() => []);
const addresses6 = await dns.resolve6(hostname).catch(() => []);
const allAddresses = [...addresses, ...addresses6];
for (const ip of allAddresses) {
if (isPrivateIP(ip)) {
return {
valid: false,
error: `Hostname ${hostname} resolves to private IP ${ip}`,
url: null
};
}
}
} catch (err) {
// DNS resolution failed - this could be an attacker attempting to bypass SSRF
// protection via DNS manipulation or timing attacks.
// Security: block the request rather than allowing it through
console.warn(`SSRF protection: DNS resolution failed for ${hostname}: ${err.message}`);
return {
valid: false,
error: `DNS resolution failed for hostname: ${hostname}`,
url: null
};
}
}
return { valid: true, error: null, url };
}
/**
* Wrapper for fetch that validates URL first
* @param {string} urlString - URL to fetch
* @param {object} fetchOptions - Options for fetch()
* @param {object} validationOptions - Options for URL validation
* @returns {Promise<Response>}
* @throws {Error} If URL validation fails
*/
export async function safeFetch(urlString, fetchOptions = {}, validationOptions = {}) {
const validation = await validateExternalUrl(urlString, validationOptions);
if (!validation.valid) {
throw new Error(`SSRF protection: ${validation.error}`);
}
return fetch(urlString, fetchOptions);
}