Table of Contents

What Is Server Side Request Forgery?

3 min. read

Server-side request forgery ranks seventh on the OWASP API Security Top 10 for good reason. In this type of cyberattack, attackers turn your application server into a proxy, reaching internal resources your firewall was built to protect. Cloud infrastructure, microservices architectures, and webhook integrations have made SSRF both more common and more dangerous. Inside, you'll find how SSRF attacks work, real-world exploitation techniques, business impact analysis, identification methods, and concrete prevention strategies for cloud-native environments.

API7:2023 - Server Side Request Forgery Explained

Server-side request forgery transforms your application server into an attacker's proxy. An attacker submits a URL to your API, and your server fetches the resource at that location, presenting a critical failure in API security, as the request originates from inside your network perimeter. It carries all the trust and access privileges your server possesses.

Traditional perimeter defenses offer zero protection against SSRF. Your firewall blocks external actors from reaching internal services, but your own application server sits behind that firewall with full access. VPNs segment your network from the public internet, yet your server operates within that trusted boundary. When your server makes the malicious request, security controls see legitimate internal traffic from an authorized system.

The vulnerability stems from a deceptively simple oversight: accepting user-supplied URLs without rigorous validation. Your API receives a string claiming to be an image location, a webhook endpoint, or a data source. Your server parses the URL and initiates an HTTP request. The attacker controls the destination.

Amplified Risk in Cloud-Native Architectures

Modern application development patterns have made SSRF dramatically more prevalent. Webhooks enable integrations between services by accepting external URLs for callbacks. File fetching functionality pulls resources from user-specified locations. Custom SSO implementations redirect to authentication providers. URL preview features generate rich embeds for links. Each pattern involves your server making requests based on user input.

Cloud infrastructure compounds the danger. AWS, Azure, and GCP expose metadata services at well-known addresses like 169.254.169.254. These endpoints serve instance credentials, configuration details, and sensitive environment data. Kubernetes and Docker publish management APIs over HTTP at predictable paths. Container orchestration platforms place administrative controls within network reach of compromised services.

The connected architecture of microservices creates extensive attack surfaces. Services communicate across internal networks using REST APIs and gRPC channels. A single vulnerable endpoint in one service can pivot to internal resources across your entire infrastructure. Rate limiting and egress filtering become complex when legitimate application behavior involves constant outbound connections to dynamic destinations.

Understanding Server Side Request Forgery in API Security

SSRF exploits the trust relationship between your application server and the resources it accesses. The attack manipulates legitimate application functionality to reach destinations the attacker couldn't access directly.

The Basic Attack Flow

When an API endpoint accepts a URL parameter as part of normal operations, your server parses the string, initiates an HTTP or HTTPS request to the specified destination, and processes the response. The attacker exploits this by crafting a malicious URL pointing to internal infrastructure, cloud metadata endpoints, or other protected resources.

Your server executes the request using its own network context and credentials, meaning the target system receives a connection from what appears to be a trusted internal source. Response data flows back through your server to the attacker, while the entire exchange masquerades as legitimate internal traffic to monitoring systems and security controls.

Port scanning becomes trivial through SSRF, as attackers submit URLs targeting sequential ports on internal hosts. Response timing and status codes reveal which ports accept connections. A quick 200 response indicates an open service, connection timeouts suggest filtered ports, while explicit rejection messages expose closed ports.

Development Patterns That Create SSRF Exposure

Webhook implementations accept callback URLs from external systems. Your API validates the webhook registration by sending a test request to verify ownership. Security products integrate with SIEMs through webhook endpoints. CI/CD pipelines trigger builds via webhook notifications. Each integration point accepts a URL and makes a server-side request.

File fetching from URLs powers user-facing features across applications. Social networks allow profile picture uploads via URL. Document management systems import files from remote locations. Content aggregators pull articles from RSS feeds. E-learning platforms embed resources from external hosts.

Custom SSO implementations retrieve identity provider metadata from user-specified endpoints. OAuth flows redirect to authorization servers. SAML configurations fetch XML metadata from IdP URLs. OpenID Connect discovers provider configurations through well-known endpoints.

URL preview generation creates rich embeds for shared links across multiple platforms. Messaging platforms fetch Open Graph metadata, collaboration tools render link previews in comments, and marketing platforms generate social media cards from article URLs.

Infrastructure Vulnerabilities in Cloud Environments

Cloud metadata services expose sensitive information over HTTP without authentication. AWS places instance metadata at 169.254.169.254, Azure uses 169.254.169.254 for the Instance Metadata Service, and GCP serves metadata through metadata.google.internal—with each endpoint providing instance credentials, user data, and configuration details.

Kubernetes exposes the API server to pods within the cluster, where default service accounts grant basic cluster access. The kubelet API runs on port 10250 with varying authentication requirements, while etcd stores cluster state and often listens on port 2379.

