Back to Blog
Cloud IAM Security

From SSRF to RCE: A Masterclass in Cloud Metadata Exploitation

OffSec Research Team
10 June 2026 • 09:00 AM16 min
From SSRF to RCE: A Masterclass in Cloud Metadata Exploitation
TL;DR — In the cloud, a humble Server-Side Request Forgery (SSRF) is rarely "just" an SSRF. If the vulnerable workload runs on a cloud instance with an attached role, SSRF against the Instance Metadata Service (IMDS) can hand the attacker temporary IAM credentials. From there, over-permissioned roles convert credential theft into lateral movement, privilege escalation, and ultimately remote code execution across the account. This article traces the full path, contrasts IMDSv1 with IMDSv2, and explains the defences that break the chain.

Executive Summary

The 2019 Capital One breach made one lesson permanent: in cloud environments, SSRF is a credential-theft primitive. An attacker who can make a server issue an HTTP request of their choosing can target the link-local metadata endpoint (169.254.169.254) that every major cloud exposes to its instances. That endpoint, by design, serves the instance's identity — including, in AWS, the temporary security credentials of the IAM role attached to the instance.

Those credentials are the keys to the kingdom's anteroom. What the attacker can do next depends entirely on the role's policy. In a least-privilege world, stolen instance credentials might let an attacker read one S3 bucket. In the real world, instance roles are routinely over-permissioned, and the path from "I have your instance's credentials" to "I run code as you across the account" is short.

What Is SSRF, Precisely?

SSRF occurs when an application takes a URL (or a component of one) from user input and makes a server-side request to it, without adequately validating the destination. The classic vulnerable patterns:

  • A "fetch this image/URL" feature (webhooks, link previews, PDF/screenshot generators).
  • An import-from-URL or document-conversion service.
  • A misconfigured reverse proxy or an API gateway that forwards a user-controlled url= parameter.
python
# VULNERABLE: user controls the destination of a server-side request@app.route("/fetch")def fetch():    url = request.args.get("url")        # attacker-controlled    resp = requests.get(url)             # no allow-list, no validation    return resp.text

The danger is that the request originates from the server, inside the trust boundary. It can reach internal services, admin panels, and — the prize — the cloud metadata endpoint, none of which are reachable from the public internet.

The Metadata Endpoint

Every cloud instance can query a non-routable, link-local address for information about itself:

CloudMetadata baseCredential path (role/identity)
AWShttp://169.254.169.254/latest/meta-data/iam/security-credentials/<role>
GCPhttp://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token
Azurehttp://169.254.169.254/metadata/instanceidentity/oauth2/token (IMDS)

The endpoint is a feature: it is how an instance discovers its region, its tags, its user-data startup script, and — crucially — its credentials, so that SDKs can authenticate to cloud APIs without hard-coded keys. That convenience is exactly what SSRF turns against the victim.

IMDSv1: The Easy Path

On a cloud using the legacy IMDSv1 (a simple, unauthenticated GET request), the SSRF-to-credentials step is trivial:

text
# 1. Discover the role nameGET /fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/   → AppServerRole # 2. Retrieve the temporary credentialsGET /fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/AppServerRole   {    "AccessKeyId": "ASIA...",    "SecretAccessKey": "wJalr...",    "Token": "IQoJb3JpZ2lu...",    "Expiration": "2026-05-15T20:00:00Z"  }

The attacker now possesses a valid AccessKeyId/SecretAccessKey/Token triple. They export it into their own AWS CLI and operate as the instance role from anywhere on the internet, until the token expires (typically a few hours — but new ones are always available via the same SSRF).

diagram — rendering…
flowchart TD
    A["Attacker finds SSRF<br/>in /fetch?url="] --> B["Point it at<br/>169.254.169.254"]
    B --> C["IMDSv1: GET role creds<br/>(no auth required)"]
    C --> D["Temporary IAM credentials<br/>AccessKey + Secret + Token"]
    D --> E["Use creds with aws-cli<br/>from attacker machine"]
    E --> F{"What can the<br/>role do?"}
    F -->|Over-permissioned| G["Privilege escalation<br/>+ lateral movement"]
    G --> H["Remote Code Execution<br/>across the account"]
    style C fill:#2a0c14,stroke:#ef233c,color:#fee2e2
    style H fill:#2a0c14,stroke:#ef233c,color:#fee2e2

IMDSv2: Partial Protection

AWS introduced IMDSv2 as a direct response to SSRF credential theft. It is session-oriented: a client must first PUT a request to obtain a short-lived token, then include that token as a header on subsequent GETs.

text
# Step 1 — obtain a session token (note: PUT, with a TTL header)PUT /latest/api/tokenX-aws-ec2-metadata-token-ttl-seconds: 21600  → AQAAA... (the token) # Step 2 — use the token on the metadata GETGET /latest/meta-data/iam/security-credentials/AppServerRoleX-aws-ec2-metadata-token: AQAAA...

Two properties make IMDSv2 meaningfully harder for SSRF to abuse:

  • It requires a PUT with a custom header. Most SSRF primitives only let an attacker perform simple GETs; they cannot set arbitrary request headers or change the method.
  • A default `PUT` response hop limit of 1. The X-Forwarded-For-style hop restriction (TTL/hop limit on the IP packet) means responses do not traverse to containers behind a proxy hop, frustrating some container-based SSRF.

IMDSv2 is not a panacea — a full-request SSRF (one that lets the attacker set the method and headers, e.g. some proxy or gopher:// primitives) can still complete the dance. But it converts the most common, simplest SSRF from a one-line credential theft into a much harder problem. Enforcing IMDSv2 (and disabling v1) is the single highest-leverage control here.

From Credentials to RCE

Stealing credentials is the midpoint, not the end. The role's permissions decide what happens next. Here is a representative escalation path that ends in code execution — none of it requires a new vulnerability, only an over-broad policy.

diagram — rendering…
flowchart LR
    A["Stolen instance<br/>role creds"] --> B["enumerate:<br/>sts get-caller-identity<br/>iam list-attached-*"]
    B --> C{"Dangerous<br/>permissions?"}
    C -->|"iam:PassRole +<br/>ec2:RunInstances"| D["Launch new EC2 with<br/>a high-priv role"]
    C -->|"ssm:SendCommand"| E["Run commands on<br/>existing instances"]
    C -->|"lambda:UpdateFunctionCode"| F["Backdoor a Lambda<br/>with a powerful role"]
    D & E & F --> G["Code execution as a<br/>more privileged identity"]
    G --> H["Persist, exfiltrate,<br/>or reach Org admin"]
    style G fill:#2a0c14,stroke:#ef233c,color:#fee2e2

Concrete examples of "credentials → RCE":

  • `ssm:SendCommand` — AWS Systems Manager lets you run shell commands on any managed instance. If the stolen role can call it, the attacker executes commands as root/SYSTEM on other servers directly, no exploit needed.
  • `iam:PassRole` + `ec2:RunInstances` — launch a new instance and attach a far more privileged role to it; the new box runs attacker user-data with that role's power.
  • `lambda:UpdateFunctionCode` — overwrite an existing Lambda's code; it executes with the function's (often generous) execution role.
  • `iam:CreatePolicyVersion` / `iam:AttachUserPolicy` — directly grant yourself AdministratorAccess if the role can edit IAM.
text
PRIVILEGE-ESCALATION-ENABLING PERMISSIONS (by how often they appear over-granted) iam:PassRole              ████████░░  extremely commonssm:SendCommand           ██████░░░░  common on managed fleetslambda:UpdateFunctionCode ████░░░░░░  common in serverless estatesiam:* / Administrator     ███░░░░░░░  worryingly frequent on "app" rolesec2:RunInstances          █████░░░░░  common

GCP and Azure: The Same Pattern, Different Locks

AWS gets the attention because of Capital One, but every major cloud exposes a metadata service, and each has its own quirks that change how exploitable an SSRF is.

Google Cloud Platform. GCP's metadata server lives at metadata.google.internal (and 169.254.169.254). Critically, it requires a custom request header — Metadata-Flavor: Google — for sensitive endpoints. This is GCP's analogue to IMDSv2's header requirement: a plain GET-only SSRF that cannot set headers will be rejected. Where an SSRF can influence headers, the path to the service-account OAuth token is direct:

text
GET /computeMetadata/v1/instance/service-accounts/default/tokenMetadata-Flavor: Google  → { "access_token": "ya29...", "expires_in": 3599, "token_type": "Bearer" }

That bearer token then authenticates to Google Cloud APIs with the service account's scopes. The legacy ?recursive=true and the old X-Google-Metadata-Request allowances widened this surface historically; modern GCP enforces the header.

Microsoft Azure. Azure's Instance Metadata Service (IMDS) also requires the header Metadata: true and refuses requests that arrive with an X-Forwarded-For header — a deliberate anti-SSRF control, since proxies add that header. The managed-identity token endpoint is the prize:

text
GET /metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/Metadata: true  → { "access_token": "eyJ0...", "resource": "https://management.azure.com/" }
CloudHeader requiredBlocks X-Forwarded-ForSession/token model
AWS IMDSv1nonenoDirect GET (most exposed)
AWS IMDSv2X-aws-ec2-metadata-token (via PUT)hop-limitSession token, PUT-first
GCPMetadata-Flavor: Googlen/aHeader-gated
Azure IMDSMetadata: trueyesHeader-gated

The common thread: the clouds that require a custom header are meaningfully harder to exploit via simple GET-only SSRF. This is exactly why moving AWS workloads to IMDSv2 closes the gap — it brings AWS in line with the header-gated model that GCP and Azure adopted from the start.

Blind SSRF and Out-of-Band Techniques

Not every SSRF returns the response body to the attacker. Blind SSRF — where you can make the server issue a request but cannot read the result — is still dangerous, and several techniques convert it into a usable primitive:

  • Out-of-band confirmation. Point the SSRF at an attacker-controlled domain and watch for the DNS/HTTP callback to confirm the vulnerability exists, even when the response is hidden.
  • DNS rebinding. Bypass an application-layer allow-list that validates the hostname at check time but resolves it again at use time. The attacker's DNS server returns a benign IP for the validation request, then flips to 169.254.169.254 for the actual fetch (a TOCTOU on name resolution). The defence is to resolve once and connect to that resolved IP, and to deny link-local/private ranges post-resolution.
  • Redirect-based bypass. If the app validates the initial URL but follows redirects, point it at an attacker server that 302-redirects to the metadata endpoint. Defences must re-validate the destination after every redirect.
  • Protocol smuggling (`gopher://`, `dict://`). Some SSRF primitives (notably via certain libraries or via curl) support protocols that let the attacker craft arbitrary TCP payloads — including a full HTTP request with custom method and headers. This is the technique that can defeat even IMDSv2/GCP/Azure header gating, because the attacker controls the entire request, not just a URL.
diagram — rendering…
flowchart TD
    A["Blind SSRF found"] --> B{"Response readable?"}
    B -->|No| C["OOB callback to confirm"]
    C --> D{"Allow-list present?"}
    D -->|"validated once"| E["DNS rebinding /<br/>redirect bypass"]
    D -->|"GET-only block"| F["gopher:// protocol<br/>smuggling → full request"]
    E & F --> G["Reach metadata endpoint"]
    style G fill:#2a0c14,stroke:#ef233c,color:#fee2e2

The takeaway for testers: never dismiss a blind SSRF as low severity in a cloud context. The combination of OOB confirmation and one of the bypass techniques routinely escalates "the server made a DNS request" into "the server handed me its IAM token."

A Concrete Walkthrough

  • The attacker finds a link-preview feature that fetches arbitrary URLs.
  • They confirm SSRF by pointing it at a server they control and observing the callback.
  • They target 169.254.169.254. If IMDSv1 is enabled, credentials come back immediately. If IMDSv2 is enforced and the SSRF is GET-only, this step fails — chain broken.
  • With credentials, aws sts get-caller-identity confirms the role; aws iam list-attached-role-policies enumerates permissions.
  • They discover the role has ssm:SendCommand. They issue a command document that runs a reverse shell on a database instance.
  • From the database instance they harvest secrets, pivot, and work toward organisation-wide control.

The entire path used one application bug (SSRF) and one configuration weakness (an over-permissioned, IMDSv1-reachable role).

Detection

SourceIndicator
Application / proxy logsOutbound requests to 169.254.169.254 or metadata.google.internal originating from a web app
VPC Flow LogsInstance making metadata calls it never made before (rare baseline deviation)
CloudTrailInstance-role credentials used from an IP outside the VPC / from a foreign region
CloudTrailsts:GetCallerIdentity, mass iam:List*/Describe* recon shortly after, then ssm:SendCommand or RunInstances
GuardDutyUnauthorizedAccess:IAMUser/InstanceCredentialExfiltration finding
High-fidelity signal: AWS records a credential's "binding" to an instance. When instance-role credentials appear in CloudTrail being used from an external IP, that is near-conclusive evidence of exfiltration — GuardDuty raises exactly this finding. Alert on it with priority.

Defence in Depth

The chain has multiple independent break points — implement several:

  • Enforce IMDSv2 and disable IMDSv1. Set instance metadata options to http-tokens: required. This neutralises the most common GET-only SSRF credential theft outright.
  • Set the metadata hop limit to 1 (and to a higher value only where containers genuinely need it). This prevents containerised SSRF from reaching IMDS through a network hop.
  • Least-privilege instance roles. An app server's role should grant exactly the S3 prefix / queue / parameter it needs — never iam:*, ssm:SendCommand, or iam:PassRole unless specifically required and tightly scoped.
  • Block egress / validate destinations at the app layer. Allow-list the hosts your SSRF-prone feature may contact; explicitly deny link-local (169.254.0.0/16), private RFC1918 ranges, and metadata hostnames. Re-resolve and re-check after redirects to defeat DNS-rebinding.
  • Detect credential exfiltration. Enable GuardDuty (or equivalent) and alert on instance credentials used off-instance.
  • Scope conditions on roles. Use aws:SourceVpc/aws:SourceIp policy conditions so credentials are useless outside the expected network.

IMDSv2 Bypasses and Extended Pivoting

IMDSv2 substantially raises the bar for credential theft via SSRF, but it does not eliminate the threat. Understanding exactly where IMDSv2's protections hold — and where they break — is essential both for testers assessing cloud environments and for defenders deciding what controls to prioritise.

What IMDSv2 Actually Protects Against

IMDSv2's two key properties are:

  • A PUT request is required first — most simple GET-only SSRF primitives cannot complete the token exchange.
  • A configurable hop limit (default: 1) — the IP TTL on the token-exchange response is decremented at each hop, so responses do not traverse one network hop in the response path. A containerised workload sitting one hop behind a host-level proxy therefore cannot reach IMDSv2 by default.

This means IMDSv2 cleanly defeats a basic requests.get(user_controlled_url) SSRF: an application that only issues GET requests cannot do the prerequisite PUT to obtain the session token.

IMDSv2 Bypass Conditions

The protection fails in four recognisable scenarios:

1. The SSRF primitive supports arbitrary HTTP methods and headers.

If the vulnerable application uses a library or utility that supports PUT (e.g. curl, a proxy configured to pass through arbitrary methods, or an SSRF in a server-side scripting context where the attacker controls the full request), the attacker can complete the IMDSv2 dance:

bash
# Step 1 — PUT to get session token (attacker-controlled via full-request SSRF)curl -s -X PUT "http://169.254.169.254/latest/api/token" \     -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"# → AQAAAxxxxxxxxxxxxxxxx (session token) # Step 2 — GET credentials using the tokencurl -s -H "X-aws-ec2-metadata-token: AQAAAxxxxxxxxxxxxxxxx" \     "http://169.254.169.254/latest/meta-data/iam/security-credentials/AppServerRole"

SSRF primitives backed by gopher:// are especially powerful here because gopher:// lets an attacker craft the entire TCP payload, including custom HTTP methods and headers that a standard SSRF filter might not anticipate:

text
gopher://169.254.169.254:80/_PUT%20/latest/api/token%20HTTP/1.0%0D%0AX-aws-ec2-metadata-token-ttl-seconds:%2021600%0D%0A%0D%0A

2. IMDSv1 is still enabled.

AWS does not disable IMDSv1 by default when IMDSv2 is configured — it must be explicitly set to http-tokens: required. Many existing instances were launched before IMDSv2 existed and never had the setting updated. The AWS-recommended Terraform pattern to enforce this:

hcl
resource "aws_instance" "example" {  ami           = "ami-0abcdef1234567890"  instance_type = "t3.micro"   metadata_options {    http_endpoint               = "enabled"    http_tokens                 = "required"   # enforces IMDSv2; disables v1    http_put_response_hop_limit = 1            # prevent container traversal  }}

An audit command to find non-enforced instances across a region:

bash
aws ec2 describe-instances --query \  "Reservations[*].Instances[?MetadataOptions.HttpTokens!='required'].[InstanceId,Tags[?Key=='Name'].Value|[0]]" \  --output table

3. The hop limit is set above 1 for containerised workloads.

When http_put_response_hop_limit is set to 2 or higher (commonly done to allow containers running on an EC2 host to access IMDS), the TTL-based hop restriction is relaxed. A container running on such a host can reach IMDS through the bridge network, and any SSRF in a containerised service can again complete the full IMDSv2 flow.

4. An IMDSv2-aware SSRF exists in the application.

Some applications deliberately access IMDS themselves — for instance, to pull the instance's region, tags, or user-data at startup. If the code path that makes the IMDS call is itself injectable (e.g. the URL is derived from configuration that an attacker can influence), the application's own IMDSv2-capable client becomes the tool of the attack.

Chaining SSRF to Broader Account Pivots

Once IAM credentials are in hand, the post-exploitation surface depends on the full cloud account graph, not just the role attached to the compromised instance. The following pivot patterns extend compromise beyond the initial EC2 workload:

Enumerating other accounts in an AWS Organisation:

bash
# Check if the role can assume roles in other accountsaws sts get-caller-identityaws organizations list-accounts              # requires org:ListAccountsaws iam list-roles | grep AssumeRole        # find cross-account trust policies # Attempt to assume a role in a spoke accountaws sts assume-role \    --role-arn arn:aws:iam::TARGET_ACCOUNT_ID:role/OrganizationAccountAccessRole \    --role-session-name pivot

Pivoting via EC2 Instance Connect or SSM:

If the role has ssm:StartSession or ec2-instance-connect:SendSSHPublicKey, the attacker can open interactive shell sessions on other instances without any network path between their machine and the target:

bash
# SSM shell to a different instance — no inbound network access neededaws ssm start-session --target i-0abc123def456789 # EC2 Instance Connect: push an ephemeral SSH key to any instanceaws ec2-instance-connect send-ssh-public-key \    --instance-id i-0abc123def456789 \    --instance-os-user ec2-user \    --ssh-public-key file://~/.ssh/id_rsa.pub

Cross-service pivots worth checking for:

PermissionWhat it enablesPivot target
secretsmanager:GetSecretValueRead DB passwords, API keys, TLS certsEvery downstream service trusting those secrets
rds:DescribeDBInstances + VPC accessEnumerate and connect to RDS databasesData exfiltration, lateral movement
ecs:UpdateService + ecs:RegisterTaskDefinitionRewrite a container task definition with a malicious imageCode execution in ECS with the task's role
eks:UpdateClusterConfig / kubectl via aws eks get-tokenInteract with Kubernetes APIK8s cluster takeover if RBAC is misconfigured
codecommit:GitPullRead application source codeSecrets in source, understanding architecture
s3:GetObject on sensitive bucketsRead backups, config dumps, credential filesHigh-value data theft

The pattern across all of these is the same: the initial SSRF steals an IAM token, and from that token, a least-privilege enumeration reveals the horizontal blast radius available. In practice, "over-permissioned" instance roles are the rule rather than the exception, so a single SSRF routinely opens a lateral movement path to multiple services, accounts, or even the full AWS Organisation.

Conclusion and Takeaways

The SSRF-to-RCE cloud chain is the defining attack pattern of the IaaS era because it weaponises two things every cloud account has: a metadata service that hands out credentials, and IAM roles that are almost always broader than they need to be. The application bug (SSRF) is the spark; the over-permissioned role is the fuel. Remove either and the fire goes out.

For builders, the priorities are unambiguous: enforce IMDSv2, rigorously scope instance roles to least privilege, and validate the destination of every server-side request with an allow-list that explicitly excludes link-local and private ranges. For defenders, the single most valuable alert you can configure is "instance-role credentials seen from outside the instance's network" — it catches the exact moment a metadata SSRF becomes a breach. Treat every SSRF finding in a cloud workload not as a medium-severity web bug, but as a potential account takeover, and you will prioritise it correctly.