Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 12 · 50 minutes

Respond to a leaked key in the right order

After this lesson you can
  • Put the actions for a leaked cloud key in an order and give the reason for each
  • Find from the audit log everything that a key did and everything that it made
  • Keep the evidence and write down what is known and what is not
Lab files of this lesson (25)

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

It is Saturday 21 November 2026, 10:00 UTC. You have told your lead what lessons 3 to 7 showed: the key of the deploy user is in the repository, and someone used it. She says: "Then this is an incident, and you are on it. Stop the access, do not destroy what we need to understand it, and write down what you do. Start with the plan: I want to read the order of actions before anyone touches the account." The course "Security operations basics" taught the method in lessons 11 to 13: the lifecycle, containment and evidence, the report. This lesson applies it to a cloud account, where some steps have a different order and different traps.

Recall

Lesson 7: what did the intruder do after the deploy key could not create a user?

It started machines in an unused region and gave one of them the role ec2-maintenance. From that machine, the role created a user, attached an administrator policy, made an access key and stopped the trail.

Lesson 4: why does deleting the line with the key from the repository not fix a leak?

The key is in the history, in clones, in build logs and in images. Only making the key inactive ends its use.

The idea

A leaked cloud key differs from a stolen password on a server in three ways. The intruder needs no access to your network: the API is on the internet. The intruder can create new ways in within minutes: users, keys, role sessions, machines. And every one of those actions is in a log that you can read, if the log was on.

One leaked key at Larkfield
10 Maythe key of ci-deploy is created12 Junea build prints the key ID; the secret is already in the repository18 Nov 02:41first use of the key from an address that nobody knows18 Nov 02:52a machine with a stronger role switches the trail off21 Nov 10:00the response starts, 79 hours after the first use10 Maythe key of ci-deploy is created12 Junea build prints the key ID; the secret isalready in the repository18 Nov 02:41first use of the key from an address thatnobody knows18 Nov 02:52a machine with a stronger role switches thetrail off21 Nov 10:00the response starts, 79 hours after thefirst use

The order of the response follows from that.

StepActionWhy in this place
1Make the leaked key inactive. Do not delete it.It stops the use of the key at once. It can be undone if a production job breaks, and it does not change the log. A deleted key is gone from the lists that you still need.
2Scope, fast. From the audit log: what did the key do, and what did it make?You cannot close doors that you have not found. Ten minutes of reading, not ten hours.
3End the sessions of every role that the key reached.Temporary credentials that were issued before step 1 keep working until they end. An inactive key does not end them.
4Close the doors that were made: new users, new keys, changed policies and trust.These are the intruder's way back in.
5Check that logging is on, and keep the evidence.Everything after this point should be recorded.
6Preserve, then stop the resources that were created.A machine that the intruder started is evidence. Take a snapshot of its disk before you stop it (aws ec2 describe-instances shows the volume ID). Do not delete it. A stop loses what is in memory: if you need memory, ask the senior responder before you stop the machine.
7Undo the changes to your own resources, and issue a new key.Last, because a new key in the same leaking place is the next incident.

If the response cannot start until the log is readable, scoping can wait ten minutes: the key is still the intruder's way in. If the intruder has sessions already, steps 1 and 3 are one action.

Step 3 has a mechanism of its own. To revoke the sessions of a role, AWS attaches a policy to the role that denies every action when the session was issued before a given time. The condition key is aws:TokenIssueTime. It is present only in requests that are signed with temporary credentials, so the policy does not touch long-lived keys, and sessions that start after that time work normally.

In a real account, these actions are single calls. This course does not run them, because they need an account. In the plan, ci-deploy is the user and ec2-maintenance the role.

aws iam update-access-key --user-name ci-deploy --access-key-id AKIAQ7XJ2MPLWEXAMPLE --status Inactive
aws iam put-role-policy --role-name ec2-maintenance --policy-name revoke-sessions --policy-document file://revoke-ec2-maintenance.json
aws ec2 create-snapshot --volume-id VOLUME_ID --description "evidence of the incident"
aws ec2 stop-instances --region ap-southeast-2 --instance-ids INSTANCE_ID

