Platform Engineering · Lesson 248

Security Incident Response and Forensics: Contain the Attacker Without Destroying the Evidence

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

What you will learn

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.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

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.

Try it: what happens after the first action?

Pick the first action on the compromised CI runner, how far scoping goes, and how logs are kept.

keptevidence
3 objectsproven exposure
closedback doors

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Security incident response grows in four levels: knowing the order of work, preserving evidence, scoping completely, and rehearsing until it is fast.

Basic — Know the order of work

At the basic level you know how a security incident differs from an outage.

  • Detect, triage, preserve, contain, scope, eradicate, recover, notify, review.
  • A private channel and early legal involvement.
  • Disable and isolate rather than delete and terminate.

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.

Intermediate — Preserve evidence

At the intermediate level evidence is preserved in minutes.

  • Disk snapshots and memory capture before changes.
  • Logs copied to a locked evidence account; hashes and chain of custody.
  • Automated playbooks for the common cases.

Try it: Intermediate

What does a chain-of-custody record contain?

Now do it: Write an evidence manifest with hashes for one machine.

Advanced — Scope completely

At the advanced level the scope is complete and proven.

  • Audit log queries for the identity and everything it created or assumed.
  • A persistence hunt: users, keys, roles, trust policies, functions, jobs, images, SSH keys.
  • Data-access logs for sensitive stores, so exposure can be proven narrow.

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.

Master — Rehearse until it is fast

At the master level the response is practised and measured.

  • Tabletop and live exercises for the top scenarios; purple-team tests of detections.
  • Time to contain and time to scope measured per incident.
  • Prevention from every review: short-lived credentials, least privilege, secret scanning.

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.

Go deeper

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.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The key that came back.

Timeline

  • Day 0, 03:12A CI access key, printed into a public build log by a debugging step, is used from an unknown network to list buckets and read objects.
  • 03:25The key is disabled and the runner isolated. Its own API calls show bucket listings and three object reads. The incident is closed that afternoon.
  • Day 2, 22:40A new alert: IAM user svc-backup, created by the leaked key at 03:14 on day 0, is used from another address. A scheduled function had been set to recreate it if deleted.
  • Day 3–4A second response hunts all identities and functions created since day 0, removes them, rotates every CI secret, and widens the notification.

What changed after

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.

Try it yourself, from scratch

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.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. 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

    Options: ps -eo picks columns including the parent PID and the start time; ss -tanp lists TCP connections with their processes. Processes and connections vanish on reboot, so they come first.

    Expect: Three files named with the same UTC timestamp.

    Clean up: chmod -R u+w ~/labs/ir && rm -rf ~/labs/ir.

  2. 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

    Options: The manifest is the start of the chain of custody: anyone can later show the files are unchanged.

    Expect: One SHA-256 line per file, then the custody record.

  3. 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 ..

    Options: sha256sum -c recomputes each hash and compares it with the manifest.

    Expect: Three OK lines, then FAILED for the edited file and a warning that one checksum did not match.

2. Python: scope_hunt.py

This 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']

3. What to notice

4. Advanced: every step as one Bash script

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

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Your company has had security incidents handled as outages: restarts, terminations, and public channels. Design its security incident response for cloud workloads.

Clarifying questions to ask

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?

Rough sizing

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.

Shape of the answer

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.

Trade-offs to name

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.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
Terminate at onceHop 3: PreserveBreaksThe 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 persistenceHop 5: ScopeBreaksScoping 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 persistenceHop 6: EradicateBreaksTwo days later, svc-backup is used from a new address. The response starts again, now with a second, longer timeline and a larger disclosure.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Detection → Triage → Preserve → Contain → Scope → Eradicate → Recover → Notify → Review. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

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.

Saved on this device, in this browser.
Next in this series · Lesson 249
Secret Rotation, Secretless Workloads, and Verifying Signatures and SBOMs at Deploy

Two supply lines feed every workload: the credentials it uses and the software it runs. Both are attack paths. For credentials, the goal is secretless: workload identity instead of stored keys, and where secrets must exist…

Go to Lesson 249 →

Or browse the full course from the Lessons index.