Advanced·20 min read·Updated 2026-10-15

SSRF (Server-Side Request Forgery): Detection, Impact & Prevention

Original WeSecureX guide for authorized testing of sites you own. Linked Sources are citations for verification - not copied articles. Ads are not served on this page.

Server-Side Request Forgery (SSRF, CWE-918) occurs when a web application receives an untrusted URL from a user and fetches data from that destination using server-side network privileges without adequate validation. In cloud hosting environments (AWS, GCP, Azure), SSRF is routinely weaponized by threat actors to query link-local metadata endpoints (`http://169.254.169.254`), steal temporary IAM role credentials, query internal Consul or Redis datastores, and pivot through private Virtual Private Cloud (VPC) subnets. Traditional blocklists (such as checking for 'localhost' or '127.0.0.1') fail completely against decimal IP encodings, IPv6 transitions, and Time-of-Check to Time-of-Use (TOCTOU) DNS rebinding attacks. In this guide, we break down SSRF mechanics, demonstrate socket-level IP validation, and explore automated detection using the [WeSecureX Website Vulnerability Scanner](/scanner), [Surface Reconnaissance](/surface), and [Vulnerabilities Catalog](/vulnerabilities). Learn more about enterprise breaches in [The Anatomy of a Data Breach](/blog/the-anatomy-of-a-data-breach-how-attackers-find-and-exploit-vulnerabilities).

Quick Answer

Prevent SSRF by enforcing strict HTTPS protocol allowlists, resolving DNS prior to connection to verify the target IP does not fall within private CIDR subnets (RFC 1918, link-local 169.254.0.0/16, or loopback), pinning the verified IP in HTTP socket options, enforcing AWS IMDSv2 with session tokens, and disabling automated HTTP redirects.

Key Takeaways
  • SSRF allows attackers to use your server as a proxy to attack internal networks and cloud metadata.
  • Cloud metadata credential theft via IMDSv1 is the highest-severity SSRF risk in cloud environments.
  • Regex URL filtering fails against DNS rebinding and IP encoding tricks; always resolve and check IPs.
  • Enforce IMDSv2 and restrict VPC egress to block metadata access at the infrastructure layer.
Visual Diagram · SSRF Cloud Metadata Exploitation & Egress Defense Flow
1

1. Malicious Input

Attacker submits URL parameter ?url=http://169.254.169.254/latest/meta-data/ to webhook endpoint.

2

2. DNS Resolution Check

Server resolves target hostname and checks IP against blocked RFC1918 and link-local subnets.

3

3. Private Range Rejection

Server detects IP 169.254.169.254 belongs to metadata link-local range and aborts request immediately.

4

4. IMDSv2 Session Guard

AWS IMDSv2 requires PUT header token, neutralizing any secondary GET-based SSRF attempts.

ShareShare on XLinkedIn

1. SSRF Attack Vectors & Cloud Metadata Theft

WeSecureX Automated Vulnerability Scanner detecting SSRF and cloud metadata exfiltration vectors
WeSecureX Automated Vulnerability Scanner detecting SSRF and cloud metadata exfiltration vectorsWeSecureX Platform View

Server-Side Request Forgery (SSRF) vulnerabilities emerge whenever an application feature accepts a destination URL from an untrusted client and executes an outbound network request using server-side privileges. Typical vulnerable components include custom webhook notification dispatchers, PDF invoice generators that render remote stylesheets, social media link preview crawlers, profile avatar import tools, and data synchronization proxies. Because the outgoing request originates from the application server's trusted IP address inside the corporate VPC, perimeter firewalls and security groups treat the traffic as internal and authorized, effectively transforming the application server into an unintended proxy for the attacker.

In modern cloud infrastructure (AWS EC2, Google Cloud Compute Engine, Microsoft Azure Virtual Machines), SSRF represents a catastrophic threat vector. By default, cloud hypervisors expose a link-local metadata IP address (169.254.169.254) accessible from any process running on the host instance. Under legacy implementations like AWS IMDSv1, this endpoint requires zero authentication. An attacker who supplies http://169.254.169.254/latest/meta-data/iam/security-credentials/ into a vulnerable URL parameter can extract the temporary IAM role credentials (AccessKeyId, SecretAccessKey, and Token) assigned to the cloud instance. With these credentials in hand, the attacker can connect directly to the cloud provider's management APIs from their external machine, granting them full administrative control over internal S3 buckets, RDS databases, and serverless Lambda functions.

Beyond cloud metadata exploitation, SSRF enables adversaries to map internal networks and interact with unauthenticated administrative microservices. Threat actors routinely target internal database instances such as Redis (port 6379), Memcached (port 11211), Elasticsearch (port 9200), and Apache Solr (port 8983). By crafting specialized payloads or leveraging protocols like gopher://, attackers can issue arbitrary write commands to internal key-value stores, overwrite serialized application sessions, or trigger secondary Remote Code Execution (RCE) vulnerabilities. Even in Blind SSRF scenarios - where the server fetches the target URL but does not return the response body to the user - adversaries measure network connection latency to perform internal port scanning and discover hidden internal services.

Audit your public web applications and API endpoints against cloud metadata exfiltration using the WeSecureX Website Vulnerability Scanner and inspect perimeter assets on Attack Surface Reconnaissance. Check our technical breakdown of Common Website Vulnerabilities and How to Prevent Them.

2. Production-Safe DNS & IP Resolution Code Pattern

WeSecureX Attack Surface Recon mapping internal and external service perimeters
WeSecureX Attack Surface Recon mapping internal and external service perimetersWeSecureX Platform View

Attempting to defend against SSRF by validating user-supplied URLs using regular expressions alone is fundamentally insecure. Attackers bypass string-based filters using alternative IP encodings - such as decimal integers (http://2130706433 for 127.0.0.1), hexadecimal notation (http://0x7f000001), octal values (0177.0.0.1), or enclosed alphanumeric Unicode homoglyphs. A regex that looks for 127.0.0.1 or localhost will trivially pass these obfuscated strings, allowing the underlying HTTP client library to resolve the address and trigger an internal request.

A far more dangerous bypass technique is DNS Rebinding, which exploits a classic Time-of-Check to Time-of-Use (TOCTOU) race condition. In a DNS rebinding attack, an attacker registers a custom domain name (such as attacker-domain.com) configured with a custom DNS nameserver that serves responses with a Time-to-Live (TTL) of 0 seconds. When the application server executes its validation logic, it performs a DNS lookup; the nameserver responds with a legitimate public IP address (such as 93.184.216.34). Because the IP is public, the validation check passes. However, a few milliseconds later, when the application's HTTP client opens a TCP socket to execute the request, the socket library performs a second DNS query because the TTL has expired. At this instant, the attacker's nameserver responds with 169.254.169.254 or 127.0.0.1, coercing the server into connecting directly to the restricted internal metadata endpoint.

To build an impenetrable SSRF defense, engineering teams must implement a two-phase socket pinning architecture:

  1. Strict Protocol Allowlisting: Permit only https: (or http: if explicitly necessary). Disallow dangerous URI schemes such as file://, gopher://, dict://, and ftp://.
  2. Authoritative DNS Resolution: Perform asynchronous DNS lookups using the host operating system's DNS resolver to extract all associated IPv4 and IPv6 addresses.
  3. CIDR Subnet Validation: Verify that none of the resolved IP addresses fall within RFC 1918 private address spaces (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), loopback ranges (127.0.0.0/8, ::1), link-local metadata space (169.254.0.0/16, fe80::/10), or multicast blocks.
  4. Transport Socket Pinning: Pass the pre-validated IP address directly into the HTTP client socket options (or custom agent lookup function) to ensure that the outgoing TCP connection connects exclusively to the verified IP without performing a second DNS query.

Verify your DNS records and network configuration with the WeSecureX DNS Record Lookup and test exposed services using the Open Port Scanner.

typescript
// Secure SSRF Validation Helper in TypeScript / Node.js
import dns from 'node:dns/promises';
import net from 'node:net';

const PRIVATE_SUBNETS = [
  /^127\./,                        // IPv4 Loopback
  /^10\./,                         // Class A Private (RFC 1918)
  /^172\.(1[6-9]|2[0-9]|3[0-1])\./,// Class B Private (RFC 1918)
  /^192\.168\./,                   // Class C Private (RFC 1918)
  /^169\.254\./,                   // Link-Local & AWS Metadata
  /^0\./,                          // Current Network
  /^::1$/,                         // IPv6 Loopback
  /^fc00:/i,                       // IPv6 Unique Local
  /^fe80:/i,                       // IPv6 Link-Local
];

export async function validateUrlForSsrf(rawUrl: string): Promise<string> {
  const parsed = new URL(rawUrl);

  // 1. Enforce HTTPS protocol strictly
  if (parsed.protocol !== 'https:') {
    throw new Error('Only HTTPS protocol is permitted');
  }

  // 2. Reject raw IP literals in hostname
  if (net.isIP(parsed.hostname)) {
    throw new Error('Direct IP addresses are prohibited');
  }

  // 3. Resolve DNS to verify actual IP address
  const { address } = await dns.lookup(parsed.hostname);

  // 4. Verify resolved IP is not in private or metadata subnets
  const isPrivate = PRIVATE_SUBNETS.some((regex) => regex.test(address));
  if (isPrivate || address === '0.0.0.0') {
    throw new Error('Target IP resolves to a restricted private/metadata subnet');
  }

  return parsed.toString();
}

3. Enforcing IMDSv2 & Network Egress Controls

WeSecureX Free Tools Directory showing security scanners and diagnostic utilities
WeSecureX Free Tools Directory showing security scanners and diagnostic utilitiesWeSecureX Platform View

Application-level URL validation must be reinforced with robust infrastructure network boundaries. If a software defect or third-party dependency vulnerability bypasses application filters, defensive network controls provide an impassable backstop. A defense-in-depth security model ensures that even if an attacker manages to trigger an arbitrary HTTP request, the network architecture prevents unauthorized egress and metadata exfiltration.

The cornerstone of modern cloud metadata defense is enforcing AWS IMDSv2 across all virtual machines and container instances. Unlike IMDSv1, which accepts simple unauthenticated GET requests, IMDSv2 is a session-oriented protocol that requires callers to first issue an HTTP PUT request with an X-aws-ec2-metadata-token-ttl-seconds header to acquire a temporary cryptographic session token. Subsequent metadata queries must include this token in an X-aws-ec2-metadata-token header. Because most SSRF vulnerabilities are restricted to standard GET or POST verbs and cannot forge custom PUT headers across cross-origin boundaries, IMDSv2 completely neutralizes metadata exfiltration. Furthermore, setting HttpPutResponseHopLimit to 1 ensures that containerized applications (such as Docker or Kubernetes pods running on EC2) cannot access the host instance's metadata endpoint.

In addition to IMDSv2, enterprise architectures must enforce strict egress firewall controls and network segmentation. Application servers residing in private subnets should have no direct route to the public internet or link-local subnets; outbound internet connectivity should be mediated through forward proxies or NAT Gateways with strict domain allowlists. Webhook dispatchers and URL crawlers should be isolated into dedicated, ephemeral worker containers operating inside isolated DMZ subnets that have zero network connectivity to internal database clusters, Redis caches, or management planes.

Finally, server-side HTTP fetch clients must be configured to disable automatic HTTP redirect following (setting redirect: 'manual' or maxRedirects: 0). If an application validates that an initial URL (such as https://example.com) points to a legitimate public IP, but automatically follows HTTP 301 or 302 redirects, an attacker can configure the external server to issue a redirect toward http://169.254.169.254. Unless redirect destinations are recursively validated against private IP allowlists, the application will follow the redirect directly into internal infrastructure.

Audit your HTTP headers with the Security Headers Checker and learn how continuous testing protects modern applications in Securing Modern Web Applications: The Shift to Continuous Testing.

Tip

Always disable automatic HTTP redirects in server-side fetch libraries. An allowlisted URL (https://trusted.com) can return a 301 redirect to http://169.254.169.254, bypassing initial validation if redirects are followed automatically.

Apply it with WeSecureX

Where your app fetches a user-supplied URL, WeSecureX points that parameter at an internal address on a target you own. SSRF is confirmed when the server fetches the internal resource on your behalf.

URL parameter aimed inward

http
POST /api/fetch HTTP/1.1
Host: yoursite.com

{ "url": "http://169.254.169.254/latest/meta-data/" }

Response that returns internal data

http
HTTP/1.1 200 OK
{ "body": "iam/\nhostname\n..." }
What the finding shows

The finding records the parameter, the internal target, and the metadata the server echoed back. That echo is the proof the request left your boundary inward.

Fix: allowlist hosts, block internal ranges

javascript
const u = new URL(input);
if (!ALLOWED_HOSTS.has(u.hostname)) throw new Error('blocked');
if (isPrivateIp(u.hostname)) throw new Error('blocked');

After the rescan

Rescan the same endpoint. The internal URL is now rejected before any fetch, and the finding clears.

Checks that belong with this topic

  • Never fetch arbitrary user-supplied URLs without validation.
  • Enforce explicit hostname allowlists for external API integrations.
  • Resolve DNS and verify resolved IPs are not in RFC1918 or 169.254.0.0/16 subnets.
  • Disable automatic HTTP redirect following in server fetch clients.
  • Enforce AWS IMDSv2 across all cloud EC2 instances.
  • Audit URL fetch parameters using the [WeSecureX Security Scanner](/scanner).

Actionable Checklist

WeSecureX Platform · Scanner Engine

Automated Vulnerability Scanner

Launch targeted or full-domain security audits to detect OWASP Top 10 vulnerabilities automatically.

Includes: OWASP Top 10 automated test suites · Real-time severity scoring (CVSS v3.1) · Instant remediation code snippets

Frequently Asked Questions

IMDSv2 is an AWS metadata service configuration that requires callers to send an HTTP PUT request with a X-aws-ec2-metadata-token-ttl-seconds header to obtain a session token before requesting metadata. Because basic SSRF attacks can only send simple GET requests, IMDSv2 neutralizes metadata credential theft.

DNS Rebinding is an attack where an attacker configures a domain name to return a public IP during initial DNS validation, but immediately returns 127.0.0.1 or 169.254.169.254 when the application connects milliseconds later.

If an application validates that https://trusted-site.com is public, but follows HTTP redirects automatically, trusted-site.com can issue a 301 redirect to http://169.254.169.254, causing the server to fetch metadata.

A WAF can block known payload strings (like 169.254.169.254), but it cannot prevent SSRF triggered via domain names that resolve to internal IPs or DNS rebinding. Application IP validation is mandatory.

Run an authenticated scan using the [WeSecureX Security Scanner](/scanner) to test all URL parameters against out-of-band callback targets.

Authoritative Sources & References

  • OWASP - Server-Side Request Forgery Prevention Cheat SheetOWASP (official)
    View Source
  • AWS EC2 - Configuring the Instance Metadata Service (IMDSv2)AWS (official)
    View Source

Continue exploring related technical architecture and defensive guides

Security Research & Engineering Articles

All articles