Skip to content

SSRF Protection — Preventing Server-Side Request Forgery

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Ssrf Protection. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

SSRF Attacks trick servers into making requests to internal systems, potentially exposing sensitive services and cloud metadata endpoints.

const { URL } = require('url');
const dns = require('dns').promises;

// SSRF protection middleware
async function validateURL(urlString) {
  const parsed = new URL(urlString);

  // Block internal IPs and hostnames
  const blockedHosts = [
    'localhost', '127.0.0.1', '0.0.0.0',
    '169.254.169.254',  // AWS metadata
    'metadata.google.internal',  // GCP metadata
    '100.100.100.200'  // Alicloud metadata
  ];

  if (blockedHosts.includes(parsed.hostname)) {
    throw new Error('URL pointing to internal service blocked');
  }

  // Resolve DNS and check for private IPs
  try {
    const addresses = await dns.resolve4(parsed.hostname);
    const privateRanges = [
      /^10\./, /^172\.(1[6-9]|2\d|3[01])\./, /^192\.168\./,
      /^127\./, /^169\.254\./
    ];

    for (const addr of addresses) {
      if (privateRanges.some(range => range.test(addr))) {
        throw new Error(`URL resolves to private IP: ${addr}`);
      }
    }
  } catch (err) {
    throw new Error(`DNS resolution failed: ${err.message}`);
  }

  // Only allow specific protocols
  if (!['http:', 'https:'].includes(parsed.protocol)) {
    throw new Error('Only HTTP/HTTPS protocols allowed');
  }

  return parsed.toString();
}

// Safe HTTP client
class SafeHttpClient {
  constructor(options = {}) {
    this.options = {
      timeout: options.timeout || 5000,
      maxRedirects: options.maxRedirects || 5,
      allowedHosts: options.allowedHosts || [],
      ...options
    };
  }

  async get(url) {
    const validated = await validateURL(url);
    return axios.get(validated, {
      timeout: this.options.timeout,
      maxRedirects: this.options.maxRedirects,
      headers: { 'User-Agent': 'ScanApp-Service' }
    });
  }
}

// Usage
app.post('/api/fetch-url', async (req, res) => {
  try {
    const client = new SafeHttpClient({ allowedHosts: ['api.example.com'] });
    const response = await client.get(req.body.url);
    res.json({ status: response.status, data: response.data.slice(0, 1000) });
  } catch (err) {
    res.status(400).json({ error: 'URL_FETCH_FAILED', message: err.message });
  }
});

SSRF protection prevents attackers from using your backend as a proxy to access internal services.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro