Detecting and Fixing Metadata Credential Theft
Suppose the SSRF of the previous lesson worked: an attacker made the web tier fetch …/security-credentials/app-role and now holds a valid access key ID, secret and session token for the instance's role. Nothing on the instance looks different, and the credentials are genuine, so authentication won't fail. What gives the theft away is where and how the credentials are used. This lesson builds that detection over synthetic CloudTrail events, then walks through the response: cut off the stolen session, close the hole, and shrink what any future stolen session could do.
What instance credentials look like in the logs
When an EC2 instance uses its role, CloudTrail records an assumed-role identity whose session name is the instance ID:
userIdentity.type AssumedRole
userIdentity.arn arn:aws:sts::123456789012:assumed-role/app-role/i-0a1b2c3d4e5f60001
userIdentity.accessKeyId ASIA… (changes whenever the instance credentials rotate, several times a day)
sourceIPAddress 10.10.0.70 (through a VPC endpoint) or the NAT gateway's public address
vpcEndpointId vpce-0a1b2c3d (when the call went through one)That gives a strong invariant: calls made with an instance's credentials should come from that instance's network path. Its private address via a VPC endpoint, or the NAT gateway's public address for calls that go out through the Internet. A call with the same session from any other address means the credentials left the instance. GuardDuty implements this as UnauthorizedAccess:IAMUser/InstanceCredentialExfiltration.OutsideAWS (used from outside AWS) and .InsideAWS (used from another AWS account); you can implement it yourself from CloudTrail.
Two other traces help:
- Web, WAF and proxy logs containing
169.254.169.254,metadata,latest/meta-dataor encoded variants in parameters: the SSRF attempt itself (SSRF detection). - The
MetadataNoTokenmetric rising on an instance whose own software uses IMDSv2: someone else is making v1 requests. (VPC flow logs don't record traffic to169.254.169.254, so don't look for it there.)
The detection
instances = { # instance id -> addresses its API calls may legitimately come from
"i-0a1b2c3d4e5f60001": {"10.10.0.70", "198.51.100.5"}, # private IP (via endpoint), NAT gateway EIP
"i-0a1b2c3d4e5f60002": {"10.10.0.71", "198.51.100.5"},
}
events = [
("09:00:12", "assumed-role/app-role/i-0a1b2c3d4e5f60001", "ASIAEXAMPLE0000000A1", "s3:PutObject", "10.10.0.70", "vpce-0a1b2c3d"),
("09:03:40", "assumed-role/app-role/i-0a1b2c3d4e5f60002", "ASIAEXAMPLE0000000B1", "s3:PutObject", "10.10.0.71", "vpce-0a1b2c3d"),
("09:05:02", "assumed-role/app-role/i-0a1b2c3d4e5f60001", "ASIAEXAMPLE0000000A1", "sts:GetCallerIdentity", "203.0.113.66", None),
("09:05:30", "assumed-role/app-role/i-0a1b2c3d4e5f60001", "ASIAEXAMPLE0000000A1", "s3:ListBuckets", "203.0.113.66", None),
("09:06:11", "assumed-role/app-role/i-0a1b2c3d4e5f60001", "ASIAEXAMPLE0000000A1", "s3:GetObject", "203.0.113.66", None),
("09:06:15", "assumed-role/app-role/i-0a1b2c3d4e5f60001", "ASIAEXAMPLE0000000A1", "s3:GetObject", "203.0.113.66", None),
("09:07:00", "assumed-role/app-role/i-0a1b2c3d4e5f60001", "ASIAEXAMPLE0000000A1", "s3:PutObject", "198.51.100.5", None),
("09:20:44", "assumed-role/ci-deploy/gh-run-4411", "ASIAEXAMPLE0000000C1", "ec2:RunInstances", "192.0.2.44", None),
]
alerts, first_bad = [], {}
for t, arn, key, action, ip, vpce in events:
session = arn.split("/")[-1]
if not session.startswith("i-"):
continue # not an instance session: other rules apply
allowed = instances.get(session, set())
if ip not in allowed:
first_bad.setdefault(key, t)
alerts.append(f"{t} {session} key {key} used from {ip} ({action}); expected {sorted(allowed)}")
for a in alerts:
print("ALERT", a)
for key, t in first_bad.items():
print(f"\nscope: session key {key}, first misuse {t}; actions from outside:",
sorted({e[3] for e in events if e[2] == key and e[4] not in instances[e[1].split('/')[-1]]}))ALERT 09:05:02 i-0a1b2c3d4e5f60001 key ASIAEXAMPLE0000000A1 used from 203.0.113.66 (sts:GetCallerIdentity); expected ['10.10.0.70', '198.51.100.5']
ALERT 09:05:30 i-0a1b2c3d4e5f60001 key ASIAEXAMPLE0000000A1 used from 203.0.113.66 (s3:ListBuckets); expected ['10.10.0.70', '198.51.100.5']
ALERT 09:06:11 i-0a1b2c3d4e5f60001 key ASIAEXAMPLE0000000A1 used from 203.0.113.66 (s3:GetObject); expected ['10.10.0.70', '198.51.100.5']
ALERT 09:06:15 i-0a1b2c3d4e5f60001 key ASIAEXAMPLE0000000A1 used from 203.0.113.66 (s3:GetObject); expected ['10.10.0.70', '198.51.100.5']
scope: session key ASIAEXAMPLE0000000A1, first misuse 09:05:02; actions from outside: ['s3:GetObject', 's3:ListBuckets', 'sts:GetCallerIdentity']
The legitimate calls of both instances (through the endpoint, or from the NAT address) raise nothing, and the CI session is left to other rules. The same session key of instance …001 used from 203.0.113.66 raises four alerts: the attacker checked whose credentials they had, listed buckets and downloaded two objects. The scope line is the start of the investigation: one session key, a start time, and the actions to follow up (which objects were read, from which bucket).
Response
- Revoke the stolen session. Temporary credentials can't be deactivated like access keys, so AWS revokes them with a policy: attaching a deny on everything for sessions issued before now (
"Condition": {"DateLessThan": {"aws:TokenIssueTime": "<now>"}}) to the role. The console's "Revoke active sessions" does exactly that. The instance simply fetches new credentials and keeps working; the attacker's copy stops. - Close the hole: require IMDSv2 with hop limit 1 on the instance and its launch template, and fix the SSRF itself (allow-list, no redirects).
- Scope the damage from CloudTrail: everything done with the stolen key ID and any credentials it created; S3 data events for object-level reads (only if they were enabled).
- Shrink the role to what the application uses, and add a network perimeter so the role's credentials only work from the VPC (Private Endpoints and Egress).
The second step of that last point is powerful enough to deserve a model of its own: a condition on the role that denies use outside the account's network makes stolen instance credentials useless even before anyone notices.
from datetime import datetime
REVOKED_BEFORE = datetime(2026, 5, 4, 9, 30)
def decide(call):
# 1. revocation: deny sessions issued before the revoke time
if call["token_issued"] < REVOKED_BEFORE:
return "DENY (session revoked, aws:TokenIssueTime)"
# 2. network perimeter on the role: deny unless via our endpoint or from our NAT address
if call.get("vpce") != "vpce-0a1b2c3d" and call["ip"] not in {"198.51.100.5"}:
return "DENY (outside network perimeter)"
return "ALLOW"
calls = [
("attacker, stolen session (issued 08:55)", dict(token_issued=datetime(2026, 5, 4, 8, 55), ip="203.0.113.66")),
("instance, old session (issued 08:55)", dict(token_issued=datetime(2026, 5, 4, 8, 55), ip="10.10.0.70", vpce="vpce-0a1b2c3d")),
("instance, refreshed session (issued 09:31)", dict(token_issued=datetime(2026, 5, 4, 9, 31), ip="10.10.0.70", vpce="vpce-0a1b2c3d")),
("attacker steals the new session (09:31)", dict(token_issued=datetime(2026, 5, 4, 9, 31), ip="203.0.113.66")),
]
for label, c in calls:
print(f"{label:44} {decide(c)}")attacker, stolen session (issued 08:55) DENY (session revoked, aws:TokenIssueTime)
instance, old session (issued 08:55) DENY (session revoked, aws:TokenIssueTime)
instance, refreshed session (issued 09:31) ALLOW
attacker steals the new session (09:31) DENY (outside network perimeter)
Revocation alone stops the copy the attacker already has, and briefly the instance's own old session (SDKs refresh credentials and recover). It doesn't stop a new theft through the same hole; the network perimeter does, which is why it belongs in the permanent fix and not only in the incident.
Pitfalls
- Matching only
sourceIPAddressagainst the instance's private IP: calls through the NAT gateway legitimately show its public address, and some AWS services call on the role's behalf (sourceIPAddresslikes3.amazonaws.com); include those in the allowed set. - Revoking sessions but leaving IMDSv1 on: the attacker fetches fresh credentials a minute later.
- Forgetting other credential sources with the same exposure: ECS task-role endpoints (
169.254.170.2), Lambda environment credentials, and the metadata servers of Azure and GCP.
Practice
1. Add an event where instance …002's key is used from 10.10.0.70 (instance …001's address). Is it an alert, and is that right?
Yes, an alert: …002's credentials should only appear from 10.10.0.71 or the NAT address. It probably means code on …001 obtained …002's credentials (or a mapping error), and is worth investigating either way.
2. Why does the scope line include sts:GetCallerIdentity, which reads nothing?
Because it is the attacker's first move, made by almost every tool that receives credentials, and its timestamp and source address are often the earliest evidence. It needs no permission and can't be denied by IAM policies, so it always appears.
3. Write the condition for the network perimeter in IAM policy terms.
A Deny on * with "Condition": {"StringNotEqualsIfExists": {"aws:SourceVpce": "vpce-0a1b2c3d"}, "NotIpAddressIfExists": {"aws:SourceIp": "198.51.100.5/32"}, "BoolIfExists": {"aws:ViaAWSService": "false"}}, attached to the role (or as an SCP or RCP for all instance roles). Conditions are ANDed, so the deny applies only when none of the allowed paths match. For instance credentials specifically, AWS also adds the global keys aws:Ec2InstanceSourceVpc and aws:Ec2InstanceSourcePrivateIPv4 to their requests, so a perimeter can compare them with aws:SourceVpc and aws:VpcSourceIp instead of listing addresses (AWS's data-perimeter guidance shows this pattern).
Test yourself
How can you recognise an EC2 instance's role session in CloudTrail?
- Its access key starts with AKIA
- The session name in the assumed-role ARN is the instance ID
- It has no userIdentity
- It is always in us-east-1
What is the invariant behind the detection?
- Instances never call S3
- An instance's credentials should only be used from that instance's network path (private IP via endpoint, or its NAT address)
- Credentials expire after 5 minutes
- Only root can use roles
How are stolen temporary role credentials revoked?
- Delete the access key
- Attach a deny for sessions with aws:TokenIssueTime before now
- Reboot the instance
- They can't be
Why is revocation alone not a fix?
- It doesn't work
- The attacker can steal a fresh session through the same hole; IMDSv2 and a network perimeter are needed
- It breaks the instance permanently
- It deletes CloudTrail