Browse CTFs New CTF Sign in

Cloud Instance Metadata Credential Theft: IMDS Exploitation for IAM Role Token Extraction

forensic_file_artifacts Difficulty 1–5 30 min certifiable

Theory

Why This Matters

AWS Instance Metadata Service (IMDS) credentials appearing in public sources represent one of the highest-impact OSINT findings in cloud security. Security researchers at major bug bounty programs report that IMDS-sourced temporary credentials are the single most common high-severity finding in public GitHub repositories. Threat intelligence analysts tracking cloud-focused threat actors such as Scattered Spider and TeamTNT document systematic scraping of GitHub, Pastebin, and public Docker registries for these credentials as part of initial access operations. A single exposed IMDS credential set can grant an attacker access to an entire AWS account if the attached IAM role has broad permissions — a pattern that has led to data breaches affecting millions of records. Understanding how to identify, validate, and triage these credentials is a core skill for cloud security analysts and incident responders.

Core Concept

The AWS Instance Metadata Service (IMDS) provides EC2 instances with temporary credentials for the IAM role attached to the instance profile. The service is accessible only from within the instance at the link-local address http://169.254.169.254/. When an application running on EC2 calls this endpoint (via curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_NAME), it receives a JSON object containing an AccessKeyId, SecretAccessKey, and SessionToken. These are temporary credentials — they expire and are automatically rotated approximately every six hours by the AWS Security Token Service (STS).

AWS credential prefix identification is the first triage step. Long-term IAM user credentials begin with AKIA (Access Key ID prefix for long-term keys). IMDS-sourced and STS-generated temporary credentials begin with ASIA (the prefix for short-term/session keys). When a SessionToken field is present alongside AccessKeyId and SecretAccessKey, the credential is definitively a temporary STS credential. The presence of an ASIA prefix without a session token in a dump indicates data corruption or partial exposure.

Public OSINT sources for credential exposure include: GitHub repositories (including commit history, which persists after a file is deleted from HEAD); Pastebin and similar paste sites; Shodan-indexed web pages that accidentally serve credential files (e.g., .env files served by misconfigured web servers); public Docker image layers (build history can contain RUN export AWS_SECRET_ACCESS_KEY=... commands); and CI/CD build logs (GitHub Actions, CircleCI, Jenkins) where --debug or verbose logging flags cause environment variables to appear in artifact files stored publicly.

Credential lifetime is critical to OSINT tradecraft. IMDS credentials rotate every ~6 hours. A credential found in a paste from 8 hours ago may already be invalid. The validation step (aws sts get-caller-identity) must be performed promptly, and a negative result does not prove the credential was never valid — it may simply have rotated. Historical exposure still indicates a misconfiguration that warrants investigation.

Pacu is an AWS exploitation framework used to enumerate permissions associated with a discovered credential set. The iam__enum_permissions module attempts to call IAM and service APIs to determine what actions the credential can perform, building a permission map without requiring iam:ListAttachedRolePolicies access.

Technical Deep-Dive

# 1. GitHub search for IMDS credential patterns (using GitHub search API or gh CLI)
gh search code "ASIA" --extension env --limit 50
gh search code "AWS_SESSION_TOKEN" --language python --limit 50

# Google dork equivalents (run in browser):
# site:github.com "ASIA" "AWS_SESSION_TOKEN" "AWS_SECRET_ACCESS_KEY"
# site:pastebin.com "ASia" "SecretAccessKey"

# 2. Identifying credential type from prefix
# Long-term (IAM user): AKIA...  (no SessionToken)
# Temporary (STS/IMDS): ASIA...  (SessionToken required)

# Example exposed credential structure in .env file:
# AWS_ACCESS_KEY_ID=ASIAQGFJ7EXAMPLE1234
# AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
# AWS_SESSION_TOKEN=AQoXnyc4lcK4...

# 3. Validate credential and identify the associated identity
export AWS_ACCESS_KEY_ID="ASIAQGFJ7EXAMPLE1234"
export AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
export AWS_SESSION_TOKEN="AQoXnyc4lcK4..."
aws sts get-caller-identity
# Returns: { "UserId": "AROAEXAMPLE:i-0abc123", "Account": "123456789012",
#            "Arn": "arn:aws:sts::123456789012:assumed-role/EC2Role/i-0abc123" }

# 4. Enumerate permissions with Pacu (post-validation, authorized scope only)
git clone https://github.com/RhinoSecurityLabs/pacu
cd pacu && python3 pacu.py
# In Pacu shell:
# import_keys --access-key ASIA... --secret-key ... --session-token ...
# run iam__enum_permissions

# 5. Search Shodan for accidentally exposed .env files
# Shodan query: http.html:"AWS_SECRET_ACCESS_KEY" http.status:200
# Shodan CLI:
shodan search 'http.html:"AWS_SECRET_ACCESS_KEY"' --fields ip_str,port,http.title