Throughout, keep a log of your own actions with times in UTC, and separate three things in every note: what the evidence shows, what you conclude, and what you do not know.

Worked example

1. Save the response planner

respond.py reads the snapshot and changes nothing in any account: it prints a plan. Its function follow does the scoping. It starts with the calls of the leaked key that came from outside the known networks of the company, so the owner's own use of the key is left out. Then it reads what those calls made: machines (a role session of a machine carries the ID of the machine), users and keys. It adds them to the set of actors and reads the log again, until nothing new appears. The function that writes the policy of step 3 is short.

def revoke_policy(now):
    """A policy that denies every call of a session that was issued before NOW. New sessions are not touched."""
    return {"Version": "2012-10-17", "Statement": [{"Effect": "Deny", "Action": "*", "Resource": "*",
                                                    "Condition": {"DateLessThan": {"aws:TokenIssueTime": now}}}]}

Open the block and save the file. It uses trail.py, iam_audit.py and policy_eval.py.

The finished file: respond.py

respond.py

"""respond.py: plan the response to a leaked access key, from the audit log and the identity snapshot.

    python3 respond.py FOLDER ACCESS_KEY_ID [NOW]        NOW is a UTC time such as 2026-11-21T10:00:00Z

It changes nothing in any account. It writes the plan, a session-revoking policy and sealed evidence into FOLDER-response.
"""
import hashlib
import json
import shutil
import sys
from pathlib import Path

import trail
from iam_audit import audit_policy
from policy_eval import policy_names


def follow(records, key_id, known_networks):
    """Start with the calls of the leaked key from unknown addresses. Then follow everything that those calls made."""
    actors, made, mine = {key_id}, {"instances": {}, "roles": set(), "users": set(), "keys": {}}, []
    grew = True
    while grew:
        grew = False
        for e in records:
            ident = e["userIdentity"]
            session = ident["arn"].rsplit("/", 1)[-1] if ident["type"] == "AssumedRole" else None
            by_actor = ident.get("accessKeyId") in actors or ident.get("userName") in actors or session in actors
            if not by_actor or e in mine:
                continue
            if ident.get("accessKeyId") == key_id and not trail.outside(e, known_networks):
                continue  # the owner's own use of the key
            mine.append(e)
            grew = True
            params, response = e["requestParameters"] or {}, e["responseElements"] or {}
            if e.get("errorCode"):
                continue
            if e["eventName"] == "RunInstances":
                for item in response["instancesSet"]["items"]:
                    made["instances"][item["instanceId"]] = e["awsRegion"]
                    actors.add(item["instanceId"])  # a role session of a machine carries the id of the machine
                if "iamInstanceProfile" in params:
                    made["roles"].add(params["iamInstanceProfile"]["name"])
            elif e["eventName"] == "CreateUser":
                made["users"].add(params["userName"])
                actors.add(params["userName"])
            elif e["eventName"] == "CreateAccessKey":
                made["keys"][response["accessKey"]["accessKeyId"]] = params["userName"]
                actors.add(response["accessKey"]["accessKeyId"])
    return sorted(mine, key=lambda e: e["eventTime"]), made


def revoke_policy(now):
    """A policy that denies every call of a session that was issued before NOW. New sessions are not touched."""
    return {"Version": "2012-10-17", "Statement": [{"Effect": "Deny", "Action": "*", "Resource": "*",
                                                    "Condition": {"DateLessThan": {"aws:TokenIssueTime": now}}}]}


def plan(folder, key_id, now="2026-11-21T10:00:00Z"):
    records = trail.load(folder)
    with open(f"{folder}/iam.json") as src:
        iam = json.load(src)
    with open(f"{folder}/inventory.json") as src:
        inv = json.load(src)
    owner = next(u for u in iam["users"] if any(k["id"] == key_id for k in u["access_keys"]))
    names = policy_names(iam, owner["arn"])
    weak = [f for n in names for f in audit_policy(n, iam["policies"][n])]
    events, made = follow(records, key_id, inv["known_networks"])
    changes = [e for e in events if not e["readOnly"] and not e.get("errorCode") and e["eventName"] not in ("RunInstances",)]
    steps = [f"Make the access key {key_id} of {owner['name']} inactive. Do not delete it yet: an inactive key can be studied and restored."]
    for name in sorted(made["roles"]):
        steps.append(f"Deny the sessions of the role {name} that were issued before {now} (revoke-{name}.json). "
                     "A key that is inactive does not end the sessions that it started.")
    for key, user in sorted(made["keys"].items()):
        steps.append(f"Make the access key {key} of the user {user} inactive.")
    for user in sorted(made["users"]):
        steps.append(f"Detach every policy from the user {user}. Keep the user until the review is done.")
    for stop, start, minutes in trail.gaps(records):
        steps.append(f"Check that the trail is logging. It was off for {minutes} minutes, from {stop} to {start}: "
                     "read the event history of the provider for that time.")
    by_region = {}
    for iid, region in made["instances"].items():
        by_region.setdefault(region, []).append(iid)
    for region, ids in sorted(by_region.items()):
        steps.append(f"Take a snapshot of the {len(ids)} machines in {region}, then stop them: {', '.join(sorted(ids))}.")
    for e in changes:
        if e["eventSource"] == "s3.amazonaws.com":
            steps.append(f"Undo {e['eventName']} on the bucket {e['requestParameters']['bucketName']} ({e['eventTime']}).")
    steps.append(f"Only now: give {owner['name']} a new credential (a role for the job, lesson 4; else a key in a secret store) and fix the cause.")
    return {"key": key_id, "owner": owner["name"], "policies": names, "weak_points": len(weak), "now": now,
            "first": events[0]["eventTime"] if events else None, "last": events[-1]["eventTime"] if events else None,
            "events": len(events), "refused": sum(1 for e in events if e.get("errorCode")),
            "addresses": sorted({e["sourceIPAddress"] for e in events}), "made": {
                "instances": made["instances"], "roles": sorted(made["roles"]), "users": sorted(made["users"]), "keys": made["keys"]},
            "changes": [f"{e['eventTime']} {trail.who(e)} {e['eventName']}" for e in changes], "steps": steps}


def seal(folder, out):
    """Copy the log into the response folder and write its SHA-256 hash next to it (Security operations basics, lesson 12)."""
    evidence = out / "evidence"
    evidence.mkdir(parents=True, exist_ok=True)
    shutil.copy2(f"{folder}/events.json", evidence / "events.json")
    digest = hashlib.sha256((evidence / "events.json").read_bytes()).hexdigest()
    (evidence / "SHA256SUMS").write_text(f"{digest}  events.json\n")
    return digest


if __name__ == "__main__":
    folder, key_id = sys.argv[1], sys.argv[2]
    p = plan(folder, key_id, *sys.argv[3:4])
    out = Path(folder.rstrip("/") + "-response")
    digest = seal(folder, out)
    (out / "plan.json").write_text(json.dumps(p, indent=1) + "\n")
    for name in p["made"]["roles"]:
        (out / f"revoke-{name}.json").write_text(json.dumps(revoke_policy(p["now"]), indent=1) + "\n")
    print(f"key {p['key']} of {p['owner']}; policies {', '.join(p['policies'])} ({p['weak_points']} weak points)")
    print(f"misuse: {p['events']} events ({p['refused']} refused) from {p['first']} to {p['last']}")
    print("from: " + ", ".join(p["addresses"]))
    made = p["made"]
    print(f"made: {len(made['instances'])} machines, {len(made['users'])} users, {len(made['keys'])} keys; used roles: {', '.join(made['roles']) or 'none'}")
    for c in p["changes"]:
        print("  change  " + c)
    for n, step in enumerate(p["steps"], 1):
        print(f"{n}. {step}")
    print(f"evidence sealed in {out}/evidence, sha256 {digest[:12]}")

2. Scope the incident

The arguments are the folder of the snapshot, the ID of the leaked key and the time of the response.

python3 respond.py account AKIAQ7XJ2MPLWEXAMPLE 2026-11-21T10:00:00Z | head -n 10 | cut -c1-120
key AKIAQ7XJ2MPLWEXAMPLE of ci-deploy; policies DeployFull (4 weak points)
misuse: 17 events (3 refused) from 2026-11-18T02:41:07Z to 2026-11-19T03:12:08Z
from: 203.0.113.140, 203.0.113.77
made: 3 machines, 1 users, 1 keys; used roles: ec2-maintenance
  change  2026-11-18T02:50:07Z role ec2-maintenance CreateUser
  change  2026-11-18T02:50:27Z role ec2-maintenance AttachUserPolicy
  change  2026-11-18T02:50:52Z role ec2-maintenance CreateAccessKey
  change  2026-11-18T02:52:07Z role ec2-maintenance StopLogging
  change  2026-11-19T03:11:37Z svc-monitor DeleteBucketPublicAccessBlock
  change  2026-11-19T03:12:08Z svc-monitor PutBucketAcl

One key, and behind it three machines, one role, one new user and one new key. The six changes are what the intruder did to the account. The two source addresses are the intruder's own and the address of the machine in Sydney.

3. Read the order of actions

grep -E "^[0-9]+\." keeps the lines that start with a number: the steps of the plan. fold -s -w 110 breaks a line that is longer than 110 characters at a space, so that the whole step fits the page.

python3 respond.py account AKIAQ7XJ2MPLWEXAMPLE 2026-11-21T10:00:00Z | grep -E "^[0-9]+\." | fold -s -w 110
1. Make the access key AKIAQ7XJ2MPLWEXAMPLE of ci-deploy inactive. Do not delete it yet: an inactive key can
be studied and restored.
2. Deny the sessions of the role ec2-maintenance that were issued before 2026-11-21T10:00:00Z
(revoke-ec2-maintenance.json). A key that is inactive does not end the sessions that it started.
3. Make the access key AKIAE52JRQW3DEXAMPLE of the user svc-monitor inactive.
4. Detach every policy from the user svc-monitor. Keep the user until the review is done.
5. Check that the trail is logging. It was off for 323 minutes, from 2026-11-18T02:52:07Z to
2026-11-18T08:15:30Z: read the event history of the provider for that time.
6. Take a snapshot of the 3 machines in ap-southeast-2, then stop them: i-00371135fa847ca27,
i-0602dadb72a889788, i-0c767544ace4967f3.
7. Undo DeleteBucketPublicAccessBlock on the bucket larkfield-uploads (2026-11-19T03:11:37Z).
8. Undo PutBucketAcl on the bucket larkfield-uploads (2026-11-19T03:12:08Z).
9. Only now: give ci-deploy a new credential (a role for the job, lesson 4; else a key in a secret store) and
fix the cause.

The planner does the scoping (step 2) first, in the log, and then lists the actions in the order of the table. The plan names the second key, which a responder who only switched off the key from the repository would have missed: the user svc-monitor was still acting on 19 November.

Step 9 says "secret store". That is a service that keeps secrets and hands them to the programs that may read them: AWS Secrets Manager, or Systems Manager Parameter Store. The better answer is no stored key at all (lesson 4, Field notes).

4. Test the policy that ends the sessions

The planner wrote the policy of step 3 into the response folder. Test it with the evaluator of lesson 2 before you trust it: a session of the role from before the response, a session from after it, and a request with a long-lived key, which carries no issue time.

python3 -c "
import json
from policy_eval import decide
admin = {'Statement': [{'Effect': 'Allow', 'Action': '*', 'Resource': '*'}]}
revoke = json.load(open('account-response/revoke-ec2-maintenance.json'))
for name, context in (('session of 18 November', {'aws:TokenIssueTime': '2026-11-18T02:48:35Z'}),
                      ('session of 21 November, 11:00', {'aws:TokenIssueTime': '2026-11-21T11:00:00Z'}),
                      ('long-lived key', {})):
    print(f'{name:30s}', decide([admin, revoke], {'action': 'iam:CreateUser', 'resource': '*', 'context': context}))"
session of 18 November         explicit deny
session of 21 November, 11:00  allow
long-lived key                 allow

The old session is denied, and a new one works. The third line is the reason for steps 1 and 4: this policy does nothing against a long-lived key, so each such key needs its own action.

5. Check the evidence

The planner copied the log into account-response/evidence and wrote its SHA-256 hash next to it, as you did by hand in "Security operations basics", lesson 12. sha256sum -c reads such a list and checks each file. The brackets run the two commands in a subshell, so your own shell stays in the lab folder.

(cd account-response/evidence && sha256sum -c SHA256SUMS)
events.json: OK

In a real account, the evidence is more than this file: the log files in the trail's bucket with their digest files, the event history for the hours when the trail was off, the snapshots of the three machines, and the current policies of every identity that was touched. Copy them to a place that the affected account cannot write to.

6. Write the first note

A first note is short, and it is honest about its limits. For this case:

INCIDENT NOTE 1, 2026-11-21 10:20 UTC, analyst: you
What we know (source: audit log, sealed copy, sha256 631802a29c18...):
- The access key AKIAQ7XJ2MPLWEXAMPLE (user ci-deploy) was used from 203.0.113.77 from 2026-11-18 02:41 UTC.
- It started 3 machines in ap-southeast-2. One had the role ec2-maintenance (administrator rights).
- That role created the user svc-monitor with an administrator policy and an access key, then stopped the trail.
- svc-monitor made the bucket larkfield-uploads public on 2026-11-19 03:12 UTC.
What we conclude: the key was taken from the shop repository, where it is stored with its secret.
What we do not know: what was done from 02:52 to 08:15 UTC on 18 November (trail off), what the machines ran,
  and whether objects were read from our buckets (no data events).
Done so far: nothing in the account. Plan attached, 9 steps.

Your turn

The sister company calls: the same key ID is in their repository, and their snapshot is account2. Make the response plan for 2026-11-21T10:00:00Z, read it, check the sealed evidence, and write the first note for that case in a file note-account2.txt, with the three headings of step 6. The page does not check your note. It checks that you read the plan.

Check yourself

You make the leaked key inactive. Ten minutes later the audit log shows a new call by the role that the intruder used. How is that possible?

The role session was issued before the key was switched off, and temporary credentials work until their end time. Making a key inactive does not end sessions that were started with it. You must deny the old sessions of the role with a condition on aws:TokenIssueTime.

Why does the plan say "make inactive" and not "delete" for the keys, and "stop" and not "terminate" for the machines?

Both keep the evidence and both can be undone. An inactive key still appears in the lists with its dates. A stopped machine with a snapshot can be examined, and a terminated one is gone with its disk. In an incident, choose the action that stops the harm and destroys nothing.

The response planner prints 9 steps and you carry out all of them. What can it have missed?

Everything that left no record in this file: actions while the trail was off, reads of data, changes in other accounts that trusted this one, and ways back in that the program does not follow, such as a changed trust policy or a new password for an existing user. A tool gives the first plan. The analyst reads the changes one by one and asks what each could be used for.

Field notes

  • Write this plan before the incident, as a runbook ("Security operations basics", lesson 13), and practise it on a test account. The order of steps 1 to 4 is what people get wrong at three in the morning.
  • AWS may itself attach a quarantine policy to a user whose key it finds exposed in public. Do not remove such a policy yourself. AWS opens a support case with the steps to follow.
  • The AWS Security Incident Response Guide and NIST SP 800-61 are the public texts for this work. Read the current version of each at its source.
  • Tell the people who must know, in the order that your incident plan names ("Security operations basics", lesson 11). A key that could read personal data may start a legal deadline: that decision belongs to the person named in the plan, not to the analyst.
  • After the incident, fix the cause and not only the key: no long-lived key for the deploy job (lesson 4), a smaller policy (lesson 3), no administrator role for machines, and an alert on StopLogging (lesson 7).