Lesson 04 · 45 minutes
Find leaked keys and judge the credentials of an account
- Tell long-lived credentials from temporary ones and say why the difference matters
- Report the age and the use of every access key of an account
- Scan a repository for keys and map each one to its owner
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
The audit of lesson 3 showed what the deploy user can do. Now your lead asks how an outsider could become the deploy user: "It is a program, so it has no password. It has a key. Where is that key written down? Check our shop repository, the build logs and the image, and tell me how old every key of the account is." A secret access key is a text of forty characters. It works for anyone who has it, from anywhere, until someone switches it off.
Recall
Lesson 3: why is iam:PassRole on every resource an escalation path?
The holder can hand any role of the account to a service, for example to a new machine, and then use that machine. If one role has more rights than the holder, the holder now has them too.
Lesson 2: which condition key is missing from a request that is signed with a long-lived access key?
aws:MultiFactorAuthPresent. A guard that denies requests without MFA must use BoolIfExists, or a stolen access key passes it.
The idea
A credential is what an identity shows to prove who it is. AWS has two families.
| Long-lived | Temporary | |
|---|---|---|
| What | The password of a user, or an access key: an access key ID and a secret access key | An access key ID, a secret access key and a session token, with an end time |
| ID starts with | AKIA | ASIA |
| Made by | An administrator, for an IAM user. A user can have two access keys at most. | The Security Token Service (STS), when a principal assumes a role |
| Ends | When someone makes it inactive or deletes it | By itself, after minutes or hours |
| If it leaks | It works until somebody notices | It stops working at its end time |
The access key ID is a name. It appears in logs and it is not secret. The secret access key signs the requests. AWS shows it once, when the key is made, and never again. The AWS documentation uses the pair AKIAIOSFODNN7EXAMPLE and wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY as its example, so you will meet these two texts in many repositories. They open nothing.
The best key is the one that does not exist. A program that runs inside AWS gets a role, and the platform hands it temporary credentials that change by themselves (lesson 8 shows where they come from). People sign in through a central identity system (in AWS, IAM Identity Center) and assume roles. Access keys remain for programs that run outside the cloud, and those keys need three habits: one key for one purpose, rotation (replace the key on a schedule, as in "Security fundamentals", lesson 3, for passwords), and removal when unused. For people, MFA is the control that makes a stolen password useless.
Keys leak through copies. Each copy is a place that a scanner must read.
- Settings file → Repository: the commit keeps it in the history
- Repository → Build log: the pipeline prints its environment
- Dockerfile → Image: an ENV line stays in an image layer
- Image → Registry: everyone who pulls the image has the key
Removing the key from the newest version of a file does not remove it from the history of the repository. A leaked key has one fix: make it inactive and issue a new one (lesson 12).
| Same idea, other names | AWS | Microsoft Azure | Google Cloud |
|---|---|---|---|
| A long-lived secret for a program | Access key of an IAM user | Client secret of an application | Service account key |
| No stored secret for a workload | Role with temporary credentials | Managed identity | Attached service account |
Worked example
1. Report the keys of the account
key_report.py reads the users of account/iam.json and prints one line for each access key: the owner, the ID, the status, the age in days and the days since its last use. It marks a key as OLD after 90 days (the limit of this lab: take your own from your company's policy), UNUSED when nobody used it for 90 days, and HUMAN when it belongs to a person who also has a password. "Today" is 21 November 2026, the day of the snapshot.
key_report.py
"""key_report.py: the age and the use of every access key of an account.
python3 key_report.py [folder] [today] default: account 2026-11-21
"""
import json
import sys
from datetime import date
MAX_AGE = 90 # days: the limit of this lab; take your own from your policy
def key_rows(iam, today="2026-11-21"):
"""One row for each access key: owner, id, status, age in days, days since last use, and flags."""
now, rows = date.fromisoformat(today), []
for u in iam["users"]:
active = [k for k in u["access_keys"] if k["status"] == "Active"]
for k in u["access_keys"]:
age = (now - date.fromisoformat(k["created"])).days
idle = (now - date.fromisoformat(k["last_used"])).days if k["last_used"] else None
flags = []
if k["status"] == "Active" and age > MAX_AGE:
flags.append("OLD")
if k["status"] == "Active" and (idle is None or idle > MAX_AGE):
flags.append("UNUSED")
if k["status"] == "Inactive":
flags.append("INACTIVE")
if u["console"] and k["status"] == "Active":
flags.append("HUMAN") # a person with a long-lived key
if len(active) > 1:
flags.append("TWO-ACTIVE")
rows.append({"user": u["name"], "id": k["id"], "status": k["status"], "age": age, "idle": idle, "flags": flags})
return rows
if __name__ == "__main__":
folder = sys.argv[1] if len(sys.argv) > 1 else "account"
with open(f"{folder}/iam.json") as src:
rows = key_rows(json.load(src), sys.argv[2] if len(sys.argv) > 2 else "2026-11-21")
for x in rows:
idle = "never" if x["idle"] is None else f"{x['idle']} d"
print(f"{x['user']:14s} {x['id']} {x['status']:8s} age {x['age']:4d} d idle {idle:6s} {' '.join(x['flags'])}")
print(f"{len(rows)} keys, {sum('OLD' in x['flags'] for x in rows)} older than {MAX_AGE} days")python3 key_report.pyben.okafor AKIAT4HN8RZKDEXAMPLE Active age 629 d idle 2 d OLD HUMAN
ci-deploy AKIAQ7XJ2MPLWEXAMPLE Active age 195 d idle 1 d OLD
ci-deploy AKIAL9SD3FQUAEXAMPLE Inactive age 675 d idle 509 d INACTIVE
backup-bot AKIAW2CV6BYGFEXAMPLE Active age 731 d idle 1 d OLD
svc-monitor AKIAE52JRQW3DEXAMPLE Active age 3 d idle 2 d
5 keys, 3 older than 90 daysThree active keys are older than 90 days, and one of them is two years old. The key of ben.okafor is a person's key: he should use a role. The last line is the user that nobody owns, with a key that is three days old.
2. Make the repository
gen_repo.py writes a small invented code repository into the folder repo. It joins every key from parts when it runs, so that the program itself holds no whole key. Open the block, save the file and run it. find repo -type f | sort lists the files.
The finished file: gen_repo.py
gen_repo.py
"""gen_repo.py: write a small invented code repository with secrets in the wrong places.
python3 gen_repo.py [seed] [folder] default: seed 1, folder repo
Every key here is invented. Each one ends in EXAMPLE, as the keys in the AWS documentation do, and opens nothing.
"""
import hashlib
import random
import shutil
import sys
from pathlib import Path
SEED = int(sys.argv[1]) if len(sys.argv) > 1 else 1
OUT = Path(sys.argv[2] if len(sys.argv) > 2 else "repo")
r = random.Random(100 + SEED) # only random() is used
SECRET_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/+"
def pick(items):
return items[int(r.random() * len(items))]
def secret():
"""40 characters that look like a secret access key. The parts are joined here so that no whole key is in this file."""
return "".join(pick(SECRET_LETTERS) for _ in range(30)) + "EXAMPLE" + "KEY"
CI_KEY, BEN_KEY = "AKIAQ7XJ2MPLW" + "EXAMPLE", "AKIAT4HN8RZKD" + "EXAMPLE" # the ids of account/iam.json
TEMP_KEY = "ASIA" + "".join(pick("ABCDEFGHJKLMNPQRSTUVWXYZ23456789") for _ in range(9)) + "EXAMPLE"
DOC_KEY, DOC_SECRET = "AKIAIOSFODNN7" + "EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCY" + "EXAMPLEKEY" # printed in the AWS documentation
CI_SECRET, BEN_SECRET = secret(), secret()
WORDS = ["order", "basket", "invoice", "stock", "price", "title", "author", "page", "cover", "parcel"]
def filler(n, style):
lines = []
for i in range(n):
a, b = pick(WORDS), pick(WORDS)
lines.append({"py": f"def {a}_{b}_{i}(x):\n return x + {int(r.random() * 90)}",
"log": f"2026-06-12T09:{i % 60:02d}:{int(r.random() * 60):02d}Z step {i}: build {a}-{b} ok",
"md": f"- The {a} service reads the {b} table."}[style])
return lines
def write(name, lines):
path = OUT / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("\n".join(lines) + "\n")
if __name__ == "__main__":
shutil.rmtree(OUT, ignore_errors=True)
n = 4 + int(r.random() * 5)
write("README.md", ["# larkfield-shop", "", "Set your own keys. The AWS documentation shows this example pair:", "",
f" aws_access_key_id = {DOC_KEY}", f" aws_secret_access_key = {DOC_SECRET}", ""] + filler(n, "md"))
write("src/orders.py", filler(n + 3, "py"))
write("src/settings.py", filler(2, "py") + ["", "REGION = \"eu-west-1\"", f"AWS_ACCESS_KEY_ID = \"{BEN_KEY}\"",
f"aws_secret_access_key = \"{BEN_SECRET}\"", ""] + filler(2, "py"))
write("deploy/ci.env", ["STAGE=prod", f"AWS_ACCESS_KEY_ID={CI_KEY}", f"AWS_SECRET_ACCESS_KEY={CI_SECRET}", "AWS_DEFAULT_REGION=eu-west-1"])
log = filler(20 + n, "log")
log.insert(7 + n, f"2026-06-12T09:08:11Z step 8: + export AWS_ACCESS_KEY_ID={CI_KEY}")
if SEED != 1:
log.insert(3, f"2026-06-12T09:03:40Z step 3: + export AWS_SECRET_ACCESS_KEY={CI_SECRET}")
write("logs/build-0612.log", log)
write("Dockerfile", ["FROM python:3.13-slim", "COPY src /app", f"ENV AWS_ACCESS_KEY_ID={CI_KEY}",
f"ENV AWS_SECRET_ACCESS_KEY={CI_SECRET}", "CMD [\"python\", \"/app/orders.py\"]"])
write("tests/fixtures.py", ["# a session that expired long ago, kept as test data", f"TEMP_ID = \"{TEMP_KEY}\"",
"TEMP_TOKEN = \"" + "".join(pick(SECRET_LETTERS) for _ in range(48)) + "EXAMPLE\""] + filler(2, "py"))
write("docs/notes.md", ["# Notes", "", "Rotate the deploy key every quarter. Its id starts with AKIA and ends with ...MPLW.", ""] + filler(n, "md"))
write("history/0007-remove-key.patch", ["commit 0007: remove the key from settings", "--- a/src/old_settings.py", "+++ b/src/old_settings.py",
f"-AWS_ACCESS_KEY_ID = \"{BEN_KEY}\"", f"-aws_secret_access_key = \"{BEN_SECRET}\"",
"+AWS_ACCESS_KEY_ID = os.environ[\"AWS_ACCESS_KEY_ID\"]"])
if SEED != 1:
write("infra/deploy.pem", ["-----BEGIN OPENSSH PRIVATE KEY-----", "bm90IGEgcmVhbCBrZXk6IGxhYiBkYXRhIG9ubHk=", "-----END OPENSSH PRIVATE KEY-----"])
write("notebooks/report.ipynb", ["{\"cells\": [{\"source\": [\"client = connect('" + CI_KEY + "')\"]}]}"])
files = sorted(p for p in OUT.rglob("*") if p.is_file())
digest = hashlib.sha256(b"".join(p.read_bytes() for p in files)).hexdigest()[:12]
print(f"{len(files)} files in {OUT}, sha256 of all {digest}")python3 gen_repo.py
find repo -type f | sort9 files in repo, sha256 of all 9b274d5dede0
repo/Dockerfile
repo/README.md
repo/deploy/ci.env
repo/docs/notes.md
repo/history/0007-remove-key.patch
repo/logs/build-0612.log
repo/src/orders.py
repo/src/settings.py
repo/tests/fixtures.py3. Search by hand first
An access key ID has a fixed start, so grep finds it. -r searches a folder and all folders below it, -n prints line numbers and -o prints only the part that matched. -E switches on extended patterns: (AKIA|ASIA) means one of the two, and [A-Z0-9]{16} means sixteen capital letters or digits. LC_ALL=C sort sorts the lines in plain byte order, so that the order is the same on every machine.
grep -rnoE "(AKIA|ASIA)[A-Z0-9]{16}" repo | LC_ALL=C sortrepo/Dockerfile:3:AKIAQ7XJ2MPLWEXAMPLE
repo/README.md:5:AKIAIOSFODNN7EXAMPLE
repo/deploy/ci.env:2:AKIAQ7XJ2MPLWEXAMPLE
repo/history/0007-remove-key.patch:4:AKIAT4HN8RZKDEXAMPLE
repo/logs/build-0612.log:15:AKIAQ7XJ2MPLWEXAMPLE
repo/src/settings.py:7:AKIAT4HN8RZKDEXAMPLE
repo/tests/fixtures.py:2:ASIAUG87QXGHKEXAMPLEThe key of ci-deploy is in three files and the key of ben.okafor in two. The other two lines are the example key of the AWS documentation and a temporary key. grep shows where, but not whose key it is, whether it is still active, or whether the secret is next to it.
4. Save the scanner
scan_keys.py looks for three things: an access key ID, a secret access key that is assigned to its usual name, and the first line of a private key file. re.compile prepares a pattern, (?i) makes it ignore case, and \b is a word boundary. The function scan_text returns the line number, the kind and the value of every match.
def scan_text(text):
"""Return (line number, kind, value) for every match in a text."""
hits = []
for number, line in enumerate(text.splitlines(), 1):
for kind, pattern in PATTERNS.items():
for m in pattern.finditer(line):
hits.append((number, kind, m.group(m.lastindex or 0)))
return hitsThree more ideas are in the file. The set ALLOW holds the two example values of the AWS documentation: the scanner reports them but does not count them. The function owners reads iam.json and maps each key ID of the account to its user and status. And mask prints only the first four characters of a secret, because a report is one more copy. Open the block and save the file.
The finished file: scan_keys.py
scan_keys.py
"""scan_keys.py: find cloud keys in a folder of code, logs and build files.
python3 scan_keys.py [folder] [iam-folder] default: repo account
Exit code 1 when it finds a key that is not on the allow-list.
"""
import json
import re
import sys
from pathlib import Path
PATTERNS = {
"access key id": re.compile(r"\b(?:AKIA|ASIA)[A-Z0-9]{16}\b"),
"secret access key": re.compile(r"(?i)aws_secret_access_key\s*[=:]\s*[\"']?([A-Za-z0-9/+=]{40})\b"),
"private key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
}
# Values that the provider prints in its own documentation. They open nothing.
ALLOW = {"AKIAIOSFODNN7EXAMPLE", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"}
def mask(kind, value):
"""An access key id is a name, not a secret: show it. Show only the first four characters of anything else."""
return value if kind == "access key id" else value[:4] + "..."
def scan_text(text):
"""Return (line number, kind, value) for every match in a text."""
hits = []
for number, line in enumerate(text.splitlines(), 1):
for kind, pattern in PATTERNS.items():
for m in pattern.finditer(line):
hits.append((number, kind, m.group(m.lastindex or 0)))
return hits
def scan(folder):
hits = []
for path in sorted(Path(folder).rglob("*")):
if path.is_file():
for number, kind, value in scan_text(path.read_text(errors="replace")):
hits.append({"file": str(path), "line": number, "kind": kind, "value": value, "allowed": value in ALLOW})
return hits
def owners(iam_folder):
"""Map each access key id of the account to its user and status."""
try:
with open(f"{iam_folder}/iam.json") as src:
return {k["id"]: (u["name"], k["status"]) for u in json.load(src)["users"] for k in u["access_keys"]}
except FileNotFoundError:
return {}
if __name__ == "__main__":
hits = scan(sys.argv[1] if len(sys.argv) > 1 else "repo")
known = owners(sys.argv[2] if len(sys.argv) > 2 else "account")
for h in hits:
note = "documented example, allowed" if h["allowed"] else ""
if h["value"] in known:
note = "key of user %s, %s" % known[h["value"]]
print(f"{h['file']}:{h['line']} {h['kind']:17s} {mask(h['kind'], h['value']):20s} {note}")
real = [h for h in hits if not h["allowed"]]
print(f"{len(real)} findings in {len({h['file'] for h in real})} files, {len(hits) - len(real)} allowed")
sys.exit(1 if real else 0)5. Scan and read the result
python3 scan_keys.py
echo "exit code $?"repo/Dockerfile:3 access key id AKIAQ7XJ2MPLWEXAMPLE key of user ci-deploy, Active
repo/Dockerfile:4 secret access key sN/E...
repo/README.md:5 access key id AKIAIOSFODNN7EXAMPLE documented example, allowed
repo/README.md:6 secret access key wJal... documented example, allowed
repo/deploy/ci.env:2 access key id AKIAQ7XJ2MPLWEXAMPLE key of user ci-deploy, Active
repo/deploy/ci.env:3 secret access key sN/E...
repo/history/0007-remove-key.patch:4 access key id AKIAT4HN8RZKDEXAMPLE key of user ben.okafor, Active
repo/history/0007-remove-key.patch:5 secret access key tAkJ...
repo/logs/build-0612.log:15 access key id AKIAQ7XJ2MPLWEXAMPLE key of user ci-deploy, Active
repo/src/settings.py:7 access key id AKIAT4HN8RZKDEXAMPLE key of user ben.okafor, Active
repo/src/settings.py:8 secret access key tAkJ...
repo/tests/fixtures.py:2 access key id ASIAUG87QXGHKEXAMPLE
10 findings in 6 files, 2 allowed
exit code 1Read it as a list of work.
- The key of
ci-deployis in the deployment file with its secret, in the image definition with its secret, and in a build log. It is active. Its policyDeployFullis the one with the four findings of lesson 3. - The key of
ben.okaforis insrc/settings.pywith its secret. It is also in a patch file of the history folder: someone removed it from one file, and the old version still shows it. - The pair in
README.mdis the documented example. It is on the allow-list. - The
ASIAkey in the tests is a temporary key. The account does not know it. Ask where it came from, but it ended long ago.
Your turn
The second repository of the company is larger. Make it with seed 2 in the folder repo2 and scan it. Then decide in which order you would act, and write down for each leaked key: the owner, where it is, and whether the secret is next to it.
python3 gen_repo.py 2 repo211 files in repo2, sha256 of all 7e06e4135850Check yourself
A developer deletes the line with the key, commits and pushes. Is the leak fixed?
No. The key is still in the history of the repository, in every copy that was cloned, and perhaps in build logs and images. The only fix is to make the key inactive and issue a new one. Cleaning the history is a second step that helps the next scan.
Why does the scanner print the access key ID in full and only four characters of the secret?
The ID is a name: you need all of it to find the owner in iam.json and the calls in the audit log, and it gives no access alone. The secret signs requests. A report with the full secret would be a new leak in a new place, often a ticket system that many people can read.
The scanner prints 0 findings for a folder. What can it still hold?
A secret that is split over two lines, encoded, compressed, or named differently, and every secret of another kind: a database password, a token of another service. A scanner finds the shapes that it knows. The control that does not depend on shapes is to have no long-lived key: a role for each workload.
Field notes
- A build system runs outside the cloud, but it does not need a stored key. Many CI systems can assume a role through OpenID Connect (OIDC) federation: the pipeline proves who it is with a short-lived token and gets temporary credentials, and no key is stored anywhere. Look for this before you rotate a deploy key. Write the trust policy with a condition on the
subclaim of the token that names one repository or branch: a wildcard there lets pipelines outside your control assume the role. - Where a key must exist, keep it in a secret store, a service that hands a secret only to programs that may read it: AWS Secrets Manager or Systems Manager Parameter Store. Never keep it in the repository.
- Scan before the commit and in the pipeline, not once a year. Gitleaks and TruffleHog are open tools for this, and the large code hosts have secret scanning of their own. The exit code 1 of a scanner is what stops a merge. A scanner also needs an allow-list for documented examples and test data, or people learn to ignore it. Keep the list short and exact: single values, never a whole folder.
- IAM gives a credential report for the whole account, with the age and the last use of every password and key. Read it every month. A key that nobody used for 90 days should be made inactive, then deleted. Rotate a key with an overlap: make the second key, move the program to it, make the first key inactive, wait, delete. The limit of two keys for a user exists for exactly this.
- The root user should have MFA and no access key at all. Check that first in any new account.