Dev.to Security 🔐 Cybersecurity 👁 0 📖 6 min read

The Definitive Guide to Server-Side Request Forgery (SSRF)

From internal port scanning to cloud instance metadata exfiltration. Server-Side Request Forgery (SSRF) is a serious web application security vulnerability that allows attackers to manipulate a server into sending reques

From internal port scanning to cloud instance metadata exfiltration. Server-Side Request Forgery (SSRF) is a serious web application security vulnerability that allows attackers to manipulate a server into sending requests to unintended destinations.

Unlike traditional attacks that target a user's browser, SSRF abuses the trust placed in a backend server. When an application fetches URLs supplied by users without proper validation, attackers may reach internal services, access restricted endpoints, or interact with cloud infrastructure.

For developers building modern web applications, understanding SSRF is essential. This guide explains how SSRF works, demonstrates a controlled testing environment, and covers a complete remediation guide: hardening internal DNS egress proxies and IMDSv2.

1. Understanding SSRF and How It Works

SSRF occurs when an application accepts a URL from a user and makes a server-side HTTP request without sufficiently validating the destination.

Consider a website that provides a URL preview feature. A user submits a URL, and the backend retrieves its contents to generate a preview.

A vulnerable implementation might look like this:

from flask import Flask, request
import requests

app = Flask(__name__)

@app.route("/preview")
def preview():
    url = request.args.get("url")

    response = requests.get(url)

    return response.text

if __name__ == "__main__":
    app.run(port=5000)

The problem is that the application accepts arbitrary URLs. It does not check whether the destination is public, private, or internal.

Potential SSRF targets include:

  • Internal application services.
  • Localhost and private network addresses.
  • Internal DNS services.
  • Cloud instance metadata endpoints.
  • Administrative dashboards and APIs.

This makes SSRF particularly dangerous in cloud environments where backend services may have access to sensitive infrastructure.

2. Common SSRF Techniques and Decimal IP Notation

Attackers may attempt different address representations to bypass weak URL filters.

One example is decimal IP notation.

The IPv4 address 127.0.0.1 can also be represented as the decimal integer 2130706433.

Test the conversion using Python:

import ipaddress

decimal_ip = 2130706433

converted_ip = ipaddress.ip_address(decimal_ip)

print("Original decimal:", decimal_ip)
print("Converted IPv4:", converted_ip)

Expected output:

Original decimal: 2130706433
Converted IPv4: 127.0.0.1

A string-based security filter might recognize the dotted address but fail to recognize alternative representations.

Other areas that require testing include:

  • IPv4 and IPv6 representations.
  • DNS resolution and rebinding.
  • Redirect handling.
  • URL encoding and normalization.
  • Alternative hostname representations.

For a controlled local Docker lab, start a test server:

python -m http.server 8000 --bind 127.0.0.1

Test both representations:

curl http://127.0.0.1:8000
curl http://2130706433:8000

These requests demonstrate how different representations can resolve to the same loopback destination on compatible systems.

Security lesson: Never depend on simple string matching to validate URLs or IP addresses.

3. Building a Controlled SSRF Testing Environment

A local testing environment helps developers understand how backend requests behave without targeting external systems.

Create a project directory:

mkdir ssrf-security-lab
cd ssrf-security-lab

Create a Docker Compose configuration:

services:
  internal-service:
    image: nginx:alpine
    container_name: ssrf-internal
    ports:
      - "127.0.0.1:8081:80"

Start the environment:

docker compose up -d

Check the local service:

curl http://127.0.0.1:8081

Expected result: an Nginx welcome page.

Check the running container:

docker ps

Stop the lab after testing:

docker compose down

This environment provides a simple internal service for understanding how applications interact with backend resources.

4. Vulnerable vs. Remediated Code: Complete SSRF Protection

The vulnerable implementation accepts any URL and sends a backend request.

A safer implementation should enforce strict destination validation, use an allowlist, restrict redirects, and apply request timeouts.

Remediated Python example:

from flask import Flask, request, abort
from urllib.parse import urlparse
import requests
import ipaddress
import socket

app = Flask(__name__)

ALLOWED_HOSTS = {
    "example.com"
}

def validate_url(url):
    parsed = urlparse(url)

    if parsed.scheme != "https":
        return False

    if parsed.hostname not in ALLOWED_HOSTS:
        return False

    if parsed.username or parsed.password:
        return False

    try:
        addresses = socket.getaddrinfo(
            parsed.hostname,
            443,
            type=socket.SOCK_STREAM
        )

        if not addresses:
            return False

        for address in addresses:
            ip = ipaddress.ip_address(address[4][0])

            if not ip.is_global:
                return False

    except (OSError, ValueError):
        return False

    return True


@app.route("/preview")
def preview():
    url = request.args.get("url", "")

    if not validate_url(url):
        abort(403, "Destination not allowed")

    try:
        response = requests.get(
            url,
            timeout=5,
            allow_redirects=False
        )

        return response.text

    except requests.RequestException:
        abort(502, "Request failed")


if __name__ == "__main__":
    app.run(port=5000)

This is a baseline defensive example, not a complete production-grade SSRF control. DNS validation followed by a separate HTTP connection can still permit DNS rebinding or resolution changes.

Production applications should enforce destination restrictions at the network egress layer as well. The proxy must validate the actual resolved and connected IP address, including IPv4 and IPv6, and reject private, loopback, link-local, and other prohibited destinations.

5. Complete Remediation Guide: DNS Egress Proxies and IMDSv2

Application-level validation alone is not enough. Strong SSRF protection requires multiple security layers.

A. Harden internal DNS and egress proxies

An outbound proxy should enforce destination policies before allowing backend requests.

Recommended controls:

  • Allow only approved destination domains.
  • Block private, loopback, and link-local address ranges.
  • Validate resolved IPv4 and IPv6 addresses.
  • Prevent DNS rebinding and resolution inconsistencies.
  • Restrict outbound ports and protocols.
  • Disable unrestricted redirects.
  • Maintain logs for blocked outbound requests.

For example, a Squid proxy can use destination ACLs:

acl SSL_ports port 443
acl Safe_ports port 80 443
acl CONNECT method CONNECT

http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports

acl blocked_private dst 10.0.0.0/8
acl blocked_loopback dst 127.0.0.0/8
acl blocked_linklocal dst 169.254.0.0/16
acl blocked_private_v6 dst ::1
acl blocked_private_v6 dst fc00::/7
acl blocked_linklocal_v6 dst fe80::/10

http_access deny blocked_private
http_access deny blocked_loopback
http_access deny blocked_linklocal
http_access deny blocked_private_v6
http_access deny blocked_linklocal_v6

http_access allow localhost
http_access deny all

This is an illustrative baseline. Production proxy policies must also account for all prohibited address ranges, DNS resolution behavior, and the actual network architecture.

B. Enable AWS IMDSv2

Cloud metadata services can expose sensitive instance information if applications are vulnerable to SSRF.

AWS Instance Metadata Service Version 2 (IMDSv2) introduces session-oriented access using tokens.

Enable token requirements using AWS CLI:

aws ec2 modify-instance-metadata-options \
  --instance-id i-xxxxxxxxxxxxxxxxx \
  --http-tokens required \
  --http-endpoint enabled \
  --http-put-response-hop-limit 1

Replace the instance ID with the authorized test instance.

Verify the configuration:

aws ec2 describe-instances \
  --instance-ids i-xxxxxxxxxxxxxxxxx \
  --query "Reservations[].Instances[].MetadataOptions"

Test token-based metadata access from the authorized instance without displaying credentials:

TOKEN=$(curl -s -X PUT \
  "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 60")

curl -s -o /dev/null -w "%{http_code}\n" \
  -H "X-aws-ec2-metadata-token: $TOKEN" \
  "http://169.254.169.254/latest/meta-data/"

The token requirement makes simple unauthenticated metadata requests insufficient. However, IMDSv2 is not a replacement for SSRF prevention. Applications should still block access to metadata endpoints through their egress controls and avoid exposing unnecessary instance permissions.

C. Final SSRF Security Checklist

  • [ ] Validate and normalize every user-supplied URL.
  • [ ] Use strict destination allowlists.
  • [ ] Block private and reserved IP ranges.
  • [ ] Validate IPv4 and IPv6 DNS results.
  • [ ] Prevent DNS rebinding.
  • [ ] Disable unrestricted redirects.
  • [ ] Configure outbound proxy restrictions.
  • [ ] Require IMDSv2 on AWS EC2 instances.
  • [ ] Apply least-privilege IAM permissions.
  • [ ] Monitor and log suspicious outbound requests.

Final Thoughts

SSRF is not just a URL validation problem. It is an infrastructure security issue that affects application code, internal networking, DNS resolution, and cloud permissions.

A strong defense combines secure coding practices, restricted network egress, hardened DNS proxies, and cloud metadata protection.

Developers should test these controls regularly rather than relying on a single validation function.

Want to strengthen application security?

Download SSRF Remediation Guide

Explore Hack My Website for automated DAST scanning and practical web application security testing.

📰 Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.