Repository navigation
Preventing SSRF #6737
|
Hey folks, I use Axios in a backend environment, where I download files using dynamic URLs. const response = await axios({
method: 'GET',
responseType: 'arraybuffer',
url,
});Snyk flagged this as an SSRF vulnerability. However, when I'm looking online about Axios, I see a lot of resolved issues around SSRF (like #6545). My question is: do I need to clean and verify those URLs before doing the request? Or is this done automatically by Axios? Cheers! |
Replies: 1 comment 1 reply
|
Snyk is right - axios does not prevent SSRF automatically. You need to validate URLs before passing them in. Here's a solid baseline validator for backend file download scenarios: import { URL } from 'url'
// private/loopback ranges that shouldn't be reachable
const PRIVATE_IP = /^(127\.|10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.|::1|localhost)/i
function assertSafeUrl(rawUrl: string): void {
let parsed: URL
try {
parsed = new URL(rawUrl)
} catch {
throw new Error(`Invalid URL: ${rawUrl}`)
}
if (!['http:', 'https:'].includes(parsed.protocol)) {
throw new Error(`Disallowed protocol: ${parsed.protocol}`)
}
if (PRIVATE_IP.test(parsed.hostname)) {
throw new Error(`Private/loopback addresses not allowed: ${parsed.hostname}`)
}
}
// before your axios call:
assertSafeUrl(url)
const response = await axios({ method: 'GET', responseType: 'arraybuffer', url })A few notes: the regex blocklist is a good baseline but a hostname allowlist is stronger if you know which external services you'll be downloading from - then you just check against the known set of allowed hostnames. Also watch out for DNS rebinding - a hostname can resolve to a private IP after your check passes. For high-security contexts, resolve the hostname to an IP yourself and validate that too. But for most cases the blocklist above handles the common SSRF vectors that scanners flag. |
Snyk is right - axios does not prevent SSRF automatically. You need to validate URLs before passing them in.
Here's a solid baseline validator for backend file download scenarios: