Bash and Linux

Find files that contain a leaked AWS access key

mediumgrep and regex

Problem statement

Before open-sourcing a repository, security asks you to list every file that contains something shaped like an AWS access key ID: AKIA followed by exactly 16 uppercase letters or digits. Search the whole tree recursively, print only file paths (sorted), and skip the .git directory, whose history is handled separately. Run from the root of this tree:

config/app.env

TEXT
AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
AWS_REGION=us-east-1

scripts/deploy.sh

Bash
#!/bin/bash
aws s3 sync ./dist s3://my-bucket --region us-east-1

src/settings.py

TEXT
DEBUG = False
KEY = "AKIAJ7Q2EXAMPLE4ZZ9X"

README.md

TEXT
Set your AKIA... keys through environment variables. Never commit them.

.git/COMMIT_EDITMSG

TEXT
remove AKIAIOSFODNN7EXAMPLE from app.env

Examples

Example 1

Input: Run the command from the tree root.

Output: ./config/app.env ./src/settings.py

Explanation: AKIA... in the README is not followed by 16 key characters, and .git is excluded.

Hints

Approach

Optimal

grep -r walks the directory tree from .. -l stops reading a file at its first match and prints just the file name, which is what an audit list needs. -E enables {16}, so AKIA[0-9A-Z]{16} means the literal prefix followed by exactly 16 characters from the class. --exclude-dir=.git prunes the git metadata. grep's traversal order depends on the filesystem, so the result is piped to sort to make it stable and diff-friendly.

Bash
grep -rlE --exclude-dir=.git 'AKIA[0-9A-Z]{16}' . | sort

Follow-up questions

  • How would you also print the line number and the matching key only? (grep -rnoE)
  • How would you scan every commit in the git history, not just the working tree?

Frequently asked questions

Only 'at least 16 in a row', because the regex is not anchored on the right. A 20-character run would still match. That is fine for an audit, since a false positive is cheap, but add \b or -w if you need an exact boundary.

It is a quick first pass. Real scanners such as gitleaks or trufflehog also scan the full git history, check many key formats and verify entropy. A key removed in a later commit is still leaked if it exists in history.