Fix SSRF (Server Side Request Forgery) in Koa
SSRF in Koa occurs when your backend fetches a user-supplied URL without validation, effectively turning your server into a proxy for an attacker. This allows them to scan internal ports, hit loopback services (127.0.0.1), or exfiltrate cloud metadata (169.254.169.254). If you're using 'axios' or 'node-fetch' inside a Koa middleware on raw query params, you're vulnerable.
The Vulnerable Pattern
const Koa = require('koa'); const axios = require('axios'); const app = new Koa();app.use(async (ctx) => { const { targetUrl } = ctx.query; // CRITICAL VULNERABILITY: No validation on targetUrl const response = await axios.get(targetUrl); ctx.body = response.data; });
app.listen(3000);
The Secure Implementation
To kill SSRF, you must implement a multi-layered defense. First, use a strict allowlist for hostnames; never trust user input. Second, enforce HTTPS to prevent protocol smuggling (e.g., file:// or gopher://). Third, disable redirects in your HTTP client to prevent an attacker from bypassing domain checks via a 302 redirect to an internal IP. For advanced protection, resolve the DNS and verify the destination IP is not in a private range (RFC 1918) before the request is dispatched.
const Koa = require('koa'); const { URL } = require('url'); const axios = require('axios'); const app = new Koa();const ALLOWED_HOSTS = [‘api.trusted-partner.com’, ‘images.cdn.com’];
app.use(async (ctx) => { const { targetUrl } = ctx.query; try { const parsed = new URL(targetUrl);
// 1. Protocol Whitelisting if (parsed.protocol !== 'https:') { throw new Error('Forbidden Protocol'); } // 2. Domain Allowlisting if (!ALLOWED_HOSTS.includes(parsed.hostname)) { ctx.status = 403; ctx.body = 'Target Domain Not Allowed'; return; } const response = await axios.get(targetUrl, { timeout: 2000, maxRedirects: 0 // 3. Prevent Redirect-based SSRF }); ctx.body = response.data;} catch (err) { ctx.status = 400; ctx.body = ‘Invalid Request’; } });
app.listen(3000);
Your Koa API
might be exposed to SSRF (Server Side Request Forgery)
74% of Koa apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.