A security incident differs from an outage in one important way: there is someone on the other side, and the system is also a crime scene. Responders must preserve evidence before changing anything (disk snapshots, memory, logs copied to storage the attacker cannot touch), contain in ways that keep that evidence (isolate, do not terminate), scope everything the attacker did, including the back doors they left (persistence), and only then eradicate and recover. Legal and regulatory clocks start at discovery, so notification is part of the plan from the first hour. This lesson follows one leaked cloud access key and shows two failures: terminating the compromised machine at once, and stopping at the first key while the attacker's second way in stays open.
Difficulty: Advanced · Know this first: Lesson 211, Lesson 247
By the end of this lesson you can work at four levels:
This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.
This bar adds up minutes from the alert to an attacker contained, scoped, and notified. It is a worked example, not a measurement. The preserve and scope hops decide whether the scope is proven and whether the attacker is really out.
Pick the first action on the compromised CI runner, how far scoping goes, and how logs are kept.
Three questions. No score is saved anywhere — this is just you against the material.
Security incident response grows in four levels: knowing the order of work, preserving evidence, scoping completely, and rehearsing until it is fast.
At the basic level you know how a security incident differs from an outage.
Where it breaks: handling a breach like an outage, in the public incident channel, with restarts.
Try it: Basic
Why run a security incident in a restricted channel?
Now do it: Check that your security incident process has a private channel.
At the intermediate level evidence is preserved in minutes.
Try it: Intermediate
What does a chain-of-custody record contain?
Now do it: Write an evidence manifest with hashes for one machine.
At the advanced level the scope is complete and proven.
Try it: Advanced
Data-access logging was off for a bucket the key could read. What does the notification have to assume?
Now do it: Turn on data-access logging for your most sensitive bucket.
At the master level the response is practised and measured.
Trade-off: preserving evidence first costs minutes while the attacker may still be active; isolation contains them in those minutes without losing what you need to prove the scope.
Try it: Master
What is the single best prevention for leaked long-lived cloud keys in CI?
Now do it: Find the long-lived keys in your CI and plan their replacement.
A first-hour evidence and containment playbook for a leaked AWS access key on a CI instance (adapt for Azure and Google Cloud; run from a separate incident-response account and role):
aws ec2 create-snapshot --volume-id vol-0abc --description "IR-4127 ci-runner root, before containment"
aws ec2 modify-instance-attribute --instance-id i-0abc --groups sg-quarantine # no ingress, no egress
aws iam update-access-key --user-name ci-deployer --access-key-id AKIA... --status Inactive # disable, keep
aws iam put-user-policy --user-name ci-deployer --policy-name ir-deny-all \
--policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Action":"*","Resource":"*"}]}'
# scope: every action by the key, then by anything it created
aws cloudtrail lookup-events --lookup-attributes AttributeKey=AccessKeyId,AttributeValue=AKIA... --max-results 50
# persistence hunt: identities and keys created since the first malicious event
aws iam list-users --query "Users[?CreateDate>='2026-11-27']"
CloudTrail event history covers 90 days of management events in one Region; for real investigations you need an organisation-wide trail to a separate, locked account, and data events (S3 object reads) enabled for sensitive buckets. The equivalents are Azure Activity Log and resource logs exported to a locked storage account, and Google Cloud Audit Logs with Data Access logs enabled, exported by an organisation sink.
On a Linux host, collect volatile data first (memory with a tool such as LiME or AVML, running processes, network connections, logged-in users), then disk images, and hash everything into a manifest. Frameworks to structure the work: NIST SP 800-61 (incident handling) and the cloud providers' own incident response guides.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The key that came back.
A persistence-hunt checklist in the playbook, CI moved to workload identity federation with no long-lived keys, secret scanning on build logs, data-access logging on sensitive buckets, and a yearly tabletop exercise of this exact scenario.
Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.
Before you start: A Linux machine you own (a VM or WSL is ideal), with ps, ss, and sha256sum, and Python 3. This lab collects evidence from your own machine only.
Type each one, read what it prints, and compare it with the note above it.
Collect volatile data first, into an evidence folder, with UTC timestamps in the file names.
mkdir -p ~/labs/ir/evidence && cd ~/labs/ir ts=$(date -u +%Y%m%dT%H%M%SZ) ps -eo pid,ppid,user,lstart,cmd > evidence/processes-$ts.txt ss -tanp > evidence/connections-$ts.txt 2>/dev/null who > evidence/logins-$ts.txt ls evidence
Hash everything into a manifest, record who collected it, and make it read-only.
Changes a real system: On a real incident, collect with the incident-response team's tools and accounts, write to a separate locked store, and never work on the only copy.
cd ~/labs/ir/evidence && sha256sum * > ../MANIFEST.sha256 && cd .. printf 'case=IR-LAB\ncollected_by=%s\ncollected_at=%s\nmethod=ps ss who, live system\n' "$(id -un)" "$ts" > custody.txt chmod -R a-w evidence MANIFEST.sha256 cat MANIFEST.sha256 custody.txt
Verify the evidence, then see what tampering looks like.
cd ~/labs/ir/evidence && sha256sum -c ../MANIFEST.sha256 f=$(ls logins-*); chmod u+w "$f"; echo "edited" >> "$f"; sha256sum -c ../MANIFEST.sha256; cd ..
scope_hunt.pyThis program scopes a leaked key from a set of audit events in two ways: looking only at the data the key read, and following every identity it created, which finds the persistence. It then builds an evidence manifest with hashes and detects a modified artifact. Save it as scope_hunt.py, then run it.
# scope_hunt.py
import hashlib
EVENTS = [ # (UTC time, actor, action, target), from a preserved audit-log export
("03:12:04", "key:AKIA-CI7", "ListBuckets", "*"),
("03:12:40", "key:AKIA-CI7", "GetObject", "s3://build-cache/env.txt"),
("03:13:02", "key:AKIA-CI7", "GetObject", "s3://build-cache/deploy.sh"),
("03:13:30", "key:AKIA-CI7", "GetObject", "s3://build-cache/tokens.json"),
("03:14:10", "key:AKIA-CI7", "CreateUser", "svc-backup"),
("03:14:25", "key:AKIA-CI7", "CreateAccessKey", "svc-backup"),
("03:14:50", "key:AKIA-CI7", "CreateFunction", "nightly-sync"),
("03:15:05", "key:AKIA-CI7", "PutRule", "nightly-sync every 6 hours"),
("03:40:00", "user:svc-backup", "ListBuckets", "*"),
("03:41:10", "user:svc-backup", "GetObject", "s3://customer-exports/2026-11.csv"),
("03:50:00", "user:ops-admin", "DescribeInstances", "*"), # normal admin work, not the attacker
]
PERSISTENCE = {"CreateUser", "CreateAccessKey", "CreateRole", "UpdateAssumeRolePolicy", "CreateFunction", "PutRule"}
reads = [t for _, a, act, t in EVENTS if a == "key:AKIA-CI7" and act == "GetObject"]
print("scope 1, the key's reads only:", len(reads), "objects;", "no persistence looked for")
tainted, changed = {"key:AKIA-CI7"}, True
while changed: # follow identities the attacker created
new = {"user:" + t for _, a, act, t in EVENTS if a in tainted and act == "CreateUser"}
changed = not new <= tainted
tainted |= new
print("scope 2, every identity the attacker controlled:", sorted(tainted))
for t, a, act, target in EVENTS:
if a in tainted:
flag = "PERSISTENCE" if act in PERSISTENCE else "data read" if act == "GetObject" else ""
print(f" {t} {a:<16} {act:<16} {target:<36} {flag}")
print("to remove:", sorted({tg.split()[0] for _, a, act, tg in EVENTS if a in tainted and act in PERSISTENCE}))
print()
artifacts = {"cloudtrail-export.json": b"...events...", "runner-root.snapshot-id": b"snap-0f3c", "memory.lime": b"\x00" * 64}
manifest = {name: hashlib.sha256(data).hexdigest() for name, data in artifacts.items()}
for name, h in manifest.items():
print(f" {h[:16]} {name}")
artifacts["cloudtrail-export.json"] = b"...events, one line removed..."
bad = [n for n, d in artifacts.items() if hashlib.sha256(d).hexdigest() != manifest[n]]
print("verification:", "all match" if not bad else f"MODIFIED: {bad}")
Run it, and you should see this output:
$ python3 scope_hunt.py scope 1, the key's reads only: 3 objects; no persistence looked for scope 2, every identity the attacker controlled: ['key:AKIA-CI7', 'user:svc-backup'] 03:12:04 key:AKIA-CI7 ListBuckets * 03:12:40 key:AKIA-CI7 GetObject s3://build-cache/env.txt data read 03:13:02 key:AKIA-CI7 GetObject s3://build-cache/deploy.sh data read 03:13:30 key:AKIA-CI7 GetObject s3://build-cache/tokens.json data read 03:14:10 key:AKIA-CI7 CreateUser svc-backup PERSISTENCE 03:14:25 key:AKIA-CI7 CreateAccessKey svc-backup PERSISTENCE 03:14:50 key:AKIA-CI7 CreateFunction nightly-sync PERSISTENCE 03:15:05 key:AKIA-CI7 PutRule nightly-sync every 6 hours PERSISTENCE 03:40:00 user:svc-backup ListBuckets * 03:41:10 user:svc-backup GetObject s3://customer-exports/2026-11.csv data read to remove: ['nightly-sync', 'svc-backup'] 0229490c151d1ffe cloudtrail-export.json 88e7e60e401a016c runner-root.snapshot-id f5a5fd42d16a2030 memory.lime verification: MODIFIED: ['cloudtrail-export.json']
The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/security-incident-response-and-forensics && cd ~/labs/security-incident-response-and-forensics) and save this as lab.sh.
#!/usr/bin/env bash
# The Linux steps of "Security Incident Response and Forensics: Contain the Attacker Without Destroying the Evidence", as one script (save it as lab.sh).
#
# ./lab.sh run every step, in order
# ./lab.sh 2 4 run only steps 2 and 4
# ./lab.sh --list list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.
STEPS=(
'Collect volatile data first, into an evidence folder, with UTC timestamps in the file names.'
'Hash everything into a manifest, record who collected it, and make it read-only.'
'Verify the evidence, then see what tampering looks like.'
)
step_1() {
mkdir -p ~/labs/ir/evidence && cd ~/labs/ir
ts=$(date -u +%Y%m%dT%H%M%SZ)
ps -eo pid,ppid,user,lstart,cmd > evidence/processes-$ts.txt
ss -tanp > evidence/connections-$ts.txt 2>/dev/null
who > evidence/logins-$ts.txt
ls evidence
}
step_2() {
cd ~/labs/ir/evidence && sha256sum * > ../MANIFEST.sha256 && cd ..
printf 'case=IR-LAB\ncollected_by=%s\ncollected_at=%s\nmethod=ps ss who, live system\n' "$(id -un)" "$ts" > custody.txt
chmod -R a-w evidence MANIFEST.sha256
cat MANIFEST.sha256 custody.txt
}
step_3() {
cd ~/labs/ir/evidence && sha256sum -c ../MANIFEST.sha256
f=$(ls logins-*); chmod u+w "$f"; echo "edited" >> "$f"; sha256sum -c ../MANIFEST.sha256; cd ..
}
# print a step that has to be run by hand, instead of running it
by_hand() {
echo " (run this one yourself: $1)"
sed 's/^/ /'
}
RESULTS=()
run_step() {
local n=$1 start=$SECONDS code
printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
"step_$n"
code=$?
RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}
summary() {
echo
echo "== summary"
local r
for r in "${RESULTS[@]}"; do echo " $r"; done
}
case "${1:-}" in
-h|--help) sed -n '2,6p' "$0"; exit 0 ;;
--list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac
[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
echo "there is no step '$n'; try --list" >&2
exit 2
fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done
Then make it executable and run it:
chmod +x lab.sh ./lab.sh --list # the steps ./lab.sh # every step, then a summary of exit codes and times ./lab.sh 2 3 # only steps 2 and 3
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
ps, chmod, mkdir, cat, echo, ls, cd, Redirection, If...Else.Your company has had security incidents handled as outages: restarts, terminations, and public channels. Design its security incident response for cloud workloads.
How are security incidents declared and who is involved? What evidence is preserved automatically, where, and how is custody recorded? What are the containment actions per resource type? How is scope established, including persistence? How are credentials rotated? Who decides on notifications, and from what evidence? How is the process rehearsed?
Say 200 cloud accounts, 3,000 instances and 40 Kubernetes clusters, CI with 1,500 pipelines, and personal data in 30 buckets and 12 databases.
A security severity scale and a private channel with an incident commander, legal, and the data protection officer; an organisation-wide audit trail with data events on sensitive stores, exported to a locked evidence account; automated playbooks that snapshot, capture, hash, and isolate; containment by disabling keys, revoking sessions, deny-all policies, and quarantine networks; a scoping runbook with a persistence hunt; credential rotation lists per system; notification decisions logged with evidence; quarterly tabletops and a yearly live exercise; workload identity to remove long-lived keys.
Preserving first takes minutes while the attacker may act, so automate it; data-access logging and long retention cost storage; in return, scope can be proven and notifications kept accurate.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| Terminate at once | Hop 3: Preserve | Breaks | The on-call engineer, trying to stop the attack fast, terminates the CI runner and deletes the access key within a minute. The disk, memory, the runner's local logs, and the key's identity (needed to search the audit logs cleanly) go with them. |
| Miss persistence | Hop 5: Scope | Breaks | Scoping looks only at the leaked key's own API calls, which show bucket listings and three reads. Nobody searches for identities the key created. The IAM user svc-backup, with its own access key, and a scheduled function that recreates it, stay in place. |
| Miss persistence | Hop 6: Eradicate | Breaks | Two days later, svc-backup is used from a new address. The response starts again, now with a second, longer timeline and a larger disclosure. |
The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.
Last updated . Next review due by November 2027. Found something out of date? Tell me.