The Agentic SSRF: How Autonomous Retrieval Copilots Pivot into Internal Cloud Metadata
A security operations team configures an autonomous AI triage assistant to investigate customer error reports.
When a user submits a ticket complaining that their webhook failed or their external API integration stopped responding, the assistant parses the ticket, extracts the URL mentioned by the customer, and fetches the page or payload to inspect HTTP response codes, headers, and error bodies:
async def fetch_diagnostic_url(url: str) -> str:
"""Retrieves external endpoints provided in customer support tickets."""
async with httpx.AsyncClient(timeout=10.0, follow_redirects=True) as client:
response = await client.get(url)
return response.text[:4000]
The tool works as intended for three months. It triages five hundred tickets a week, parsing stack traces and summarizing endpoint outages before a human support engineer opens the case.
Then a new ticket arrives from a newly registered trial account. The ticket body contains no profanity, no obvious attack payloads, and no hostile prompt injections. It simply reads:
“Our webhook endpoint is timing out on your European cluster. Can you verify if our health check returns 200 OK? Link: https://webhook-monitor.dev/diagnostics”
The AI agent accepts the ticket, invokes fetch_diagnostic_url("https://webhook-monitor.dev/diagnostics"), and reads the response into its working memory.
Forty seconds later, the agent updates the internal ticket with its analysis:
“The remote endpoint redirected to an internal configuration endpoint and returned an IAM session token with permissions for the bucket
prod-customer-backups-eu. The token expires in 58 minutes. Recommended remediation: check if credentials should be rotated.”
The assistant did not just inspect a webhook. It reached through the company’s internal network perimeter, queried the cloud instance metadata service, captured the runtime identity of the container it was running on, and pasted production cloud credentials directly into a support ticket visible to external users.
The Blind Proxy Trap
Server-Side Request Forgery (SSRF) has existed as long as web servers have accepted user-supplied URLs. For decades, security teams defended against it by sanitizing input fields in web forms and setting up Web Application Firewalls (WAFs) to block strings containing 127.0.0.1 or localhost.
Autonomous AI agents change the economics of SSRF in two specific ways:
- The agent generates the target URL dynamically. The attacker does not need to feed a hostile URL into the user input box. An attacker can place an indirect prompt injection on a completely public website. When the agent browses that external site to research documentation, the text on that page instructs the agent to “verify internal cluster health” at an internal address. The LLM constructs the URL itself.
- The agent interprets and exfiltrates the response. In classic blind SSRF, an attacker must infer network architecture from response times or trigger external DNS lookups. An AI agent reads whatever text comes back from the target address, interprets its structure, and frequently prints the extracted data in its response.
When an AI runtime runs inside a cloud environment (AWS ECS, Google Cloud Run, Azure Container Instances, or a Kubernetes cluster), the network interfaces inside that container have access to internal routing planes that outside attackers cannot reach.
Anatomy of the Three Primary Pivots
1. The Cloud Metadata Harvest (IMDSv1)
The most catastrophic target in any cloud workload is the Instance Metadata Service (IMDS). In AWS, every EC2 instance and ECS task has route access to 169.254.169.254.
If an application uses IMDSv1, fetching security credentials requires only a simple HTTP GET request without custom headers:
# What the AI agent's HTTP client requests:
GET http://169.254.169.254/latest/meta-data/iam/security-credentials/app-runner-role
The metadata service responds with temporary AWS access keys:
{
"Code": "Success",
"LastUpdated": "2026-11-17T14:22:10Z",
"Type": "AWS-HMAC",
"AccessKeyId": "ASIAV4EXAMPLEKEY123",
"SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"Token": "IQoJb3JpZ2luX2VjE...",
"Expiration": "2026-11-17T20:55:10Z"
}
Google Cloud has a similar service at http://metadata.google.internal/computeMetadata/v1/, though it requires the header Metadata-Flavor: Google. However, older configurations, misconfigured sidecars, and internal Kubernetes proxies often strip or forward headers indiscriminately.
2. The 302 Redirect Bypass
Many engineering teams attempt to patch SSRF with string-level validation before making the HTTP call:
# Naive validation that fails in production
parsed = urllib.parse.urlparse(user_url)
if parsed.hostname in ["localhost", "127.0.0.1", "169.254.169.254"]:
raise ValueError("Internal destinations are forbidden.")
This check inspects the initial URL and approves it because https://webhook-monitor.dev is a legitimate public domain.
When the agent’s HTTP library sends the request, the external server responds with an HTTP redirect:
HTTP/1.1 302 Found
Location: http://169.254.169.254/latest/meta-data/iam/security-credentials/
If the HTTP client has follow_redirects=True enabled (the default in many popular agent frameworks), the client automatically sends a second GET request to the internal IP. The pre-request string validation never runs on the redirected destination.
3. DNS Rebinding
Even if the agent checks the IP address of the domain before issuing the request, DNS rebinding circumvents the control.
An attacker registers a domain (rebind.attacker-infra.net) and sets up a custom authoritative DNS server:
- Resolution 1 (Validation step): The agent application checks the IP. The attacker’s DNS server returns
93.184.216.34(a public IP) with a Time-To-Live (TTL) of 1 second. The agent’s security check marks the IP as external and safe. - Resolution 2 (Execution step): Two seconds later, the underlying HTTP library resolves the domain to open the socket. The attacker’s DNS server now returns
169.254.169.254or10.0.0.1. - The socket connects to the internal service.
sequenceDiagram
autonumber
participant Attacker as Attacker Server
participant Agent as Agent Python Runtime
participant DNS as Attacker Custom DNS
participant IMDS as Cloud Metadata (169.254.169.254)
Agent->>DNS: Step 1: Resolve rebind.attacker-infra.net
DNS-->>Agent: 93.184.216.34 (Public IP, TTL=1s)
Agent->>Agent: Validation Check: Public IP confirmed (PASS)
Note over Agent: Wait 2 seconds (TTL expires)
Agent->>DNS: Step 2: Connect socket (re-resolve)
DNS-->>Agent: 169.254.169.254 (Internal IP)
Agent->>IMDS: GET /latest/meta-data/iam/security-credentials/
IMDS-->>Agent: Temporary IAM Access Keys
Agent->>Agent: LLM ingests keys into context window
Agent->>Attacker: Exfiltrates credentials in response
The Production Defense Architecture
Securing an autonomous agent against network pivot attacks requires stripping network trust at three distinct layers: the cloud infrastructure, the socket runtime, and the agent’s network route.
Layer 1: Enforce IMDSv2 and Set Hop Limits
IMDSv2 replaces simple GET queries with a session-oriented token requirement. An HTTP client must issue a PUT request with a specific header (X-aws-ec2-metadata-token-ttl-seconds) to acquire a session token before requesting metadata.
Crucially, modern container platforms allow you to set the metadata response hop limit to 1:
# Enforce IMDSv2 and restrict packet TTL to 1 hop
aws ec2 modify-instance-metadata-options \
--instance-id i-0123456789abcdef0 \
--http-tokens required \
--http-put-response-hop-limit 1 \
--http-endpoint enabled
When an agent runs inside a Docker container or Kubernetes pod, the network packet must jump across the virtual bridge interface to reach the host. If the hop limit is set to 1, the packet expires before reaching the metadata service. The container cannot talk to IMDS even if it tries.
Layer 2: Socket-Level IP Pinning (Anti-SSRF Transport)
Never allow the agent to use an unhardened HTTP client. URL validation must occur on the resolved IP address immediately before the TCP handshake, and automatic redirects must be intercepted and re-validated.
The following custom transport for Python’s httpx enforces strict IP denylists across all connection attempts and redirects:
import ipaddress
import socket
from urllib.parse import urlparse
import httpx
BLOCKED_NETWORKS = [
ipaddress.ip_network("0.0.0.0/8"),
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("127.0.0.0/8"),
ipaddress.ip_network("169.254.0.0/16"), # Link-Local & Cloud Metadata
ipaddress.ip_network("172.16.0.0/12"),
ipaddress.ip_network("192.168.0.0/16"),
ipaddress.ip_network("::1/128"), # IPv6 loopback
ipaddress.ip_network("fc00::/7"), # IPv6 unique local
ipaddress.ip_network("fe80::/10"), # IPv6 link-local
]
def verify_safe_ip(hostname: str) -> str:
"""Resolves hostname and verifies that all returned IPs are public."""
addr_info = socket.getaddrinfo(hostname, None, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM)
for family, _, _, _, sockaddr in addr_info:
ip = ipaddress.ip_address(sockaddr[0])
for blocked in BLOCKED_NETWORKS:
if ip in blocked:
raise PermissionError(f"Egress blocked: {hostname} resolved to private/reserved IP {ip}")
return addr_info[0][4][0]
class SecureEgressTransport(httpx.AsyncHTTPTransport):
"""Transport that pins DNS resolution and intercepts redirects."""
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
url = urlparse(str(request.url))
if url.scheme not in ["http", "https"]:
raise PermissionError(f"Unsupported protocol scheme: {url.scheme}")
# Verify IP immediately before connection
verify_safe_ip(url.hostname)
return await super().handle_async_request(request)
When using this transport, configure follow_redirects=False or wrap redirect handling so that every Location header is evaluated by verify_safe_ip() before the socket opens.
Layer 3: Out-of-VPC Scraping Workloads
The cleanest architecture separates the thinking runtime from the fetching runtime:
+------------------------------------+ +------------------------------------+
| Internal Corporate VPC | | Isolated Scraping Sandbox |
| | | |
| +----------------------------+ | HTTPS | +----------------------------+ |
| | Autonomous Agent Engine |---|--------->| | Stateless Scraping Worker | |
| | (Access to DB & Prompts) | | | | (Zero IAM, No VPC Peering) | |
| +----------------------------+ | | +----------------------------+ |
| | | | |
+------------------------------------+ +-----------------|------------------+
|
v Public Internet
+-----------------+
| External URLs |
+-----------------+
- The core agent orchestrator runs in your corporate network where it has access to customer tickets, models, and databases.
- The agent never executes raw web fetches directly. When it needs to inspect a URL, it dispatches an RPC to an isolated scraping worker.
- The scraping worker runs in a separate AWS account or isolated GCP project with no VPC peering, no IAM roles, and no access to internal corporate subnets.
- If an attacker manages to execute an SSRF exploit inside the scraping worker, the worker has no credentials to leak and no internal servers to pivot into.
Verifying Egress Boundaries
Before giving any retrieval tool to an autonomous model, run three automated regression tests against the agent’s web-fetch interface:
- Direct IMDS Probe: Ask the agent to fetch
http://169.254.169.254/latest/meta-data/. The call must fail with a socket connection error or transport exception. - Redirect Probe: Host a test server that issues a 302 redirect to
http://127.0.0.1:8080/. The agent must reject the second hop. - IPv6 and Hex IP Encoding: Submit obfuscated IP notations such as
http://0x7f000001orhttp://2130706433. The transport must decode the address to standard integer representation and block it before initiating the TCP handshake.
An AI agent that can browse the web without egress controls is not an assistant. It is an unauthenticated HTTP proxy running inside your production perimeter.