JAVASCRIPT
Preventing Server-Side Request Forgery (SSRF) in Node.js
Implement robust server-side request forgery (SSRF) protection in Node.js applications by validating URLs and restricting network access to prevent unauthorized requests.
const { URL } = require('url');
const https = require('https');
const http = require('http');
// List of allowed hosts or a regex to validate them.
// For a real application, this should be dynamically managed or more extensive.
const ALLOWED_HOSTS = ['example.com', 'api.trusted.com'];
const BLOCKED_IPS_REGEX = /^(10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.|127\.|0\.0\.0\.0|169\.254\.)/;
function isSafeUrl(inputUrl) {
try {
const url = new URL(inputUrl);
// 1. Check for allowed protocols
if (!['http:', 'https:'].includes(url.protocol)) {
return false;
}
// 2. Prevent IP addresses or blocked internal ranges
// This is a basic check; real-world might use a library like 'is-ip'
if (BLOCKED_IPS_REGEX.test(url.hostname)) {
return false;
}
// 3. Ensure hostname is not an internal IP or localhost (more robust check needed)
// For production, consider DNS resolution and IP checks for public IPs only
const hostname = url.hostname;
if (hostname === 'localhost' || hostname === '127.0.0.1') {
return false;
}
// 4. Whitelist hostnames (if specific external services are allowed)
// If ALLOWED_HOSTS is empty, assume any public host is allowed after IP checks.
if (ALLOWED_HOSTS.length > 0 && !ALLOWED_HOSTS.includes(hostname)) {
return false;
}
return true;
} catch (error) {
return false; // Invalid URL format
}
}
async function makeSafeRequest(url) {
if (!isSafeUrl(url)) {
throw new Error('Attempted SSRF: Unsafe URL detected.');
}
return new Promise((resolve, reject) => {
const client = url.startsWith('https') ? https : http;
client.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
}).on('error', (err) => {
reject(err);
});
});
}
// Example Usage:
// makeSafeRequest('https://example.com/data')
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Error:', error.message));
// // This would be blocked:
// makeSafeRequest('http://127.0.0.1/admin')
// .catch(error => console.error('Blocked:', error.message));
// makeSafeRequest('http://192.168.1.100/internal-api')
// .catch(error => console.error('Blocked:', error.message));
// makeSafeRequest('ftp://malicious.com/file')
// .catch(error => console.error('Blocked:', error.message));
How it works: Server-Side Request Forgery (SSRF) occurs when an attacker induces a server-side application to make an HTTP request to an arbitrary domain of their choosing. This snippet provides a `isSafeUrl` function to validate URLs by checking protocols, blocking internal IP ranges, and optionally whitelisting external hosts. The `makeSafeRequest` function then wraps `http.get`/`https.get` to ensure only validated URLs are accessed, preventing the server from being tricked into making requests to internal services or malicious external sites.