Docker daemon APIs accept HTTP requests when configured for remote management, container metadata endpoints reveal environment variables and configuration, and service meshes like Istio expose control planes on internal networks.

The Outbound Traffic Dilemma

Legitimate application behavior requires constant outbound connectivity. Microservices call external APIs for payment processing, email delivery, and data enrichment, SaaS integrations connect to dozens of third-party platforms, and content delivery networks serve static assets from distributed locations. Blocking outbound traffic breaks core functionality across modern application architectures.

How Server Side Request Forgery Manifests in Real-World APIs

Attackers weaponize SSRF through reconnaissance, credential theft, and privilege escalation. Each technique exploits your server's position inside network boundaries.

Internal Network Reconnaissance

Response timing reveals open ports without direct access to internal systems, allowing attackers to submit URLs targeting sequential ports on internal IP addresses. When connecting to an active service, the response returns quickly with HTTP status codes or error messages, while closed ports generate immediate TCP resets, and filtered ports cause request timeouts after several seconds.

Once port scans succeed, mapping network topology becomes possible through multiple reconnaissance techniques. DNS responses for internal hostnames expose naming conventions, sequential IP scanning identifies active hosts on internal subnets, and banner grabbing through partial HTTP responses reveals service versions and technologies.

Service discovery builds on topology mapping. Standard ports indicate common services: 3306 for MySQL, 5432 for PostgreSQL, 6379 for Redis, 9200 for Elasticsearch. Management interfaces run on predictable ports: 8080 for Jenkins, 9090 for Prometheus, 3000 for Grafana.

Cloud Metadata Exploitation

Because AWS Instance Metadata Service v1 responds to HTTP requests without authentication, an SSRF vulnerability allows fetching IAM role credentials from http://169.254.169.254/latest/meta-data/iam/security-credentials/, with the response including AccessKeyId, SecretAccessKey, and SessionToken carrying the instance's full permissions."

While Azure Instance Metadata Service requires a specific header, it still accepts requests from the local instance, and GCP metadata endpoints serve project information, service account tokens, and SSH keys. Each cloud provider structures metadata differently, yet all expose sensitive configuration through HTTP.

Session tokens obtained through metadata endpoints grant immediate cloud API access. An attacker uses stolen AWS credentials to enumerate S3 buckets, modify security groups, or launch additional instances. Azure tokens enable resource group access. GCP service account credentials permit BigQuery queries or Compute Engine control.

Bypassing Access Controls Through Trusted Position

Admin panels behind firewall rules become accessible when your server makes the request, since internal monitoring dashboards, database management tools, and configuration interfaces trust connections from application servers. This trusted position allows an attacker to view sensitive metrics, modify system settings, or extract data through your server's legitimate access.

Service mesh architectures trust internal traffic by default. Microservices authenticate external requests but accept internal calls without verification. An SSRF vulnerability in one service provides access to the entire mesh.

Attack Scenarios in Production Environments

When profile picture upload functionality accepts image URLs, an attacker can submit localhost:8080 as the picture location, using response timing to determine whether an internal service runs on that port. By iterating through common ports, they systematically map the internal attack surface.

Webhook registration includes test request functionality. An attacker configures a webhook pointing to the cloud metadata service, causing your server to fetch instance credentials during webhook validation and display the response, leaking IAM tokens directly to the attacker.

Document import features pull files from remote URLs. An attacker specifies file://etc/passwd or internal file share paths. Your server reads local filesystem resources or accesses internal network storage.

The Business Impact of Server Side Request Forgery

SSRF vulnerabilities translate directly into quantifiable business damage. Cloud credential theft, data breaches, and compliance failures follow exploitation.

Credential Exposure Creates Immediate Cloud Account Access

Stolen IAM credentials from cloud metadata services grant attackers the same permissions your compute instances possess, meaning an EC2 instance with S3 full access effectively hands over complete storage control. Service account tokens further enable resource creation, modification, and deletion across your entire cloud environment.

API keys and database passwords stored in environment variables leak through metadata endpoints. Attackers authenticate to external APIs using your organization's credentials. Production database access follows from exposed connection strings.

Perimeter Security Becomes Irrelevant

Firewalls restrict inbound traffic, but your server initiates outbound connections freely. An attacker reaches admin panels, monitoring systems, and internal APIs through your application's legitimate network position. VPN requirements mean nothing when your server already operates inside the protected network.

Zero-trust architectures face challenges when service-to-service authentication relies on network location. Internal microservices trust connections from other internal sources. SSRF bypasses authentication layers designed for external threats.

Data Breach Through Internal Access

Customer records, financial data, and intellectual property sit on internal systems designed for trusted access only. SSRF provides that trusted position. Attackers query internal databases, download from file shares, and extract data from business intelligence platforms.

