Skip to content

Resolve Hosts to Prevent DNS Localhost Resolution

If a URL uses a public hostname then it likely should be allowed, but if the public hostname such as https://my-domain.com resolves to 127.0.0.1 then it is effectively an SSRF attack. How do you guard against this SSRF vector?

You need to Node.js own DNS Resolver and lookup function to resolve the hostname to an IP address. If the IP address is a private IP address then you should block the request.

import dns from 'node:dns';
// Example, resolve a hostname to an IP address
// to avoid SSRF attacks
async function lookup(hostname) {
try {
const { address, family } = await dns.promises.lookup(hostname);
// note, this next conditional statement isn't comprehensive and is used here
// as an example reference
if (family === 4 && (address.startsWith('127.') || address === '::1')) {
throw new Error('Localhost resolution detected');
}
return address;
} catch (error) {
throw new Error('DNS resolution failed');
}
}