How to Prevent SSRF Vulnerability in AI-Generated Backend Code
OverMCP Team
How to Prevent SSRF Vulnerability in AI-Generated Backend Code
TL;DR: To prevent SSRF vulnerability in your AI-generated backend code, always validate and whitelist allowed URLs, block private IP ranges, and use a dedicated URL parser to avoid bypasses. Never trust user input directly in server-side requests.
Server-Side Request Forgery (SSRF) is a critical security flaw where an attacker tricks your server into making unintended HTTP requests to internal resources. AI coding tools like Cursor, Bolt.new, and ChatGPT often generate code that fetches external resources—images, webhooks, APIs—and they frequently miss SSRF protections. If you're building apps fast with AI, you're likely shipping SSRF holes without knowing it.
In this guide, you'll learn exactly how to prevent SSRF vulnerability in your code, with concrete examples and fixes you can apply today.
What Is SSRF and Why AI Code Is Vulnerable?
SSRF occurs when your backend makes HTTP requests to URLs provided by users or external sources. Attackers can manipulate these URLs to access:
169.254.169.254)10.0.0.1, 192.168.1.1)127.0.0.1, localhost)file:// protocolAI models are trained on code that often prioritizes functionality over security. A common pattern in AI-generated Node.js or Python code looks like this:
// AI-generated code (vulnerable)
const response = await fetch(userInput.url);
const data = await response.json();This code trusts the user-provided URL completely. An attacker can send http://169.254.169.254/latest/meta-data/ and steal your cloud credentials.
How to Prevent SSRF Vulnerability: Step-by-Step
1. Whitelist Allowed URLs (The Best Defense)
If your app only needs to fetch from specific domains (e.g., api.example.com), whitelist them explicitly:
// Node.js example
const ALLOWED_HOSTS = ['api.example.com', 'images.example.com'];
function isUrlAllowed(url) {
try {
const parsed = new URL(url);
return ALLOWED_HOSTS.includes(parsed.hostname);
} catch {
return false;
}
}
if (!isUrlAllowed(userUrl)) {
throw new Error('URL not allowed');
}2. Block Private IP Ranges
Even with hostname whitelisting, DNS rebinding attacks can bypass it. Always resolve the IP and validate it's not private:
# Python example using ipaddress and socket
import socket
import ipaddress
def is_safe_url(url):
hostname = url.hostname
try:
ip = socket.gethostbyname(hostname)
addr = ipaddress.ip_address(ip)
# Block private, loopback, link-local, and multicast
if addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_multicast:
return False
return True
except:
return False3. Validate the URL Protocol
Restrict protocols to http and https only. Block file://, ftp://, dict://, etc.:
function isAllowedProtocol(url) {
return ['http:', 'https:'].includes(url.protocol);
}4. Avoid Raw Redirect Following
Attackers can use open redirects to bypass whitelists. Disable automatic redirects or validate the final URL:
// Node.js with node-fetch
const response = await fetch(url, { redirect: 'manual' });
if (response.status >= 300 && response.status < 400) {
const redirectUrl = new URL(response.headers.get('location'), url);
if (!isUrlAllowed(redirectUrl)) {
throw new Error('Redirect not allowed');
}
}5. Use a URL Parser, Not Regex
Attackers can bypass regex with URL encoding, Unicode, and other tricks. Use built-in URL parsers:
// Good
const parsed = new URL(url);
// Bad (vulnerable to bypass)
if (url.startsWith('http://example.com')) { ... }Real-World Example: Fixing AI-Generated Code
Here's a vulnerable snippet an AI might generate for fetching a profile image:
// Vulnerable AI-generated code
app.post('/fetch-image', async (req, res) => {
const imageUrl = req.body.url;
const response = await fetch(imageUrl);
const buffer = await response.buffer();
res.send(buffer);
});Fixed version with SSRF protection:
const ALLOWED_DOMAINS = ['img.example.com', 'cdn.trusted.com'];
const BLOCKED_IPS = ['127.0.0.0/8', '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '169.254.0.0/16'];
function isSafeUrl(urlString) {
let url;
try {
url = new URL(urlString);
} catch {
return false;
}
// Protocol check
if (!['http:', 'https:'].includes(url.protocol)) return false;
// Domain whitelist
if (!ALLOWED_DOMAINS.includes(url.hostname)) return false;
// IP resolution and range check
const dns = require('dns');
const addresses = dns.resolve4(url.hostname);
for (const ip of addresses) {
const ipNum = ip.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0);
for (const block of BLOCKED_IPS) {
const [base, mask] = block.split('/');
const baseNum = base.split('.').reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0);
const maskNum = ~(2 ** (32 - parseInt(mask)) - 1);
if ((ipNum & maskNum) === (baseNum & maskNum)) return false;
}
}
return true;
}
app.post('/fetch-image', async (req, res) => {
const imageUrl = req.body.url;
if (!isSafeUrl(imageUrl)) {
return res.status(400).send('Invalid URL');
}
const response = await fetch(imageUrl);
const buffer = await response.buffer();
res.send(buffer);
});Automating SSRF Detection with OverMCP
Manually reviewing every AI-generated endpoint is tedious. Platforms like OverMCP automatically scan your codebase for SSRF and other vulnerabilities, catching issues before they reach production. OverMCP integrates with your CI/CD pipeline and provides actionable fixes.
Additional Best Practices to Prevent SSRF Vulnerability
ssrf-req-filter for Node.js).169.254.169.254).FAQ
What is the most common cause of SSRF in AI-generated code?
The most common cause is directly using user input as a URL in server-side requests without validation. AI models often generate code that fetches resources from URLs provided in request bodies, query parameters, or headers, assuming they are safe.
Can SSRF be prevented without a whitelist?
Yes, you can block private IP ranges and restrict protocols, but whitelisting is the most robust defense. Without a whitelist, you rely on DNS resolution and IP checks, which can be bypassed with DNS rebinding or IPv6 tricks.
How does OverMCP help prevent SSRF in AI-generated code?
OverMCP automatically scans your codebase for SSRF vulnerabilities, including missing URL validation, unsafe fetch calls, and exposed internal endpoints. It provides line-level feedback and suggested fixes, integrating seamlessly with your development workflow.
Conclusion
To prevent SSRF vulnerability in your AI-generated backend code, you must validate URLs against a whitelist, block private IPs, restrict protocols, and handle redirects carefully. Don't assume AI-generated code is secure—always add these protections. Use automated scanning tools like OverMCP to catch issues early and ship with confidence.