Find Leaked AWS Keys
Problem statement
Scan a repo for AWS access key IDs that were committed by mistake, list the files that contain one, and print each key's location with the key partly masked. Leaked cloud keys are one of the most common causes of real breaches: bots scan public repos for them within minutes. Every DevOps engineer should be able to run this check by hand.
An AWS access key ID is AKIA followed by exactly 16 capital letters or digits. The script plants these files (AKIAIOSFODNN7EXAMPLE is the example key AWS itself uses in its documentation, so it is safe to show):
app/config.py
AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"deploy/env.sh
export AWS_ACCESS_KEY_ID=AKIAZZZZEXAMPLE00001# old key, rotated: AKIAZZZZEXAMPLE00002docs/keys.md
Access keys start with AKIA and have 16 more characters.tests/fixture.txt
token=AKIAshort123 id=XAKIAIOSFODNN7EXAMPLE9There is also assets/logo.png, a binary file with a key inside, and .git/packed-refs, which also has one.
- List the files that contain a key, skipping
.git, binary files included. - List them again, text files only.
- Print every key as
file:line:key, with the last 12 characters replaced by*.
Expected output:
== files with a key (binary files included) ==./app/config.py./assets/logo.png./deploy/env.sh== files with a key (text files only, -I) ==./app/config.py./deploy/env.sh== each key with file and line, masked before printing ==./app/config.py:1:AKIAIOSF************./deploy/env.sh:1:AKIAZZZZ************./deploy/env.sh:2:AKIAZZZZ************Hints
AKIA[0-9A-Z]{16}. Add -w so it does not match inside a longer word, like XAKIA...9.Approach
Optimal: precise pattern, then mask
Covers: a precise grep -E pattern, -r, -l, -n, -o, -w, -I, --exclude-dir, storing a pattern in a variable, masking with sed -E capture groups.
A good secret scan is precise. A loose pattern like grep -ri 'aws' finds hundreds of harmless lines: comments, docs, variable names. People stop reading the results, and the real key slips by. A precise pattern describes the exact shape of the secret, so almost every hit is real.
| Part | Means |
|---|---|
AKIA |
the fixed start of a long-term access key ID |
[0-9A-Z] |
one capital letter or digit |
{16} |
exactly 16 of them |
-w |
the key must not be glued to other letters or digits |
What the pattern catches and what it skips.
too short, lowercase"]:::green ~~~ M2["XAKIA...9
glued to other letters"]:::green ~~~ M3["AKIA in the docs
no 16 characters"]:::green end HIT ~~~ MISS classDef blue fill:#dbeafe,stroke:#2563eb,color:#1e3a8a,stroke-width:2px classDef yellow fill:#fef3c7,stroke:#d97706,color:#78350f,stroke-width:2px classDef green fill:#d1fae5,stroke:#059669,color:#064e3b,stroke-width:2px classDef red fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:2px classDef purple fill:#ede9fe,stroke:#7c3aed,color:#4c1d95,stroke-width:2px classDef gray fill:#f3f4f6,stroke:#6b7280,color:#111827,stroke-width:2px linkStyle default stroke:#94a3b8,stroke-width:2px style HIT fill:transparent,stroke:#dc2626,stroke-width:2px style MISS fill:transparent,stroke:#059669,stroke-width:2px
AKIAshort123 has lowercase letters and is too short. XAKIAIOSFODNN7EXAMPLE9 has a key-shaped part, but it is glued to X and 9, so -w skips it. The docs line mentions AKIA but has no 16 characters after it.
The scan, step by step.
every file, skip .git"]):::purple S1 --> S2(["-w -E
exact key shape"]):::purple S2 --> S3(["-I -o
text files, just the key"]):::purple S3 --> S4(["sed
mask 12 characters"]):::purple S4 --> OUT["file:line:AKIAIOSF****"]:::green classDef blue fill:#dbeafe,stroke:#2563eb,color:#1e3a8a,stroke-width:2px classDef yellow fill:#fef3c7,stroke:#d97706,color:#78350f,stroke-width:2px classDef green fill:#d1fae5,stroke:#059669,color:#064e3b,stroke-width:2px classDef red fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:2px classDef purple fill:#ede9fe,stroke:#7c3aed,color:#4c1d95,stroke-width:2px classDef gray fill:#f3f4f6,stroke:#6b7280,color:#111827,stroke-width:2px linkStyle default stroke:#94a3b8,stroke-width:2px
Why -I? grep reads binary files too. With -l it lists logo.png, because a key really is inside it. Without -l, it prints a "binary file matches" message instead of the line, which tells you nothing about where the key is. -I skips binary files, which is right for the detail report. Run the first scan without -I too, because keys can hide inside zip files, images or built programs.
Why mask before printing? The report itself can leak the key: into your terminal history, a CI log, a chat message or a ticket. Showing the first 8 characters is enough to tell keys apart and find them in the AWS console. sed -E 's/(AKIA[0-9A-Z]{4})[0-9A-Z]{12}/\1************/' keeps the part in brackets, a capture group that \1 puts back, and replaces the other 12 characters with stars.
Walking through the code. The # Setup: lines only plant the sample files, so skip past them.
KEY='AKIA[0-9A-Z]{16}'stores the pattern once, so all three scans use the same one."$KEY"is quoted so the shell does not touch the brackets.grep -rlwE "$KEY" --exclude-dir=.git . | sortlists three files, including the PNG.- Adding
-Idrops the PNG. grep -rnowIEprintsfile:line:keyfor each key;-oprints just the key, even when a line has more than one. Thesedmasks it.
Edge cases. A file with two keys on one line gives two output lines, because -o prints each match. With no keys anywhere, every scan prints nothing and grep exits with 1, which a CI job can treat as "clean". The .git folder is skipped here, but a key deleted from the files still lives in git history, so see the follow-up.
# Setup: a repo with keys planted on purpose (AKIAIOSFODNN7EXAMPLE is AWS's own public example key)
cd "$(mktemp -d)"
mkdir -p app deploy docs tests assets .git
echo 'AWS_ACCESS_KEY_ID = "AKIAIOSFODNN7EXAMPLE"' > app/config.py
echo 'export AWS_ACCESS_KEY_ID=AKIAZZZZEXAMPLE00001' > deploy/env.sh
echo '# old key, rotated: AKIAZZZZEXAMPLE00002' >> deploy/env.sh
echo 'Access keys start with AKIA and have 16 more characters.' > docs/keys.md
echo 'token=AKIAshort123 id=XAKIAIOSFODNN7EXAMPLE9' > tests/fixture.txt
printf '\x89PNG\x00\x01AKIAIOSFODNN7EXAMPLE\x00' > assets/logo.png
echo 'AKIAIOSFODNN7EXAMPLE' > .git/packed-refs
KEY='AKIA[0-9A-Z]{16}'
echo "== files with a key (binary files included) =="
grep -rlwE "$KEY" --exclude-dir=.git . | sort
echo "== files with a key (text files only, -I) =="
grep -rlwIE "$KEY" --exclude-dir=.git . | sort
echo "== each key with file and line, masked before printing =="
grep -rnowIE "$KEY" --exclude-dir=.git . | sort |
sed -E 's/(AKIA[0-9A-Z]{4})[0-9A-Z]{12}/\1************/'Interview follow-ups
Scan the whole git history, not only the current files.
A key removed in a later commit still exists in the old commits.
git log -p --all | grep -nwE 'AKIA[0-9A-Z]{16}'prints every key that ever appeared in any branch's changes. To know which commit added it, usegit log --all -S 'AKIAIOSFODNN7EXAMPLE' --oneline, which lists commits where that text was added or removed. Removing it from history needs a rewrite tool such asgit filter-repo, and everyone must re-clone afterwards, which is why rotating the key comes first.
Frequently asked questions
Treat it as stolen, even if the repo is private. First, deactivate and delete the key in AWS (IAM, access keys), and create a new one for whatever needed it. Then check AWS CloudTrail for anything that key did that you did not expect. Only after that, clean the code and move the secret into a secret manager or environment variable. Deleting the file in a new commit is not enough, because the key is still in git history.
An access key ID (AKIA...) comes with a secret access key, which is 40 characters of letters, digits, / and +. It has no fixed prefix, so a regex for it alone gives many false hits. Scanners look for it near words like aws_secret_access_key or right next to an AKIA key. Temporary keys from AWS STS start with ASIA instead of AKIA, so a fuller pattern is (AKIA|ASIA)[0-9A-Z]{16}.
A grep check is a good first guard and easy to understand. Real teams add a dedicated tool like gitleaks or trufflehog, which know hundreds of secret patterns and scan git history. GitHub, GitLab and AWS also scan public repos and can alert or disable keys they find. Use grep to understand the idea and for quick checks on a server; use the tools for full coverage.