Healthcare organizations face HIPAA violations when protected health information leaks. Financial institutions breach PCI DSS requirements through unauthorized cardholder data access. GDPR penalties apply when personal data exposure results from inadequate security controls.

Lateral Movement Across Infrastructure

Initial SSRF exploitation establishes a foothold for broader compromise. Attackers enumerate internal systems, identify additional vulnerabilities, and move laterally across your infrastructure.

Container orchestration APIs enable cluster takeover, while service mesh access spreads compromise to all connected microservices. What begins as a single vulnerable endpoint quickly escalates into infrastructure-wide control.

Service Disruption Through Resource Exhaustion

Malicious requests target internal services with denial-of-service attacks, using your application server to flood databases with queries, overwhelm message queues, or crash monitoring systems.

Production services degrade or fail entirely as a result, creating operational incidents that appear to originate from legitimate internal infrastructure.

Third-Party Integration Compromise

Webhooks configured through SSRF redirect sensitive event data to attacker-controlled endpoints. Customer notifications, security alerts, and business-critical events stream to malicious destinations.

Supply chain attacks propagate when compromised webhooks affect partner integrations, extending the breach beyond your organization's boundaries.

Identifying Server Side Request Forgery in Your APIs

Testing for SSRF requires systematic analysis of URL-accepting endpoints and deliberate attempts to reach protected resources.

Input Analysis and Attack Surface Mapping

Catalog every API endpoint that accepts URL parameters. Profile upload features, document import functions, webhook registration, and link preview generation all deserve scrutiny. GraphQL mutations accepting URL arguments expand the attack surface beyond REST endpoints.

Review query parameters, JSON request bodies, and HTTP headers for URL fields. Parameter names like url, webhook_url, callback, image_url, fetch_from, and remote_resource signal potential SSRF vectors. Hidden or undocumented parameters sometimes accept URLs without proper validation.

Trace data flow from input acceptance through request execution. Identify the HTTP client library making outbound requests. Determine whether redirects receive automatic following. Check for timeout configurations that might reveal port scanning through response timing.

Manual Testing Approaches

Begin by submitting localhost addresses in URL parameters, trying 127.0.0.1, 0.0.0.0, and [::1] for IPv6, while internal IP ranges like 10.0.0.0/8, 172.16.0.0/12, and 192.168.0.0/16 target private networks.

Test cloud metadata endpoints directly. AWS metadata at http://169.254.169.254/latest/meta-data/ returns instance information if accessible. Azure's Instance Metadata Service requires the Metadata:true header but may respond to SSRF requests. GCP uses http://metadata.google.internal/computeMetadata/v1/.

Port scanning through timing analysis reveals internal services when you submit URLs targeting common ports: 22 for SSH, 3306 for MySQL, 6379 for Redis, 8080 for alternate HTTP. Fast responses with valid HTTP indicate open services, connection timeouts suggest filtered ports, while immediate rejections mark closed ports.

Alternative URL schemes bypass HTTP restrictions. The file:// protocol reads local filesystem resources. The gopher:// scheme crafts arbitrary TCP requests. The dict:// protocol queries dictionary servers. Some HTTP libraries support ftp://, ldap://, and sftp:// schemes.

Bypass Technique Testing

URL encoding obfuscates malicious destinations. Convert 127.0.0.1 to decimal notation: http://2130706433/. Use hexadecimal: http://0x7f.0x0.0x0.0x1/. Octal representations work in some parsers: http://0177.0000.0000.0001/.

DNS rebinding attacks exploit time-of-check-time-of-use vulnerabilities. A controlled DNS server returns a legitimate IP for validation, then switches to an internal IP for the actual request.

Redirect following bypasses allow-list restrictions. A permitted external URL redirects to internal resources. The server follows the redirect automatically, reaching protected endpoints.

Parser inconsistencies create exploitation opportunities. Different URL parsing libraries handle edge cases differently. Test with multiple @ symbols, unusual ports, and malformed authority sections.

Automated Detection Methods

SSRF scanners like SSRFmap automate payload generation and response analysis. Burp Suite's Collaborator detects blind SSRF through DNS and HTTP callbacks. Out-of-band techniques use attacker-controlled domains to receive requests even when responses don't return to the client.

Preventing Server Side Request Forgery: Best Practices

SSRF prevention requires defense in depth across network architecture, input validation, and response handling. Complete elimination proves difficult, so organizations must balance security controls against business requirements.

Network-Level Isolation

Deploy resource fetching functionality in dedicated network segments with restricted egress rules. Assume URL-accepting features will retrieve external resources exclusively. Internal resource access should flow through separate, authenticated channels.

Egress filtering blocks connections to private IP ranges, localhost addresses, and cloud metadata endpoints. Configure firewall rules to deny outbound traffic to 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, and 169.254.169.254/32. Block link-local addresses in IPv6: fe80::/10 and ::1/128.

