A program that deleted itself
An intruder starts a program, then deletes it from the disk. A disk image will never show it. But the program is still running, so every byte of it is still in memory.
Memory also holds what the program read, the shell commands that started it and who its parent was. This lesson takes the memory and reads all of that.
By the end of this lesson
Note
I can list the processes in a memory image and spot one disguised as something else.
Key words
| Word | What it means | Example |
|---|---|---|
| Memory image | a copy of a computer's RAM in a file | |
| Memory smear | memory changing while it is being copied | |
| Volatility | a free tool that reads memory images | vol linux.psaux |
| Symbol table | a map of the kernel's structures and addresses | |
| Command line | the words a process was started with | |
| Masquerading | giving a program a harmless-looking name |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsThe one rule
Important
Acquire and read only your own lab VM's memory. Another computer's memory holds its users' passwords and messages, so it needs written permission or a lawful order, under the Computer Misuse Act 1990. The intrusion here is made up, harmless and stays inside your VM.
Start a made-up intrusion in your VM
The first Run installs The Sleuth Kit and the other small tools. Volatility 3 and pakunoda come later, after the memory is taken. Then a script starts a made-up intrusion, as root. A stand-in server listens on 198.51.100.23, an address reserved for examples, put on your VM alone.
A copy of Python, renamed, talks to it, and a root shell types five commands.
Make the folder and install the tools
mkdir -p ~/forensics && cd ~/forensics && sudo apt-get install -y -qq sleuthkit dosfstools ewf-tools dcfldd foremost python3-venv fileShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the scene, part 1
printf '%s\n' 'import os' 'import pty' 'import shutil' 'import subprocess' 'import time' 'FAR = "198.51.100.23"' 'NL = chr(10)' 'for old in [["-x", "kworker"], ["-f", "labserver.py"], ["-f", "bash --norc"]]:' ' subprocess.run(["pkill", "-KILL"] + old)' 'time.sleep(1)' 'subprocess.run(["ip", "addr", "replace", FAR + "/32", "dev", "lo"])' 'os.makedirs("/srv/memlab", exist_ok=True)' 'open("/srv/memlab/labserver.py", "w").write(NL.join([' ' "import socket", "s = socket.socket()", "s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",' ' "s.bind((" + chr(34) + FAR + chr(34) + ", 443))", "s.listen()", "while True:", " c, a = s.accept()",' ' " while c.recv(100):", " pass", ""]))' 'quiet = dict(start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)' 'subprocess.Popen(["python3", "/srv/memlab/labserver.py"], stdin=subprocess.DEVNULL, **quiet)' 'time.sleep(1)' 'os.makedirs("/dev/shm/.k", exist_ok=True)' > scene.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the scene, part 2
printf '%s\n' 'shutil.copy("/usr/bin/python3", "/dev/shm/.k/kworker")' 'open("/dev/shm/.k/k.py", "w").write(NL.join([' ' "import socket, time",' ' "CONFIG = " + chr(34) + "server=" + FAR + ":443 id=LAB-7F3A sleep=30 note=made-up-for-the-lab" + chr(34),' ' "door = socket.socket()", "door.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)",' ' "door.bind((" + chr(34) + "0.0.0.0" + chr(34) + ", 4444))", "door.listen()",' ' "link = socket.create_connection((" + chr(34) + FAR + chr(34) + ", 443))",' ' "while True:", " link.send(b" + chr(34) + "LAB-7F3A hello" + chr(34) + ")", " time.sleep(30)", ""]))' 'subprocess.Popen(["[kworker/1:3]", "-"], executable="/dev/shm/.k/kworker", stdin=open("/dev/shm/.k/k.py"), **quiet)' 'time.sleep(2)' 'os.remove("/dev/shm/.k/kworker")' 'os.remove("/dev/shm/.k/k.py")' 'if os.fork() == 0:' ' os.setsid()' ' child, fd = pty.fork()' ' if child == 0:' ' os.execv("/bin/bash", ["bash", "--norc", "-i"])' >> scene.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the scene, part 3
printf '%s\n' ' for line in ["cd /dev/shm/.k", "id", "cat /etc/hostname", "ss -tn", "echo LAB-7F3A > note.txt"]:' ' os.write(fd, (line + NL).encode())' ' time.sleep(0.5)' ' while True:' ' try:' ' os.read(fd, 1000)' ' except OSError:' ' os._exit(0)' 'time.sleep(3)' 'print("The scene is running: a stand-in server, a renamed program and a root shell.")' >> scene.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Start the made-up intrusion
sudo python3 scene.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Memory is taken, then hashed
Memory changes thousands of times a second, and the tool copying it changes it too. So two acquisitions never match, and parts of one come from slightly different moments: memory smear.
You hash the memory image you took, at once. The script reads the VM's RAM through /proc/kcore into a LiME file, as Microsoft's AVML does. Run it twice and compare.
Write the memory grabber, part 1
printf '%s\n' 'import hashlib' 'import struct' 'import sys' 'ram = []' 'for line in open("/proc/iomem"):' ' if line[0].isspace() or not line.rstrip().endswith(": System RAM"):' ' continue' ' first, last = line.split(" ")[0].split("-")' ' ram.append((int(first, 16), int(last, 16)))' 'core = open("/proc/kcore", "rb")' 'head = core.read(64)' 'table_at = struct.unpack_from("<Q", head, 32)[0]' 'size, count = struct.unpack_from("<HH", head, 54)' 'core.seek(table_at)' 'table = core.read(size * count)' 'loads = []' 'for n in range(count):' ' kind, flags, offset, vaddr, paddr, filesz = struct.unpack_from("<IIQQQQ", table, n * size)' ' if kind == 1:' ' loads.append((paddr, filesz, offset))' > memgrab.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the memory grabber, part 2
printf '%s\n' 'digest = hashlib.sha256()' 'out = open(sys.argv[1], "wb")' 'total = kept = 0' 'for first, last in ram:' ' found = [seg for seg in loads if seg[0] <= first and last < seg[0] + seg[1]]' ' if not found:' ' print("skipped, not in /proc/kcore:", hex(first), hex(last))' ' continue' ' paddr, filesz, offset = found[0]' ' header = struct.pack("<IIQQ8x", 0x4C694D45, 1, first, last)' ' out.write(header)' ' digest.update(header)' ' core.seek(offset + first - paddr)' ' left = last - first + 1' ' while left > 0:' ' chunk = core.read(min(left, 1 << 20))' ' if not chunk:' ' break' ' out.write(chunk)' ' digest.update(chunk)' >> memgrab.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Write the memory grabber, part 3
printf '%s\n' ' left -= len(chunk)' ' total += len(chunk)' ' kept += 1' 'out.close()' 'print(kept, "ranges of memory,", total // (1 << 20), "MB written to", sys.argv[1])' 'print("sha256", digest.hexdigest())' >> memgrab.pyShown here, not run. Press Start lab to type it into your own lab’s terminal.
Acquire this VM's memory twice
sudo python3 memgrab.py mem.lime && sudo python3 memgrab.py mem2.lime && rm -f mem2.limeShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsVolatility needs a map of the kernel
Memory is bytes with no labels. To find the process list, Volatility must know where the kernel keeps it and how its structures are laid out. That map is a symbol table, made for one exact kernel.
Ubuntu's kernel describes its own structures inside itself, and pakunoda reads that out of the image. Install it only now. Anything installed earlier is in the memory too, and pakunoda's own files hold another kernel's sample banner that can mislead it.
Install Volatility and pakunoda, then build the table
python3 -m venv ~/memtools && ~/memtools/bin/pip install -q volatility3==2.28.2 pakunoda==1.1.0 && . ~/memtools/bin/activate && pakunoda extract mem.lime -o symbols/ && rm -f ~/.cache/volatility3/identifier.cacheShown here, not run. Press Start lab to type it into your own lab’s terminal.
A name is only a label
Each process has a short name and a command line, and a program can set both. Masquerading picks a harmless-looking name, such as a kernel worker's.
A real kernel worker has kthreadd, process 2, as its parent, and a name that says which CPU it runs on. Compare the real ones with the scene's processes.
Show kernel workers and the scene's processes
vol -q -f mem.lime -s symbols linux.psaux | awk '$3 ~ /^kworker.0:/ || $3 == "kworker" || /labserver|norc/'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsWhat the disguised process holds
Keep its process id, then ask which program it has mapped and which files it has open. Both its program and the script it read were deleted, yet memory still names them.
A dump of its memory, searched for readable words, shows what it was set up to do. linux.bash finds the commands a shell kept in memory.
Keep its id, read its program and files
KPID=$(vol -q -f mem.lime -s symbols linux.psaux | awk '$3 == "kworker" {print $1}') && echo $KPID && vol -q -f mem.lime -s symbols linux.proc.Maps --pid $KPID | grep deleted && vol -q -f mem.lime -s symbols linux.lsof --pid $KPID | grep -e deleted -e socketShown here, not run. Press Start lab to type it into your own lab’s terminal.
Dump its memory and search for settings
mkdir -p dump && (cd dump && vol -q -f ../mem.lime -s ../symbols linux.proc.Maps --pid $KPID --dump > /dev/null && grep -a -h -o "server=[^ ]* id=[^ ]*" *.dmp | sort -u)Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Recover the root shell's history
vol -q -f mem.lime -s symbols linux.bash --pid $(vol -q -f mem.lime -s symbols linux.psaux | awk '/bash --norc/ {print $1}')Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think the name in a process list is the program that runs. A process can set its own name and command line. Check its parent, its mapped program and its open files. On a live machine, ls -l /proc/*/exe shows (deleted) beside such a program, a cheap check to alert on.
Check
Have a go
Check
3 questionsAssignment: find a disguised process
A process is a dictionary with "pid", "ppid", "comm" (its short name), "args" (its command line) and "exe" (the path of its program, or "" for a kernel thread).
is_kernel_thread(proc) is True when the pid is 2 or the ppid is 2, and exe is empty.
suspects(procs, cpus) returns the pids, in order, of user processes (not kernel threads) that look wrong: their args start with [, or their exe ends with (deleted), or their name is kworker/N:... with N not below cpus.
reasons(proc, cpus) returns the list of reasons for one process, in this order, using exactly these words: "bracketed args", "deleted program", "no such cpu".
def is_kernel_thread(proc):
return False
def reasons(proc, cpus):
return []
def suspects(procs, cpus):
return []
Make a free account to save your work and track your progress.
Exit quiz
Have a go