Collecting Evidence Without Destroying It
Collect evidence from a running, compromised lab host in order of volatility: processes, sockets and a deleted implant recovered from an open file handle, then logs, changed files and a filesystem export. Hash everything with SHA-256, write a chain-of-custody record, and prove that a tampered or missing copy is detected. Includes cloud acquisition order.
Contentsand lesson path
On this page
- Goal and setup
- Order of volatility
- Step 1: Build the compromised host
- Step 2: Open the case and record the clocks
- Step 3: Memory first (not run in this lab)
- Step 4: Processes
- Step 5: Network sockets
- Step 6: Open files and a deleted script
- Step 7: Logs, persistence and changed files
- Step 8: Export the filesystem
- Step 9: Hash everything and open a custody record
- Step 10: Hand over a copy and verify it
- Step 11: Negative test, a changed and a missing copy
- The same order on a cloud machine
- Troubleshooting
- Check your understanding
- Apply it
- Review prompt
Lessons of Security Incident Response & Forensics
- From Alert to Incident: Triage, Severity and Scope Concept · 20 min
- Containment Under Pressure and Ransomware-Ready Recovery Worked example · 30 min
- Collecting Evidence Without Destroying It Lab · 30 min
- Building a Timeline from Host and Log Artifacts Lab · 30 min
- Tabletop Exercises and the Incident Report Worked example · 25 min
- Incident Response Check Knowledge check · 10 questions
What you will learn
- Acquire and preserve volatile and non-volatile evidence (memory, disk, logs, cloud audit trails) with hashes and chain-of-custody records.
01. Goal and setup
A Linux web server, web01, has been compromised. It is still running, and some of the most useful evidence exists only while it runs. In this lab you build a harmless stand-in for that server in a container, collect its evidence from the outside in the right order, and make the evidence trustworthy: every file is hashed, recorded in a chain-of-custody record and checked again when it is handed over.
You need Docker, the alpine:3.20 image (about 8 MB) and Python 3.11 or later; the Python scripts use only the standard library. Create a folder ir-lab and run every command from it. Nothing in the lab contacts the internet: the "command-and-control server" is a listener on 127.0.0.1 inside the container.
ir-lab/
├── prepare_host.sh step 1: builds the compromised host
├── custody.py, verify.py steps 9-11: custody record and checks
├── case/
│ ├── evidence/ 00-clocks.txt ... 08-filesystem.tar
│ ├── SHA256SUMS
│ └── custody.json
└── analysis/ the analyst's working copy02. Order of volatility
RFC 3227, the classic guideline for evidence collection, says to collect from the most volatile to the least volatile. Its example order runs from CPU registers and cache; to the routing table, ARP cache, process table, kernel statistics and memory; then temporary file systems; disk; remote logging and monitoring data; physical configuration and network topology; and finally archival media. Memory and live network state vanish at shutdown, a disk survives it, and logs already shipped to another system are the safest of all. So you take memory and live state first, then the disk, and you leave off-host logs for last because nothing on the host can change them.
RFC 3227 adds three warnings. Do not shut down before you have collected, because evidence is lost and the attacker may have changed the shutdown scripts. Do not trust the programs on the system: run your own tools from protected media. And remember that every command you run changes the system a little, so write down what you ran and when. In this lab docker exec runs the container's own BusyBox tools; on a real case you would bring trusted, statically linked binaries.
03. Step 1: Build the compromised host
Save prepare_host.sh and run it. It starts the container, writes a fixed authentication log, plants a cron job and a second account with user ID 0 (root), and starts an "implant": a shell script that deletes its own file and then keeps one connection open to the fake server while it sleeps.
#!/usr/bin/env bash
# Build the "compromised" lab host web01. Everything planted here is harmless.
set -euo pipefail
VICTIM=${VICTIM:-ir-victim}
docker run -d --name "$VICTIM" --hostname web01 alpine:3.20 sleep infinity > /dev/null
docker exec -i "$VICTIM" sh -s <<'HOST'
set -e
# 1. Fixed log lines, so every learner gets the same file and the same hash.
cat > /var/log/auth.log <<'LOG'
Nov 2 09:58:41 web01 sshd[2101]: Failed password for root from 203.0.113.50
Nov 2 09:58:44 web01 sshd[2101]: Failed password for root from 203.0.113.50
Nov 2 10:01:44 web01 sshd[2140]: Accepted password for deploy from 203.0.113.50
LOG
# 2. Persistence: cron runs a hidden script every five minutes.
mkdir -p /usr/local/lib/.cache
printf '#!/bin/sh\n# lab implant: does nothing\nexit 0\n' > /usr/local/lib/.cache/upd.sh
chmod 755 /usr/local/lib/.cache/upd.sh
echo '*/5 * * * * /usr/local/lib/.cache/upd.sh' >> /etc/crontabs/root
# 3. A modified system file: a second account with user id 0 (root).
echo 'sysupd:x:0:0::/root:/bin/sh' >> /etc/passwd
# 4. A stand-in "C2 server" that listens on 127.0.0.1 inside this container only.
mkdir -p /tmp/.X1-lock
cat > /tmp/.X1-lock/kworker <<'SH'
rm -f /tmp/.X1-lock/kworker
sleep 86400 | nc 127.0.0.1 4444
SH
HOST
docker exec -d "$VICTIM" sh -c 'sleep 86400 | nc -l -p 4444 -s 127.0.0.1'
sleep 1
# 5. The "implant" connects to it, deletes its own script and then only waits.
docker exec -d "$VICTIM" sh /tmp/.X1-lock/kworker
sleep 1
echo "lab host ready: $VICTIM"bash prepare_host.shlab host ready: ir-victim04. Step 2: Open the case and record the clocks
Every timestamp you collect will be compared with other systems later, so record the examiner's time and the host's time side by side, in UTC. A container shares the host kernel's clock, so here the two agree apart from the second that passes between the commands. A real server can be minutes off, and lesson 4 shows how that offset is used.
mkdir -p case/evidence
{ echo "examiner_utc $(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo "web01_utc $(docker exec ir-victim date -u +%Y-%m-%dT%H:%M:%SZ)"
} | tee case/evidence/00-clocks.txtexaminer_utc 2026-11-16T14:26:09Z
web01_utc 2026-11-16T14:26:09Z05. Step 3: Memory first (not run in this lab)
On a real server, memory comes first. It holds running code, decrypted data, keys and network state that never reach the disk. Two common open source tools are AVML, a static Rust binary that runs in user space without knowing the kernel version in advance, and LiME, a loadable kernel module. Both need root on the host, and LiME loads code into the kernel, so neither belongs on a shared machine or inside a container, which would capture the whole host. The commands below show the pattern only: run from your own media, write to external storage rather than the suspect disk, and hash the image at once.
# NOT RUN in this lab: on a real Linux server, from your own trusted media
sudo /media/ir-usb/avml acquire --compress /media/ir-usb/web01.lime.compressed
sha256sum /media/ir-usb/web01.lime.compressed06. Step 4: Processes
Save the process list straight into the evidence folder and look at it.
docker exec ir-victim ps -o pid,ppid,user,args | tee case/evidence/01-processes.txtPID PPID USER COMMAND
1 0 root sleep infinity
18 0 root sh -c sleep 86400 | nc -l -p 4444 -s 127.0.0.1
24 18 root sleep 86400
25 18 root nc -l -p 4444 -s 127.0.0.1
26 0 root sh /tmp/.X1-lock/kworker
33 26 root sleep 86400
34 26 root nc 127.0.0.1 4444
41 0 root ps -o pid,ppid,user,argsThe implant is sh /tmp/.X1-lock/kworker: a script with a kernel-thread name in a hidden folder under /tmp. Its children are a sleep and an nc that connects to port 4444. The sh -c sleep 86400 | nc -l process and its children are the stand-in C2 server; on a real host that would be an outside address.
07. Step 5: Network sockets
netstat -tanp lists TCP sockets with the process that owns each one. The full output goes to the evidence file; awk prints only the local address, remote address, state and owning process.
docker exec ir-victim netstat -tanp > case/evidence/02-sockets.txt
tail -n +3 case/evidence/02-sockets.txt | awk '{print $4, $5, $6, $7}'127.0.0.1:35175 127.0.0.1:4444 ESTABLISHED 34/nc
127.0.0.1:4444 127.0.0.1:35175 ESTABLISHED 25/ncThe connection from the implant's nc to port 4444 is exactly the kind of fact that disappears at shutdown. With the process list, it ties a running program to a remote endpoint at a known time.
08. Step 6: Open files and a deleted script
The implant deleted its own file, so a disk image will not contain it. But the shell still holds the file open, and Linux keeps the content as long as a handle exists. /proc/<pid>/fd lists the open handles, and reading one returns the content. Find the deleted handle and copy it out.
PID=$(docker exec ir-victim pgrep -f 'X1-lock/kworker')
docker exec ir-victim ls -l /proc/$PID/fd > case/evidence/03-implant-fds.txt
grep -o '[0-9]* -> .*(deleted)' case/evidence/03-implant-fds.txt
FD=$(awk '/deleted/ {print $9}' case/evidence/03-implant-fds.txt)
docker exec ir-victim cat /proc/$PID/fd/$FD > case/evidence/04-implant-script.sh
cat case/evidence/04-implant-script.sh10 -> /tmp/.X1-lock/kworker (deleted)
rm -f /tmp/.X1-lock/kworker
sleep 86400 | nc 127.0.0.1 444409. Step 7: Logs, persistence and changed files
Now the less volatile evidence. Copy the authentication log, save the root crontab, and ask Docker which paths changed since the container started. docker diff marks added paths with A and changed ones with C; sort makes the order stable.
docker cp -q ir-victim:/var/log/auth.log case/evidence/05-auth.log
docker exec ir-victim cat /etc/crontabs/root > case/evidence/06-crontab-root.txt
docker diff ir-victim | sort -k2 > case/evidence/07-diff.txt
tail -n 1 case/evidence/06-crontab-root.txt
grep -E '^A ' case/evidence/07-diff.txt*/5 * * * * /usr/local/lib/.cache/upd.sh
A /tmp/.X1-lock
A /usr/local/lib/.cache
A /usr/local/lib/.cache/upd.sh
A /var/log/auth.log10. Step 8: Export the filesystem
docker export writes the container's filesystem as a tar archive. It is a logical copy of files, not a bit-for-bit disk image: it cannot recover deleted data from free space, and it does not include volumes. On a real disk you would take a full image through a write blocker, or a snapshot in the cloud.
docker export ir-victim -o case/evidence/08-filesystem.tar
tar -tf case/evidence/08-filesystem.tar | grep -E 'X1-lock|\.cache|crontabs/root$'etc/crontabs/root
tmp/.X1-lock/
usr/local/lib/.cache/
usr/local/lib/.cache/upd.shThe folder tmp/.X1-lock/ is in the export but the kworker script is not. Only step 6 saved it. If someone had rebooted the server to "start clean", that evidence would be gone for good.
11. Step 9: Hash everything and open a custody record
A SHA-256 hash is a 64-character fingerprint of a file; changing a single bit gives a completely different value. NIST SP 800-86 (2006) still names MD5 and SHA-1, but practical collisions exist for both, so use SHA-256 today. The custody record says what each item is, where it came from, how it was collected, by whom, and its hash. RFC 3227 lists what a chain of custody must show: where, when and by whom evidence was found, handled and stored, and every change of hands. Save custody.py.
"""Write and extend a chain-of-custody record for the files in case/evidence."""
import hashlib
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
RECORD = Path("case/custody.json")
EVIDENCE = Path("case/evidence")
SOURCES = { # file name prefix: (what it is, how it was collected)
"00": ("examiner and host clocks", "date -u on both sides"),
"01": ("process list", "docker exec ps"),
"02": ("network sockets", "docker exec netstat -tanp"),
"03": ("open files of the implant", "docker exec ls -l /proc/PID/fd"),
"04": ("deleted implant script", "docker exec cat /proc/PID/fd/N"),
"05": ("SSH authentication log", "docker cp"),
"06": ("root crontab", "docker exec cat"),
"07": ("changed paths since start", "docker diff"),
"08": ("filesystem export (logical)", "docker export"),
}
def now():
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def sha256(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def create(case, host, examiner):
items = []
for n, path in enumerate(sorted(EVIDENCE.iterdir()), 1):
what, method = SOURCES[path.name[:2]]
items.append({"item": f"{case}-{n:02d}", "file": path.name, "what": what,
"source": host, "method": method, "bytes": path.stat().st_size,
"sha256": sha256(path), "collected_by": examiner,
"recorded_utc": now()})
record = {"case": case, "items": items, "custody": [
{"utc": now(), "action": "collected and hashed", "by": examiner,
"location": str(EVIDENCE)}]}
RECORD.write_text(json.dumps(record, indent=2) + "\n")
print(f"{RECORD}: {len(items)} items")
def transfer(by, to, purpose):
record = json.loads(RECORD.read_text())
record["custody"].append({"utc": now(), "action": f"copy released to {to}",
"by": by, "purpose": purpose})
RECORD.write_text(json.dumps(record, indent=2) + "\n")
print(f"{RECORD}: {len(record['custody'])} custody entries")
if __name__ == "__main__":
examiner = os.environ.get("EXAMINER", "unknown examiner")
if sys.argv[1] == "create":
create(sys.argv[2], sys.argv[3], examiner)
elif sys.argv[1] == "transfer":
transfer(examiner, sys.argv[2], sys.argv[3])(cd case/evidence && sha256sum -- * > ../SHA256SUMS)
grep -E 'auth|implant-script|crontab' case/SHA256SUMS
EXAMINER="A. Analyst" python3 custody.py create IR-2026-031 web01668b4b39c65df6238a443229b0dbf0ba8f81661af8ad91d39fc2f5c237a20afd 04-implant-script.sh
44276dc222fa9931f59ae66401025ea279b64372af94ea87a033d1440c047a0e 05-auth.log
9acc28d96e99a46ddf2fa1a6be29b433061ee578bd96631db6fbc20743fc9d24 06-crontab-root.txt
case/custody.json: 9 itemsLook at one item in the record:
python3 -c "import json
print(json.dumps(json.load(open('case/custody.json'))['items'][5], indent=2))"{
"item": "IR-2026-031-06",
"file": "05-auth.log",
"what": "SSH authentication log",
"source": "web01",
"method": "docker cp",
"bytes": 235,
"sha256": "44276dc222fa9931f59ae66401025ea279b64372af94ea87a033d1440c047a0e",
"collected_by": "A. Analyst",
"recorded_utc": "2026-11-16T14:26:10Z"
}12. Step 10: Hand over a copy and verify it
Analysts work on copies, never on the originals. Record the transfer, then check the copy against the hashes in the record with verify.py. Run the check every time evidence is copied or analysed, so you can show later that nothing changed in between.
"""Check a copy of the evidence against the hashes in the custody record."""
import json
import sys
from pathlib import Path
from custody import sha256
record = json.loads(Path(sys.argv[1]).read_text())
folder = Path(sys.argv[2])
bad = 0
for item in record["items"]:
path = folder / item["file"]
if not path.exists():
status = "MISSING"
elif sha256(path) != item["sha256"]:
status = "MISMATCH"
else:
status = "ok"
bad += status != "ok"
print(f"{status:<8} {item['item']} {item['file']}")
print(f"{len(record['items']) - bad} of {len(record['items'])} items match the record")
sys.exit(1 if bad else 0)mkdir -p analysis && cp case/evidence/* analysis/
EXAMINER="A. Analyst" python3 custody.py transfer "B. Reviewer" "timeline analysis"
python3 verify.py case/custody.json analysiscase/custody.json: 2 custody entries
ok IR-2026-031-01 00-clocks.txt
ok IR-2026-031-02 01-processes.txt
ok IR-2026-031-03 02-sockets.txt
ok IR-2026-031-04 03-implant-fds.txt
ok IR-2026-031-05 04-implant-script.sh
ok IR-2026-031-06 05-auth.log
ok IR-2026-031-07 06-crontab-root.txt
ok IR-2026-031-08 07-diff.txt
ok IR-2026-031-09 08-filesystem.tar
9 of 9 items match the record13. Step 11: Negative test, a changed and a missing copy
A check that never fails proves nothing. Add one line to the analyst's copy of the log, delete another file, and verify again.
echo 'Nov 2 10:20:00 web01 sshd[2200]: line added later' >> analysis/05-auth.log
rm analysis/02-sockets.txt
python3 verify.py case/custody.json analysisok IR-2026-031-01 00-clocks.txt
ok IR-2026-031-02 01-processes.txt
MISSING IR-2026-031-03 02-sockets.txt
ok IR-2026-031-04 03-implant-fds.txt
ok IR-2026-031-05 04-implant-script.sh
MISMATCH IR-2026-031-06 05-auth.log
ok IR-2026-031-07 06-crontab-root.txt
ok IR-2026-031-08 07-diff.txt
ok IR-2026-031-09 08-filesystem.tar
7 of 9 items match the recordThe script exits with status 1, so a pipeline can stop on it. The hash shows that the copy changed, not who changed it or why; the custody entries answer those questions. When you are done, remove the container with docker rm -f ir-victim.
14. The same order on a cloud machine
In the cloud you usually cannot touch the hardware, but the order of volatility still applies. The AWS Security Incident Response Guide gives this order for a virtual machine: record its metadata; turn on termination protection and stop the disks from being deleted with the instance; snapshot the attached disks; capture memory with a suitable tool, because a snapshot holds only what was written to disk; then isolate the instance with network rules. Export the provider's audit logs, such as AWS CloudTrail, as well, because they show who did what to the account.
Two quick reactions destroy evidence. Terminating the instance deletes its memory and, depending on settings, its disks. Stopping it loses memory. And do not mount a suspect disk on your own workstation: analyse snapshots in a separate forensic account or network.
15. Troubleshooting
16. Check your understanding
17. Apply it
Toward the skill project's compromised host case:
- Add a step that saves
/proc/<pid>/environand/proc/<pid>/mapsfor the implant, and add their prefixes toSOURCESincustody.py. - Extend
custody.pywith averifyaction that appends a custody entry each time a check passes, so the record shows every verification. - Write the collection plan for a cloud virtual machine in your environment: the exact console or CLI steps for protection, snapshots, memory and audit log export, in order.
18. Review prompt
Without looking back:
- Give the order of volatility from memory to archival media, and say why remote logs come late.
- How did you recover a script that had been deleted from the disk?
- What does a matching SHA-256 hash prove, and what does it not prove?
- Which two quick reactions destroy evidence on a cloud virtual machine?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.