Service accounts for URL-fetching components need minimal permissions. An image upload service requires S3 write access but shouldn't hold production database credentials. Separate IAM roles by function to limit credential exposure through metadata theft.

Input Validation Through Allowlists

Remote origin allowlists restrict fetching to known, trusted domains. Define specific hosts for each feature: cdn.example.com for image hosting, drive.google.com for document imports, api.partner.com for webhook integrations. Reject requests to unlisted domains.

URL scheme restrictions prevent protocol smuggling. Allow only https:// for production systems. HTTP might be acceptable in development environments but introduces downgrade risks. Block file://, gopher://, dict://, ftp://, and other schemes entirely.

Port allowlists enforce standard HTTPS on port 443. Some legitimate use cases require ports 80, 8080, or 8443. Document each exception with a business justification. Deny all other ports to prevent port scanning.

Media type validation ensures requested resources match expected formats. Image upload endpoints should accept image/jpeg, image/png, and image/webp. Webhook integrations expect application/json. Reject responses with unexpected Content-Type headers.

URL Handling Implementation

Robust URL parsing libraries prevent exploitation through malformed input. Use well-maintained parsers like Python's urllib.parse, Java's java.net.URI, or Node's url module. Avoid regex-based validation or custom parsing logic.

URL normalization standardizes input before validation. Convert Unicode characters to ASCII. Resolve encoded representations like %6C%6F%63%61%6C%68%6F%73%74 to localhost. Decode double-encoded sequences. Apply normalization consistently across validation and fetching stages.

The following creates bypass opportunities. Disable automatic redirect following in HTTP client libraries. If redirects serve legitimate purposes, revalidate the redirect target URL against allowlists before following.

Input sanitization removes dangerous characters and patterns. Strip credentials from URLs like http://user:pass@internal.host. Reject URLs containing @ symbols outside proper authority sections. Eliminate null bytes and control characters.

Response Data Filtering

Raw response data leaking to clients enables information disclosure. Parse responses, extract required fields, and construct sanitized response objects. An image upload feature needs only a success status, not the complete HTTP response from the storage service.

Response size limits prevent resource exhaustion and data exfiltration. Cap response bodies at reasonable thresholds based on expected content. Image uploads might allow 10MB maximum. Webhook test requests need only a few kilobytes.

Timeout configurations balance functionality against abuse. Set aggressive timeouts on URL fetching operations: 5-10 seconds for most use cases. Longer timeouts enable port scanning through timing analysis.

Enhanced Defense Measures

DNS resolution controls block requests to private IPs even when specified as hostnames. Resolve the hostname before making the HTTP request. Reject destinations resolving to internal ranges. Be aware that DNS rebinding can bypass single-resolution checks.

Request logging captures outbound traffic for security monitoring. Log destination URLs, response codes, and timing data. Alert on requests to suspicious destinations like metadata endpoints or internal IP ranges.

Proxy services centralize external resource fetching. Route all outbound requests through a proxy that enforces validation and logging. Squid, Privoxy, or cloud-native solutions like AWS PrivateLink provide intermediary control points.

Server Side Request Forgery FAQs

Blind SSRF occurs when your server makes requests to attacker-specified URLs but doesn't return the response data. Attackers still achieve reconnaissance through timing analysis, trigger internal actions, or exfiltrate data through DNS queries. Detection requires out-of-band monitoring since traditional response inspection reveals nothing about successful exploitation.
DNS rebinding exploits the time gap between URL validation and actual request execution. An attacker's DNS server returns a legitimate IP address during validation checks, then switches to an internal IP address when your server makes the real request. The attack bypasses validation based on initial DNS resolution.
Instance Metadata Service version 2 adds session-based authentication to AWS metadata endpoints. Applications must first request a session token via PUT, then include that token in subsequent metadata requests. IMDSv2 mitigates SSRF attacks because attackers can't forge the required PUT request through simple URL manipulation in vulnerable endpoints.
Out-of-band exfiltration transmits stolen data through channels separate from the primary attack vector. An attacker uses DNS queries, ICMP packets, or HTTP requests to attacker-controlled servers. SSRF vulnerabilities enable out-of-band techniques when response data doesn't return directly, allowing blind exploitation to still extract sensitive information successfully.
TOCTOU vulnerabilities exist when validation happens separately from resource access. Your API validates a URL at one moment, then fetches the resource later. Between these actions, an attacker modifies DNS records, redirects change, or the destination shifts. The fetched resource differs from what validation approved, bypassing security controls.
URL parser differentials arise from inconsistent parsing logic across libraries and languages. One parser extracts "example.com" as the hostname while another identifies "internal.local" from the same malformed URL. Attackers craft URLs that pass validation in your parser but resolve differently in the HTTP client library making actual requests.
Previous What Is API Security?
Next What Is API Endpoint Security