Security and hardening · Advanced · 24 min
Collect evidence from a Linux server after a suspected breach
By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · lsof 4.99 · procps and iproute2 from the Ubuntu archive
You will have a rehearsed first-response routine for an Ubuntu 26.04 server, ending with a timestamped, SHA-256 hashed archive of volatile data, persistence points and logs, copied off the machine.
On this page
Something looks wrong on a server: a process you do not recognise is eating the CPU, outbound traffic has jumped, or a login came from a country nobody on the team is in. The instinct is to kill the process, delete the strange file and reboot. Each of those destroys evidence. A reboot wipes memory, running processes and live network connections. Deleting a file removes the thing that tells you how the attacker got in, and whether they are still in.
This tutorial gives you a defensive first-response routine for your own Ubuntu 26.04 server. You take a disk snapshot, then collect the data that disappears first (who is logged in, what is running, what is talking to the network), then the places attackers use to come back (cron, systemd timers, SSH keys), then the logs. Every file is hashed with sha256sum, written to a separate disk, packed into one archive and copied off the machine. Your notes record what you did and when.
You will rehearse it on a spare server with a harmless marker to find, because a routine you have never run will fail on the worst day to learn it. This is first response, not a full forensic investigation. The last step covers when to hand over to professionals.
One limit to keep in mind throughout: you are running tools on a machine you do not trust. A capable attacker can replace ps or ss, or hide processes from them with a rootkit. Your collection is still worth having, and the disk snapshot is the copy a professional can examine with trusted tools. Do not treat a clean-looking result as proof the server is clean.
Step 1 · Stop, isolate and start your notes
Before you touch the server, decide what not to do:
- Do not reboot, shut down or reinstall it.
- Do not delete, move or "fix" suspicious files, users or crontab lines.
- Do not kill the suspicious process yet. Its memory, open files and connections are evidence.
- Do not log in from the server to other systems, or type passwords on it that are used elsewhere.
If the server is attacking others or leaking data, isolate it at the network edge rather than by pulling the plug. Your provider's cloud firewall or security group can block all traffic except SSH from your own address. That keeps the machine running while it stops talking to the attacker.
Start a notes file on your laptop now. Write one line per action, with the time in UTC, so that times line up with server logs from any timezone. Run this on your laptop:
mkdir -p ~/incident-demo
echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) Alert: high CPU and unknown process on web-01. Decided: no reboot, no clean-up." >> ~/incident-demo/notes.txtWrite who noticed what, which IP you connect from, and every command you run on the server. When you hand the case over, these notes let someone else tell your actions apart from the attacker's.
Check it worked
cat ~/incident-demo/notes.txtThe output is your line, starting with a UTC timestamp ending in Z. Keep the file open in an editor for the rest of the incident.
Step 2 · Take a disk snapshot at your provider
A snapshot is a copy of the whole disk at one moment, taken from outside the server. Nothing the attacker runs inside the machine can alter it, and it preserves deleted-but-recoverable data that your shell commands never see. Take it before you run anything else on the server.
In your provider's console, open the server's disk or volume and create a snapshot. Name it with the case and the time, for example case-web-01-20261126T0912Z. Most providers can snapshot a running server. Some offer a "crash-consistent" snapshot without stopping it, which is what you want: do not power off to get a cleaner one. Snapshots usually cost a small amount per gigabyte each month; check your provider's pricing page, and on prepaid accounts make sure your balance covers it, because a lapsed account can delete the evidence with the server.
Record the snapshot ID on your laptop (replace the example ID):
echo "$(date -u +%Y-%m-%dT%H:%M:%SZ) Snapshot created: snap-0abc123 (replace with your ID) of web-01 root disk" >> ~/incident-demo/notes.txtCheck it worked
The snapshot appears in the console as complete, with a creation time a few minutes ago, and its ID is the last line of ~/incident-demo/notes.txt. Do not continue until it shows as complete.
Step 3 · Rehearse on a spare server with a harmless marker
Do this step only on a spare server you will throw away, never on the one under investigation. You plant two harmless signs of the kind attackers leave, so that you can practise finding them.
First make sure the collection tools are installed. They are on a stock Ubuntu server already; this confirms it. On a real incident, check with command -v lsof ss ps lsmod instead of installing, because installing packages changes the disk you are trying to preserve.
sudo apt-get update
sudo apt-get install -y procps iproute2 lsof kmodNow plant the markers. The first is a copy of bash started from /tmp under a misleading name, running an idle loop, and then deleted, a common trick to leave no file behind. (Copying sleep does not work on Ubuntu 26.04: its coreutils are one multicall binary that picks the tool from its own file name, so a renamed copy refuses to run.) The second is a cron entry that would rerun it.
cp /usr/bin/bash /tmp/.demo-miner
/tmp/.demo-miner -c 'while true; do sleep 60; done' > /dev/null 2>&1 &
sleep 1
rm /tmp/.demo-miner
echo '*/30 * * * * root /tmp/.demo-miner -c true # demo-marker' | sudo tee /etc/cron.d/demo-markerThe sleep 1 gives the process a moment to start before you delete its file; delete it too soon and the marker never runs. The marker does no work. Cron will log a failure every 30 minutes because the file is gone, which is harmless; you remove both markers at the end.
Check it worked
pgrep -a -x .demo-miner
ls -l "/proc/$(pgrep -x .demo-miner)/exe"The first line shows a process ID and /tmp/.demo-miner -c while true; do sleep 60; done. The second ends in something like -> /tmp/.demo-miner (deleted): the program is running although its file no longer exists. That is one of the signs your collection should flag.
Step 4 · Prepare a separate disk for the evidence
Writing evidence to the server's own disk overwrites free space that may hold deleted attacker files, and an attacker with root can tamper with it. Write to a separate volume instead. Create a new, empty block volume in your provider's console (10 GB is enough for most servers) and attach it to the server.
Create the mount point:
sudo mkdir -p /mnt/evidenceFind the new volume. It is the disk with the size you chose and no mount point:
lsblk -o NAME,SIZE,TYPE,MOUNTPOINTSThe next command erases the device you name. Check twice that it is the new, empty volume and not the server's own disk, which is usually the one with / under MOUNTPOINTS. Replace /dev/sdb with your device:
sudo mkfs.ext4 -L evidence /dev/sdb
sudo mount -o nodev,nosuid,noexec /dev/sdb /mnt/evidencenoexec stops anything on the evidence volume from being executed directly, which matters if you copy a suspicious binary there. You will still run the collection script with sudo bash script, which reads it rather than executing it.
If you cannot attach a volume, collect to the server's disk in the next steps and copy the archive off straight away in the Copy step. That is worse, but far better than nothing.
Check it worked
findmnt /mnt/evidenceThe output shows /mnt/evidence on your new device (such as /dev/sdb), with noexec among the options. Add a line to your notes with the device name and the time.
Step 5 · Write the collection script
Keep this script in your team's runbook repository, so it exists before an incident. On the day, copy it onto the evidence volume; here you write it there directly. It only reads from the system and writes into one case folder. It records every command it runs, with a UTC timestamp, in its own notes.txt, and it carries on when a command fails, noting the failure.
The order follows the order of volatility: the clock first, then users, processes and network state, which change by the second, then open files and kernel modules, then the persistence points and logs that sit on disk.
sudo tee /mnt/evidence/collect.sh > /dev/null <<'EOF'
#!/usr/bin/env bash
# collect.sh: first-response collection for a Linux server.
# Usage: sudo bash collect.sh /mnt/evidence
# Reads from the system; writes only into a new case folder under the given directory.
set -uo pipefail
umask 077
ROOT="${1:?usage: sudo bash collect.sh /path/on/a/separate/disk}"
HOST="$(cat /proc/sys/kernel/hostname)"
CASE="case-${HOST}-$(date -u +%Y%m%dT%H%M%SZ)"
OUT="$ROOT/$CASE"
mkdir -p "$OUT/volatile" "$OUT/persistence" "$OUT/logs"
note() { printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >> "$OUT/notes.txt"; }
run() { # run <output file> <command...>
local f="$1"; shift
note "run: $* > $f"
"$@" > "$OUT/$f" 2>&1 || note "exit $?: $*"
}
note "start: case $CASE by uid $(id -u) (${SUDO_USER:-unknown})"
# 1. Clock and uptime, so every later time can be compared with the logs.
run volatile/date.txt date -u
run volatile/uptime.txt cat /proc/uptime
run volatile/timedatectl.txt timedatectl
# 2. Who is logged in and recent logins.
run volatile/who.txt who -a
run volatile/w.txt w
run volatile/last.txt last -Fwx
# 3. Processes, then each process's executable as the kernel sees it.
run volatile/ps.txt ps -e -ww -o pid,ppid,user,lstart,stat,args --forest
note "run: /proc/*/exe and cmdline > volatile/proc-exe.tsv"
for p in /proc/[0-9]*; do
pid="${p#/proc/}"
exe="$(readlink "$p/exe" 2>/dev/null)"
cmd="$(tr '\0' ' ' < "$p/cmdline" 2>/dev/null)"
printf '%s\t%s\t%s\n' "$pid" "$exe" "$cmd"
done > "$OUT/volatile/proc-exe.tsv"
grep -F '(deleted)' "$OUT/volatile/proc-exe.tsv" > "$OUT/volatile/deleted-exe.tsv"
# 4. Network state.
run volatile/ss-all.txt ss -tunapw
run volatile/ss-listen.txt ss -tulpn
run volatile/ip-addr.txt ip -s addr
run volatile/ip-route.txt ip route
run volatile/ip-neigh.txt ip neigh
run volatile/nft.txt nft list ruleset
# 5. Open files, including deleted files that are still open.
run volatile/lsof.txt lsof -nP
run volatile/lsof-deleted.txt lsof -nP +L1
# 6. Kernel modules and taint flags.
run volatile/lsmod.txt lsmod
run volatile/tainted.txt cat /proc/sys/kernel/tainted
# 7. Persistence: cron, systemd timers and units, SSH keys, accounts.
note "run: cron files > persistence/cron.txt"
for f in /etc/crontab /etc/cron.d/* /etc/cron.hourly/* /etc/cron.daily/* \
/etc/cron.weekly/* /etc/cron.monthly/* /var/spool/cron/crontabs/*; do
if [ -f "$f" ]; then
echo "=== $f"
cat "$f"
fi
done > "$OUT/persistence/cron.txt" 2>&1
run persistence/timers.txt systemctl list-timers --all --no-pager
run persistence/enabled-units.txt systemctl list-unit-files --state=enabled --no-pager
run persistence/authorized-keys.txt find /root /home -name 'authorized_keys*' -type f -exec ls -l --time-style=full-iso {} \; -exec cat {} \;
run persistence/passwd.txt cat /etc/passwd
run persistence/group.txt cat /etc/group
run persistence/recent-files.txt find /etc /usr/local /root /home /tmp /var/tmp /dev/shm -xdev -type f -mtime -3 -printf '%TY-%Tm-%Td %TT %u %m %s %p\n'
# 8. Logs: the journal for the last 7 days and a copy of /var/log.
run logs/journal-7d.txt journalctl --no-pager -o short-iso-precise --since '7 days ago'
note "run: tar of /var/log > logs/var-log.tar.gz"
tar -C / -czf "$OUT/logs/var-log.tar.gz" var/log 2> "$OUT/logs/var-log-tar-errors.txt" || note "tar exit $? (see var-log-tar-errors.txt)"
# 9. Hash every file, then pack the case and hash the archive.
note "end of collection; hashing"
( cd "$ROOT" && find "$CASE" -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum ) > "$OUT/SHA256SUMS"
tar -C "$ROOT" -czf "$ROOT/$CASE.tar.gz" "$CASE"
( cd "$ROOT" && sha256sum "$CASE.tar.gz" > "$CASE.tar.gz.sha256" )
echo "$ROOT/$CASE.tar.gz"
EOFA few choices worth knowing:
/proc/<pid>/exeis a link the kernel keeps to the running program. If the file was deleted, the link target ends in(deleted), and the script copies those lines intodeleted-exe.tsv. A legitimate process can show this briefly after a package upgrade; a program run from/tmpor/dev/shmcannot explain it that way.lsof +L1lists open files whose link count is below one: deleted files a process still holds. Attackers use this to keep a payload alive with no file on disk./proc/sys/kernel/taintedis0on an untouched kernel. A non-zero value can mean an out-of-tree or unsigned module was loaded, which is worth a professional's attention, though some legitimate drivers set it too.- On a busy server
/var/logcan be several gigabytes. Check withsudo du -sh /var/logfirst if the evidence volume is small.
Check it worked
sudo bash -n /mnt/evidence/collect.sh && echo "syntax OK"The output is syntax OK. bash -n reads the script without running it, which catches a broken paste before you need it.
Step 6 · Run it and read the volatile data
Add a line to your notes, then run the script with the evidence directory as its only argument:
sudo bash /mnt/evidence/collect.sh /mnt/evidenceIt takes from a few seconds to a few minutes, mostly for /var/log. The last line printed is the path of the archive, something like /mnt/evidence/case-web-01-20261126T091530Z.tar.gz. Some commands can fail, for example nft when nftables is not installed; the script notes the failure and carries on.
Save the case name in a variable so the next commands are copy-pasteable:
CASE=$(basename "$(ls -1d /mnt/evidence/case-*/ | tail -n 1)")
echo "$CASE"Now read what it found. Start with deleted executables and the cron files:
sudo cat "/mnt/evidence/$CASE/volatile/deleted-exe.tsv"
sudo grep -n -B1 'demo-marker' "/mnt/evidence/$CASE/persistence/cron.txt"Then look through, in this order, volatile/ss-all.txt for connections to addresses you do not recognise, volatile/ps.txt for processes whose parent is a web server or database (a shell under www-data is a classic sign), persistence/authorized-keys.txt for keys nobody can account for, and persistence/recent-files.txt for files changed in the last three days in places nobody deployed to. Write what you find in your notes, with the file and line. Do not act on it yet.
Check it worked
sudo grep -F '/tmp/.demo-miner (deleted)' "/mnt/evidence/$CASE/volatile/deleted-exe.tsv"
sudo grep -c '^20' "/mnt/evidence/$CASE/notes.txt"The first command prints the marker process: its ID, /tmp/.demo-miner (deleted) and its command line. The cron output from the previous fence showed === /etc/cron.d/demo-marker above the planted line. The second command prints the number of timestamped lines in the script's notes, around 30. If deleted-exe.tsv is empty during the rehearsal, the marker process has ended: start it again as in the rehearsal step.
Step 7 · Check the hashes and copy the evidence off
The script wrote SHA256SUMS, a hash of every file in the case, and a separate hash of the archive. Anyone who receives the archive can confirm that not one byte has changed since collection. Check both now:
cd /mnt/evidence && sudo sha256sum -c --quiet "$CASE/SHA256SUMS" && echo "all case files match"
cd /mnt/evidence && sudo sha256sum -c "$CASE.tar.gz.sha256"Print the archive's hash and paste the line into your notes on your laptop, so the value exists in a second place:
sudo cat "/mnt/evidence/$CASE.tar.gz.sha256"Now get the archive off the server. The cleanest route is to detach the evidence volume in the provider console and attach it to a clean analysis machine. To download it instead, hand the two files to your user (this changes their owner, not their content or hash), then copy them from your laptop. On the server:
sudo chown "$(id -un)" "/mnt/evidence/$CASE.tar.gz" "/mnt/evidence/$CASE.tar.gz.sha256"On your laptop, replace the user, address and case name with your own:
cd ~/incident-demo
scp 'admin@203.0.113.10:/mnt/evidence/case-web-01-20261126T091530Z.tar.gz*' .
shasum -a 256 -c case-web-01-20261126T091530Z.tar.gz.sha256shasum -a 256 is on macOS; on a Linux laptop use sha256sum -c. If you are on a metered or mobile connection, check the archive size first with ls -lh on the server. A multi-gigabyte download over prepaid data is slow and costly, and detaching the volume avoids it.
Check it worked
On the server the first command prints all case files match and the second prints case-...tar.gz: OK. On your laptop, shasum prints the same OK line, and the hash in your notes matches the one in the .sha256 file. A FAILED line means the copy is damaged or altered: copy it again and do not work from the bad one.
Step 8 · Hand over, or contain, and clean up the rehearsal
You now have a snapshot, a hashed archive and notes with times. That is what a professional incident responder will ask for first. Hand over rather than carrying on alone when any of these is true:
- Personal data may have been exposed. Data protection laws set short clocks: the GDPR and Nigeria's Data Protection Act 2023 both expect the regulator to be told within 72 hours of becoming aware of a breach, unless the breach is unlikely to put people's rights at risk. Tell whoever owns legal and compliance now.
- Payment card data, health data or customer credentials could be involved.
- The attacker may still be active, has reached other servers, or the kernel looks tampered with (a non-zero taint value you cannot explain, or tools giving inconsistent answers).
- Ransomware, extortion or legal action is in play, or you may need the evidence in court.
- You do not have the time or experience to finish the investigation calmly.
Memory capture belongs in that hand-over. A memory image can hold decrypted keys, injected code and commands that never touched the disk. Tools such as Microsoft's AVML or LiME can take one, but they need care to run on a suspect machine without destroying what you want, so leave them to someone who has practised. Your national CERT can also advise; in Nigeria that is ngCERT.
If you handle it yourselves, treat the server as lost. Rotate every secret it held (SSH keys, API tokens, database passwords), rebuild it from a clean image and your configuration, and restore data from a backup taken before the earliest suspicious time in your notes. Keep the snapshot and the archive until the case is closed.
On the rehearsal server, remove the markers:
pkill -x .demo-miner
sleep 1
sudo rm /etc/cron.d/demo-markerWhen you are done practising, delete the spare server, the evidence volume and any rehearsal snapshot in the console so they stop billing, and remove ~/incident-demo from your laptop.
Check it worked
[ -z "$(pgrep -x .demo-miner)" ]
echo "marker process gone"
ls /etc/cron.d/demo-marker 2> /dev/null || echo "marker cron file gone"The output is marker process gone and marker cron file gone. If the first test fails instead, the marker is still running: run the pkill line again. Note the time you finished the rehearsal and how long it took; that number goes in your incident response plan.
Next steps
- Put this routine, the script and who to call into a written plan: /tutorials/write-an-incident-response-plan-for-a-small-team.
- Dig into the journal you collected: /tutorials/search-the-systemd-journal-with-journalctl.
- Tell a real attack from an ordinary overload: /tutorials/find-why-a-linux-server-is-slow.
- Make the next investigation easier by logging the right events: /tutorials/log-security-events-an-analyst-can-use.
Related tutorials
- Write an incident response plan for a small teamYou will have a four-page incident response plan for a team of under 20 people, with severity levels, named roles, an out-of-band contact list, first-hour checklists for three common incidents, regulator deadlines and evidence rules, tested once in a 30-minute tabletop exercise.
- Search the systemd journal with journalctlYou will find the log lines you need in the systemd journal by service, boot, time window, priority, text and field, turn them into JSON for jq, and read them without sudo.
- Find why a Linux server is slow with top, vmstat and iostatYou will run a five-minute triage routine on Ubuntu 26.04 that tells CPU, memory and disk trouble apart with uptime, top, vmstat, iostat and pidstat, and check that sysstat is recording history for sar the next time someone says the server was slow.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials