Leaked Access Keys: Scanning and Response
Long-lived cloud access keys leak through the same few doors again and again: committed to a repository, baked into a container image, pasted into a ticket or chat, left in a laptop's ~/.aws/credentials that gets backed up somewhere public. Once a key is in a public place, it is found fast: automated scrapers watch public code hosting continuously, and researchers who planted canary keys report first use within minutes. Providers scan too (AWS, for example, scans public GitHub for its keys and attaches a quarantine policy to keys it finds), but that is a safety net, not a control. This lesson covers both halves: finding keys before anyone else does, and responding when one is out.
What a key looks like
| Credential | Shape | Notes |
|---|---|---|
| AWS access key ID | AKIA + 16 uppercase letters/digits (long-term); ASIA + 16 (temporary, with a session token) |
the ID alone isn't enough to call APIs, but it identifies the account and user; the secret key is 40 characters |
| Azure | client secrets of app registrations, storage account keys and SAS tokens, connection strings | SAS tokens carry their own permissions and expiry in the URL |
| Google Cloud | service-account key files (JSON with a private_key PEM) |
GCP recommends not creating them at all |
| CI and SaaS tokens | GitHub ghp_…/github_pat_…, Slack webhooks, payment keys |
usually lead to the cloud: CI tokens can change pipelines that hold cloud credentials |
Scanners recognise these by format, plus keywords and randomness for generic secrets. Formats with a fixed prefix (like AKIA or ghp_) are found with almost no false positives; generic passwords are the hard case.
Scanning a repository
The session below creates a small synthetic repository with a key pair in a settings file, a CI token and a webhook in a .env file, and AWS's documented example key in the docs. Trivy's secret scanner runs over it, the developer fixes the code, and the scan is repeated. It runs in your sandbox, on local files only; every value is invented.
mkdir -p shop/config shop/deploy && cd shop
git init -q -b main . && git config user.name "Lab Dev" && git config user.email dev@lab.test
cat > config/settings.py <<'PY'
AWS_REGION = "eu-west-1"
AWS_ACCESS_KEY_ID = "AKIA2LABQ7XKZ4TWNM3P"
AWS_SECRET_ACCESS_KEY = "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"
BUCKET = "lab-app-uploads"
PY
cat > deploy/.env <<'ENV'
GITHUB_TOKEN=ghp_Lab0nly1nvalidT0kenAbCdEfGhIjKlMnOpQr
SLACK_WEBHOOK=https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
ENV
echo "Docs use AWS's example key AKIAIOSFODNN7EXAMPLE." > README.md
git add -A && git commit -qm "initial import"
scan() { trivy fs -q --scanners secret -f json . | jq -r '.Results[]? | .Target as $t | .Secrets[] | " \(.Severity) \(.RuleID) \($t):\(.StartLine)"'; }
echo "== scan 1"; scan
# the fix: credentials come from the role at run time, the .env file leaves the repository
cat > config/settings.py <<'PY'
AWS_REGION = "eu-west-1"
BUCKET = "lab-app-uploads"
# credentials: the default provider chain (workload identity); secrets: Secrets Manager by ARN
PY
git rm -q deploy/.env && echo "deploy/.env" > .gitignore
git add -A && git commit -qm "remove credentials"
echo "== scan 2 (working tree)"; scan; echo " (no findings)"
echo "== but the history still has it:"
git log -p --all | grep -c 'AKIA2LABQ7XKZ4TWNM3P'== scan 1
CRITICAL aws-access-key-id config/settings.py:2
CRITICAL aws-secret-access-key config/settings.py:3
CRITICAL github-pat deploy/.env:1
MEDIUM slack-web-hook deploy/.env:2
== scan 2 (working tree)
(no findings)
== but the history still has it:
2
Three points from the transcript:
- The scanner found the key ID, the secret key, the GitHub token and the webhook, and ignored the documented example key in the README (scanners allow-list it, which is also why examples should use it).
- After the fix the working tree is clean, but
git log -pstill contains the key twice (the line added in the first commit, and the same line shown as removed in the second): removing a secret in a new commit doesn't remove it from history, and anyone who cloned the repository has it. A key that was ever committed and pushed must be revoked, not just deleted. History scanners (gitleaks, TruffleHog) and the platforms' push protection cover this side (Secret Scanning Beyond the Repository, How Secrets Leak). trivy fsscans files, so it fits pre-commit hooks and CI; container images are scanned the same way withtrivy image --scanners secret.
Responding to a leaked AWS key
When a key is reported (by a scanner, by the provider, by a stranger), act in this order:
- Contain: deactivate the key immediately (
aws iam update-access-key --status Inactive); if it belongs to a role session, revoke the role's active sessions. Deactivation is reversible and costs nothing; waiting costs a lot. - Scope: find everything the key did. CloudTrail records the
accessKeyIdinuserIdentity, so filter by it across all regions, from the time of the leak (the commit time) to now. - Eradicate: undo what the attacker created: new IAM users, access keys, login profiles, roles and trust-policy changes (persistence), instances or functions in unusual regions (often crypto-mining), changed bucket policies, snapshots shared to other accounts.
- Recover and learn: delete the key, rotate anything it could read (secrets, database passwords), and replace the use case with a role or workload identity so there is no long-lived key to leak next time.
The program does step 2 on synthetic CloudTrail events for the leaked key and classifies each call.
import json
events = json.loads("""[
{"eventTime": "2026-03-02T09:14:07Z", "eventName": "PutObject", "eventSource": "s3.amazonaws.com", "awsRegion": "eu-west-1",
"sourceIPAddress": "10.10.0.70", "userIdentity": {"accessKeyId": "AKIA2LABQ7XKZ4TWNM3P", "userName": "app-legacy"}},
{"eventTime": "2026-03-02T11:40:51Z", "eventName": "GetCallerIdentity", "eventSource": "sts.amazonaws.com", "awsRegion": "us-east-1",
"sourceIPAddress": "203.0.113.66", "userIdentity": {"accessKeyId": "AKIA2LABQ7XKZ4TWNM3P", "userName": "app-legacy"}},
{"eventTime": "2026-03-02T11:41:03Z", "eventName": "ListBuckets", "eventSource": "s3.amazonaws.com", "awsRegion": "eu-west-1",
"sourceIPAddress": "203.0.113.66", "userIdentity": {"accessKeyId": "AKIA2LABQ7XKZ4TWNM3P", "userName": "app-legacy"}},
{"eventTime": "2026-03-02T11:41:20Z", "eventName": "ListUsers", "eventSource": "iam.amazonaws.com", "awsRegion": "us-east-1",
"sourceIPAddress": "203.0.113.66", "errorCode": "AccessDenied", "userIdentity": {"accessKeyId": "AKIA2LABQ7XKZ4TWNM3P", "userName": "app-legacy"}},
{"eventTime": "2026-03-02T11:42:55Z", "eventName": "CreateUser", "eventSource": "iam.amazonaws.com", "awsRegion": "us-east-1",
"sourceIPAddress": "203.0.113.66", "requestParameters": {"userName": "backup-svc"},
"userIdentity": {"accessKeyId": "AKIA2LABQ7XKZ4TWNM3P", "userName": "app-legacy"}},
{"eventTime": "2026-03-02T11:43:10Z", "eventName": "CreateAccessKey", "eventSource": "iam.amazonaws.com", "awsRegion": "us-east-1",
"sourceIPAddress": "203.0.113.66", "requestParameters": {"userName": "backup-svc"},
"userIdentity": {"accessKeyId": "AKIA2LABQ7XKZ4TWNM3P", "userName": "app-legacy"}},
{"eventTime": "2026-03-02T11:47:31Z", "eventName": "RunInstances", "eventSource": "ec2.amazonaws.com", "awsRegion": "ap-southeast-3",
"sourceIPAddress": "203.0.113.66", "requestParameters": {"instanceType": "g5.12xlarge", "maxCount": 8},
"userIdentity": {"accessKeyId": "AKIA2LABQ7XKZ4TWNM3P", "userName": "app-legacy"}},
{"eventTime": "2026-03-02T12:05:00Z", "eventName": "PutObject", "eventSource": "s3.amazonaws.com", "awsRegion": "eu-west-1",
"sourceIPAddress": "10.10.0.70", "userIdentity": {"accessKeyId": "AKIA2LABQ7XKZ4TWNM3P", "userName": "app-legacy"}}
]""")
KNOWN_NETS = ("10.10.0.",) # where the legitimate application runs
USUAL_REGIONS = {"eu-west-1"}
CLASSES = {"GetCallerIdentity": "discovery", "ListBuckets": "discovery", "ListUsers": "discovery",
"CreateUser": "PERSISTENCE", "CreateAccessKey": "PERSISTENCE", "CreateLoginProfile": "PERSISTENCE",
"RunInstances": "IMPACT (resource abuse)"}
leaked = "AKIA2LABQ7XKZ4TWNM3P"
for e in sorted((e for e in events if e["userIdentity"]["accessKeyId"] == leaked), key=lambda e: e["eventTime"]):
known = e["sourceIPAddress"].startswith(KNOWN_NETS)
tags = [] if known else ["unknown IP"]
if e["awsRegion"] not in USUAL_REGIONS and e["eventSource"] not in ("iam.amazonaws.com", "sts.amazonaws.com"):
tags.append("unusual region")
if "errorCode" in e:
tags.append(e["errorCode"])
cls = CLASSES.get(e["eventName"], "normal app use" if known else "check")
extra = e.get("requestParameters", {})
print(f"{e['eventTime'][11:19]} {e['eventName']:17} {e['sourceIPAddress']:13} {cls:24} {', '.join(tags)} {extra if extra else ''}".rstrip())
created = [e["requestParameters"]["userName"] for e in events if e["eventName"] in ("CreateUser", "CreateAccessKey")]
print("\nto remove:", sorted(set(created)), "+ every access key of those users + instances in ap-southeast-3")09:14:07 PutObject 10.10.0.70 normal app use
11:40:51 GetCallerIdentity 203.0.113.66 discovery unknown IP
11:41:03 ListBuckets 203.0.113.66 discovery unknown IP
11:41:20 ListUsers 203.0.113.66 discovery unknown IP, AccessDenied
11:42:55 CreateUser 203.0.113.66 PERSISTENCE unknown IP {'userName': 'backup-svc'}
11:43:10 CreateAccessKey 203.0.113.66 PERSISTENCE unknown IP {'userName': 'backup-svc'}
11:47:31 RunInstances 203.0.113.66 IMPACT (resource abuse) unknown IP, unusual region {'instanceType': 'g5.12xlarge', 'maxCount': 8}
12:05:00 PutObject 10.10.0.70 normal app use
to remove: ['backup-svc'] + every access key of those users + instances in ap-southeast-3
The timeline tells the story a responder must reconstruct: the application keeps working from its own subnet, while from 11:40 an outside address uses the same key for discovery (who am I, which buckets, which users), tries IAM and fails once, then succeeds in creating a new user with its own key (persistence that survives revoking the leaked key) and starts eight GPU instances in a region the company never uses (cost and mining). Deactivating only the leaked key would leave backup-svc and the instances behind.
How leaks are detected
- Before the leak: pre-commit and CI secret scanning (as above), push protection on the code platform, image scanning, and no long-lived keys to begin with.
- After the leak: provider notifications (AWS Health and support cases about exposed keys, the quarantine policy appearing on a user); GuardDuty-style findings for calls from unusual places; your own detections: the same key from two networks,
GetCallerIdentityfrom a new IP, IAM writes by an application principal, activity in unused regions (Cloud Detections).
How it is prevented
- No long-lived keys: humans use federated sign-in, workloads use roles and workload identity, CI uses OIDC (Role Assumption). Then there is nothing of value to leak.
- Where keys must exist: one key per purpose, scoped policy, IP or VPC conditions so a leaked key fails elsewhere (data perimeter), rotation, and alerts on use from new places.
- SCPs that block unused regions and IAM user creation outside the identity pipeline turn the attacker's next steps into denied calls.
Pitfalls
- Deleting the secret from the repository and calling it done: revoke first, then clean history if you must.
- Investigating only the leaked key: persistence lives in new identities, and their activity carries their key IDs.
- Ignoring the docs example key allow-list in your own tooling: findings on
AKIAIOSFODNN7EXAMPLEare noise; findings on anything else are not.
Practice
1. In the transcript, why did scan 2 print nothing although the key is still in the repository?
trivy fs scans the working tree, and the files no longer contain the key. The key lives in the first commit; scan history with a history-aware scanner (gitleaks git) and, above all, revoke the key.
2. Which CloudTrail query finds the attacker's activity after they switched to the new user?
Filter on userIdentity.userName = backup-svc (or on the new access key ID, which appears in the CreateAccessKey response element), from 11:43 onwards, in all regions.
3. Add an SCP that would have stopped the last two attacker steps. What would it say?
Deny ec2:RunInstances (and everything except global services) outside eu-west-1, and deny iam:CreateUser/iam:CreateAccessKey for every principal except the identity-management pipeline role (aws:PrincipalArn condition), as in Boundaries and SCPs.
Test yourself
A secret was committed, pushed, and removed in the next commit. Is it safe?
- Yes
- No: it remains in history and in every clone; revoke and rotate it
- Only if the repository is private
- Yes, if Trivy reports nothing
What is the first response step for a leaked access key?
- Write the report
- Deactivate the key
- Delete the repository
- Email the attacker
Why is deactivating the leaked key not enough in the timeline?
- Keys can't be deactivated
- The attacker created a new user with its own access key and launched instances
- CloudTrail was off
- The key was temporary
Why didn't the scanner report AKIAIOSFODNN7EXAMPLE?
- It is too short
- It is AWS's documented example key, allow-listed by scanners
- It was in a README
- It is a temporary key