# 6. Scan public Docker image layers for embedded credentials
docker pull targetorg/targetimage:latest
docker history --no-trunc targetorg/targetimage:latest | grep -iE "AWS|SECRET|KEY|TOKEN"

Intelligence Collection Methodology

  1. Use GitHub search (web UI or gh search code) with patterns ASIA, AWS_SESSION_TOKEN, AWS_SECRET_ACCESS_KEY combined with target organization domain or repository names. Search both current code and commit history using tools like truffleHog (trufflehog github --org=targetorg) or git-secrets scanning.
  2. Search Pastebin via Google dorks (site:pastebin.com "ASIA" "company.com") and psbdmp.ws for full-text Pastebin search. Note paste timestamps for credential lifetime assessment.
  3. Query Shodan with http.html:"AWS_SECRET_ACCESS_KEY" http.status:200 to find web servers accidentally serving credential files. Combine with org:"company" or ssl.cert.subject.cn:company.com to scope to the target.
  4. Search public Docker Hub and GitHub Container Registry images associated with the target organization. Use docker history --no-trunc on pulled images to inspect every layer command for embedded credentials.
  5. Check GitHub Actions artifact storage — public repositories sometimes store build logs or artifacts containing debug output with environment variable values. Browse ActionsArtifacts on public repos.
  6. For each discovered credential, identify the type (AKIA = long-term, ASIA = temporary), note the presence of SessionToken, and record the exposure timestamp before validating.
  7. Validate with aws sts get-caller-identity in an isolated, authorized environment. Record the Arn and Account to identify the IAM role and AWS account affected.
  8. If validation succeeds and within authorized scope, run Pacu iam__enum_permissions to map accessible services. Document findings and report immediately given the ~6-hour credential lifetime.

Common Intelligence Collection Errors

  • Assuming an expired IMDS credential means there was no exposure: IMDS credentials rotate every ~6 hours. An InvalidClientTokenId error from aws sts get-caller-identity proves the specific credential is expired, not that the misconfiguration is resolved. The EC2 instance may still be issuing fresh credentials to any requester via SSRF.
  • Confusing AKIA and ASIA prefixes: Treating an ASIA credential as a long-term key leads to incorrect triage. Long-term AKIA keys do not require a session token and do not expire automatically; ASIA keys without a session token are malformed and will fail authentication regardless of age.
  • Validating discovered credentials from a personal or production AWS account: aws sts get-caller-identity with a discovered credential makes an API call that may be logged in the credential owner's CloudTrail. Always validate in an isolated, authorized environment or use an airgapped validation method.
  • Overlooking Docker image layer history: Analysts commonly inspect the final Dockerfile but miss build-time RUN commands that set environment variables in intermediate layers. These credentials are embedded in the image even if not present in the final filesystem.
  • Ignoring the IAM role name in the Arn field: The assumed-role/ROLENAME/SESSION pattern in the Arn from get-caller-identity reveals the IAM role name, which can be correlated back to EC2 instance profiles and infrastructure documentation to scope the impact.
  • Missing CI/CD artifact exposure: Analysts focused on source code often overlook GitHub Actions workflow run logs and downloadable artifact ZIPs on public repositories, which frequently contain verbose build output including injected secrets.

NICE Framework Alignment

Code Knowledge/Skill/Task Statement How This Card Develops It
K0058 Knowledge of network protocols Understanding HTTP link-local IMDS endpoint, AWS STS API calls, and how credential rotation operates over HTTPS
K0145 Knowledge of security assessment approaches Applying systematic multi-source credential discovery across GitHub, Pastebin, Shodan, and Docker registries
K0272 Knowledge of network security architecture Mapping AWS IAM role architecture, instance profiles, and STS trust relationships from discovered credential metadata
K0427 Knowledge of encryption algorithms Distinguishing credential types by prefix (AKIA/ASIA), understanding STS token signing, and session-based authentication
S0040 Skill in identifying and extracting data of interest Locating IMDS-sourced credentials in heterogeneous public sources and extracting associated identity and permission data
T0569 Apply and utilize authorized cyber capabilities to achieve objectives Using truffleHog, Shodan, Pacu, and AWS CLI to validate and enumerate discovered cloud credentials within authorized scope

Further Reading

  • Hacking the Cloud: AWS Penetration Testing — Nick Jones & Scott Piper (online resource, hackingthe.cloud)
  • Cloud Security and DevSecOps Practices — Chapter 9: Credential Management in Cloud Environments (Packt Publishing)
  • AWS Security Best Practices — Amazon Web Services Whitepaper (AWS Documentation, search "AWS Security Best Practices")

Challenge Lab

Reinforce your learning with a hands-on generated challenge based on this card's competency.