Explain Server-Side Request Forgery (SSRF) and how you would prevent it in a cloud-native application?

SalesforceSecurity Engineer3–5 YearsSecurity

Server-Side Request Forgery (SSRF) is a web security vulnerability that allows an attacker to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker’s choosing. This means the server, not the client, is manipulated into initiating connections. The impact of a successful SSRF attack can range from scanning internal networks, accessing restricted internal services, performing port scans on the server’s local network, or even exfiltrating sensitive data from cloud metadata services (e.g., AWS EC2 metadata API).

SSRF Mechanism and Impact

An SSRF vulnerability typically arises when a web application fetches a remote resource without sufficiently validating the user-supplied URL. For example, an application might have a feature that imports data from a URL, renders an image from a URL, or makes requests to external APIs. If an attacker can control part or all of that URL, they can point the server to internal IP addresses (like 127.0.0.1 or 10.0.0.1), internal hostnames, or even cloud metadata endpoints (like http://169.254.169.254/ in AWS). The server then performs the request on behalf of the attacker, effectively bypassing any client-side firewall or network access restrictions.

Prevention Strategies

Preventing SSRF requires a multi-layered approach. Foremost is strict input validation: implement an allowlist of permitted URLs or IP addresses that the application can access, rather than a blocklist. This means only explicitly approved destinations are allowed. If IP addresses must be used, ensure they are not private, loopback, or link-local addresses. Beyond input validation, network segmentation is critical. Deploy applications in a segmented network that restricts outbound access from the web server to internal resources using firewalls, VPC security groups, or network ACLs. Egress filtering should be configured to prevent the server from connecting to internal IP ranges, loopback addresses, and cloud metadata endpoints unless explicitly required and tightly controlled.

Best practice

The strongest defense against SSRF in a cloud-native environment is to implement a robust network perimeter combined with an application-level URL validation proxy. All external requests made by the application should pass through a dedicated, hardened proxy that strictly enforces an allowlist of destinations. Furthermore, use specialized HTTP client libraries or frameworks that automatically prevent redirects to internal IPs. For cloud environments, restrict IAM roles associated with EC2 instances or containers to have minimal permissions, especially concerning access to sensitive internal services or cloud APIs, and configure IMDSv2 (Instance Metadata Service Version 2) to require session tokens if available.

Edge case interviewers probe for

Interviewers often ask about advanced bypass techniques like DNS rebinding attacks, where a DNS entry is manipulated to resolve to an external IP initially, then to an internal IP after a short TTL, or using URL schemes like file://, gopher://, or data://. Another common edge case is partial URL control combined with URL parsers that may incorrectly resolve complex or encoded URLs, allowing an attacker to bypass simple regex checks. They might also ask how to handle scenarios where the application legitimately needs to access both internal and external resources without introducing SSRF vulnerabilities.

Common mistake

A common mistake is relying solely on blocklists for URL validation. Attackers can often bypass blocklists by using IP address encoding (decimal, hexadecimal), alternative IP address formats, non-standard port numbers, or DNS rebinding. Another error is not considering how internal DNS resolution might resolve attacker-controlled domains to internal IP addresses. Insufficient logging and monitoring of outbound connections from application servers also hinder detection and incident response for SSRF attempts.

What the interviewer is checking

The interviewer is checking your understanding of web application security vulnerabilities, specifically SSRF, and your ability to design and implement secure architectures. They want to see if you can think critically about attack vectors, apply defense-in-depth principles, and translate theoretical knowledge into practical mitigation strategies for cloud environments. Your answer should demonstrate knowledge of network security, input validation, and cloud-specific security controls.

Imagine your company has a helpful “internal request” desk. Normally, when a customer (like your web browser) wants something, they talk to the “receptionist” (your web application), who then goes to the “public archives” to get the information. SSRF is like a sneaky customer tricking the receptionist. Instead of asking for a document from the public archives, the customer gives the receptionist a disguised note that secretly tells them to go into a “restricted internal office” to fetch something private, like the CEO’s calendar or the employee directory. The receptionist, thinking it’s a normal request, unknowingly goes and fetches it.

To prevent this, you would train the receptionist to be very careful. First, they’d have a strict list (an allowlist) of ONLY the public archives they are allowed to get documents from, and they’d check every request against that list. Second, you’d put a strong, locked gate with a security guard (a firewall) between the reception area and the restricted internal offices. The guard would ensure that no one, not even the receptionist, can enter the restricted offices unless they have specific, pre-approved permission for that exact document. This way, the sneaky customer can’t trick the receptionist into going where they shouldn’t.

Why interviewers ask this

Interviewers ask about SSRF to gauge your understanding of critical server-side vulnerabilities that can have severe implications, especially in cloud environments. It tests your ability to identify how seemingly innocuous features can be exploited and your knowledge of defense-in-depth strategies covering both application and network security.

What a strong answer signals

A strong answer signals a comprehensive understanding of web security, including both attack vectors and multi-layered mitigation. It shows you can think like an attacker while designing robust defenses, integrating application-level validation with network segmentation and cloud-specific security controls like IAM and metadata service protection.

Common follow-ups

  • How can SSRF be used to exploit cloud metadata services?
  • What role do Web Application Firewalls (WAFs) play in mitigating SSRF, and what are their limitations?
  • How would you test for SSRF vulnerabilities during development and in production?

Advanced variation

Design a secure service that legitimately needs to fetch external URLs provided by users (e.g., a URL shortener or an image proxy), completely mitigating SSRF risks while maintaining full functionality. Describe the architectural components and security controls you would implement.

Consider an image processing microservice that allows users to provide an image URL for remote retrieval and resizing. An attacker could exploit this by submitting a URL like http://169.254.169.254/latest/meta-data/iam/security-credentials/. The service, running on AWS, would then fetch this URL, inadvertently returning temporary IAM credentials to the attacker. To prevent this, the service must implement strict URL validation, only allowing connection to a whitelist of trusted image hosting domains. Additionally, the instance’s security group should have egress rules blocking outbound traffic to private IP ranges and the metadata service IP, and IMDSv2 should be enforced requiring a session token for metadata access.

url_validator.py
import requests
from urllib.parse urlparse
import ipaddress

def is_safe_url(url: str) -> bool:
    # Define allowed domains (whitelist)
    ALLOWED_DOMAINS = ["example.com", "images.trustedcdn.net"]
    # Define disallowed IP ranges (private, loopback, link-local, cloud metadata)
    DISALLOWED_IP_RANGES = [
        "10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "127.0.0.0/8",
        "169.254.169.254/32", "0.0.0.0/8", "169.254.0.0/16" # Link-local, AWS IMDS
    ]

    try:
        parsed_url = urlparse(url)
        if not parsed_url.scheme in ["http", "https"]:
            return False

        # Resolve hostname to IP to check against disallowed ranges
        import socket
        ip_address = socket.gethostbyname(parsed_url.hostname)
        ip_obj = ipaddress.ip_address(ip_address)

        for disallowed_range in DISALLOWED_IP_RANGES:
            if ip_obj in ipaddress.ip_network(disallowed_range):
                return False

        # Whitelist specific domains for extra safety
        if not parsed_url.hostname in ALLOWED_DOMAINS:
            return False

        return True
    except Exception:
        return False

def fetch_remote_image(image_url: str):
    if is_safe_url(image_url):
        try:
            response = requests.get(image_url, timeout=5)
            response.raise_for_status()
            return response.content
        except requests.exceptions.RequestException as e:
            print(f"Error fetching image: {e}")
            return None
    else:
        print("Unsafe URL blocked.")
        return None

# Example usage:
# safe_image = fetch_remote_image("https://images.trustedcdn.net/logo.png")
# unsafe_image = fetch_remote_image("http://169.254.169.254/latest/meta-data/")
# unsafe_local = fetch_remote_image("http://localhost:8080/admin")
Attacker Malicious URL Web App Request (internal) Internal Network Boundary Internal Svc / IMDS Mitigation: Input Validation / Egress Firewall
  1. 1Server-Side Request Forgery (SSRF) is a vulnerability where a server is tricked into making requests to an attacker-specified URL.
  2. 2SSRF attacks commonly target internal services, databases, or cloud metadata endpoints to extract sensitive data.
  3. 3Robust input validation using an explicit allowlist of trusted domains or IP addresses is crucial for prevention.
  4. 4Network segmentation, egress filtering, and least privilege IAM roles provide essential defense-in-depth against SSRF.
  5. 5Always assume external user input is malicious and validate thoroughly before using it to initiate server-side connections.