Ravindra BagaleCourses & study guides

30. Cloud and AWS Security

30.6 EC2 Metadata, SSRF and a Leaked-Key Incident Checklist

Every EC2 instance can read its own metadata at http://169.254.169.254/. If the instance has a role, temporary credentials for that role are available there. In Chapter 29 you learned SSRF: if a vulnerable app fetches a URL the attacker controls, the attacker can make it fetch the metadata address and steal the role credentials.

The defence is IMDSv2. IMDSv2 requires a session token obtained with a PUT request first, which simple SSRF bugs cannot send.

# On your own EC2 instance: IMDSv2 way (token first)
TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 60")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id

# From your laptop: force IMDSv2 on the instance
aws ec2 modify-instance-metadata-options --instance-id i-0abc123example \
  --http-tokens required --http-endpoint enabled

After this, a plain curl http://169.254.169.254/latest/meta-data/ without a token returns 401 Unauthorized. Also give the role only the permissions it needs (30.2), so even stolen credentials can do little.

Incident checklist – "My access key leaked"

  1. Deactivate the key immediately (IAM, Users, Security credentials, Make inactive), then delete it and create a new one if still needed.
  2. Check CloudTrail for everything that key did: new users, new keys, new EC2 instances in any region, changed policies.
  3. Delete anything the attacker created (check all regions – attackers love regions you never use).
  4. Rotate other secrets that key could read (SSM, Secrets Manager).
  5. Remove the key from Git history, not just the latest commit; treat it as compromised forever.
  6. Open an AWS Support case if you see unexpected charges, and review the bill.

Ravindra Bagale's Tip

When a key leaks, students first delete the commit on GitHub. Wrong order! First deactivate the key – then everything else. Even if you remove it from Git, bots may already have copied it.

Lab

On your own EC2 instance, try the metadata URL without a token and with the IMDSv2 token. Then set --http-tokens required and show that the no-token request now fails. Write the leaked-key checklist on one page and keep it with your notes.

AWS account security checklist

Area Must-do
Root MFA on, no access keys, used rarely
IAM MFA for all humans, least privilege, roles for EC2, regular credential report
Network No 0.0.0.0/0 on admin/database ports, private subnets for RDS, Session Manager
Data Account-level S3 Block Public Access, encryption on, versioning, secrets in SSM/Secrets Manager
Detection Multi-region CloudTrail, GuardDuty, billing alarm, VPC Flow Logs
EC2 IMDSv2 required, sudo yum update regularly