6. Dynamic Analysis: Watching a Sample Run
Debuggers, breakpoints, single-stepping and call tracing on Windows and Linux: how analysts run a suspicious program under control inside the lab, what to watch while it runs, and how to make sense of what it does
Reading a recipe tells you a great deal about a dish: the ingredients, the order, the oven temperature. But some things only show up when somebody actually cooks it. The recipe says "season to taste", and you have no idea what the cook will reach for. It says "use the sauce from yesterday", and yesterday's sauce isn't in the book. Now imagine you could watch the cook through a glass wall, with a pause button that freezes the kitchen mid-stir so you can look into every pot, and a camera log that records every cupboard opened and every delivery that arrives at the back door.
That is dynamic analysis. The disassembly article read the recipe: we recovered a buffer's contents without running a single instruction. This article watches the cook. A debugger is the pause button: it stops the program wherever we choose and lets us read every register and every byte of memory. A tracer is the camera log: it records every system call, file, registry key and network connection, at full speed. Between them, they answer the questions static analysis can't: what a value turned out to be on this machine, which files the program actually touched, who it tried to talk to.
We'll go through both halves on Windows and Linux side by side: how a debugger takes control of another process, how breakpoints, watchpoints and single-stepping actually work underneath, how to trace a program's calls and filter the noise down to the handful of events that matter, what to watch while it runs, and what automated sandboxes do for you.
Everything here is synthetic and harmless, and real samples stay in the lab
The machine code on this page is a harmless 58-byte toy written for this article: the
little XOR decoder from the disassembly article, here
decoding the greeting hello, lab!. The traces and logs describe an equally
harmless synthetic "greeter" program that reads a config file, writes a log, runs one
system command and fetches a text file. Every log line, process and path is invented to
illustrate a technique. Domains are reserved names, shown defanged
(lab-greeting[.]test), and IP addresses come from the ranges reserved for
documentation. Nothing in this article
executes anything. Running a real sample, even under a debugger, means running it: that
belongs only inside the isolated lab, following its rules.
What Running It Adds
Static analysis has two great strengths: it's safe, because nothing runs, and it's complete, because every path through the code is there to read, including the ones that only run on the 1st of the month. Its weakness is that some answers simply aren't in the file:
- Values computed at run time. A key derived from the computer name, a setting read from a file that only exists on the victim, a name built from today's date.
- Code that isn't there yet. A packed program's real code only exists in memory once the unpacking stub has run. A downloader's next stage arrives over the network.
- Code that's too expensive to read. A 400-instruction obfuscated routine that you could reason through in an afternoon, or watch produce its output in a second.
- Behaviour that depends on the environment. Which files it looks for, which registry keys it reads, what it does when they're missing.
Dynamic analysis answers those by observation. It comes in two flavours, and you'll use both on almost every sample:
Behavioural: let it run and record
Run the program at full speed with monitors around it: a process tree, a file and registry log, a system-call trace, a packet capture. Fast and broad. It tells you what happened, but not why, and not what would have happened under other conditions.
Controlled: run it under a debugger
Stop the program at chosen points, inspect its registers and memory, and step through the code one instruction at a time. Slow and narrow, but exact: you can watch a value being computed, dump a decoded buffer, and confirm what you read in the disassembler.
The two feed each other. A trace says "it wrote a file to AppData and then connected
out"; the debugger, with a breakpoint on the write, shows you the code that chose the file
name. And both feed back into static analysis: every address you stop at is a function you
can now name in your disassembler database.
The Rules Before You Press Run
Everything in the lab article was built for this moment. Dynamic analysis is the point at which untrusted code actually executes, so the rules are not optional, and they don't relax because you're "only" stepping through it in a debugger. A debugger can lose control (a missed breakpoint, a thread you weren't watching, a child process it didn't follow) and then the program is simply running.
-
Isolated VM, nothing shared
The sample runs only in a victim VM on the internal lab network: no bridged or NAT adapter, no shared folders, no shared clipboard, no drag-and-drop (network isolation). Check it every time, not just the first time.
-
Clean snapshot before, revert after
Start from the
CLEANsnapshot and revert to it when you're done, even if "nothing happened" (snapshots). Never snapshot a used state as your new baseline. If you'll want to come back to an interesting moment, take a clearly named, throwaway snapshot of the used VM, and treat it as contaminated forever. -
No real network: a simulated one
The sample's DNS and HTTP go to the gateway VM running INetSim or FakeNet-NG. Its fake DNS server answers every name with the gateway's own address, and its fake web server answers every request with a harmless default file. The program believes it's online; you get a log of every name it looked up and every URL it asked for, and nothing leaves the lab. A packet capture runs on the gateway for every run.
-
Get logs out as text, not samples
Traces, packet captures and notes leave the victim VM through the channel your handling rules allow, and any file the program created leaves as a password-protected archive, exactly like an incoming sample.
The lab's pre-detonation checklist is the one to run through before every session in this article.
A note on addresses in this article's logs
To keep to the documentation ranges, every synthetic log here shows the lab's
fake-internet gateway as 192.0.2.1. In your own lab it will be whatever
address you gave the gateway VM.
Debuggers on Windows and Linux
A debugger is a program that controls another program: it can start or attach to it, stop it, read and change its registers and memory, and resume it. Three tools cover nearly all user-mode analysis:
| Tool | Platform | Best at |
|---|---|---|
| x64dbg | Windows | User-mode programs |
| WinDbg | Windows | Kernel, dumps, TTD |
| gdb + pwndbg / GEF | Linux | ELF programs |
- x64dbg is the open-source workhorse of Windows malware analysis, with a graphical CPU
view (disassembly, registers, stack and a memory dump on one screen), a large plugin
ecosystem, and two programs in one:
x64dbgfor 64-bit programs andx32dbgfor 32-bit ones. A 32-bit PE needsx32dbg; the PE article showed how to tell them apart. It's included in FLARE-VM. - WinDbg is Microsoft's debugger, command-line at heart behind a modern interface. It debugs user mode, the kernel and crash dumps, understands Microsoft's symbol files better than anything else, and supports Time Travel Debugging: record a run once, then step backwards and forwards through it at leisure.
- gdb, the GNU debugger, is on every Linux system. On its own it's terse; the
pwndbg and GEF extensions turn it into something much closer to x64dbg, printing
registers, the stack, nearby code and memory after every stop, and adding commands such
as pwndbg's
vmmap(the memory map) andtelescope(follow pointers on the stack).
Underneath the interfaces they all rely on the same small set of services from the operating system and the CPU. Understanding those services is what makes debugger behaviour make sense.
How a Debugger Takes Control
One process can't normally reach into another's memory or freeze its threads. A debugger can because the operating system gives it a special, privileged relationship with its target (or debuggee), and both systems shape that relationship as the same loop: wait for the target to stop, look at it, resume it.
Linux: ptrace
On Linux the whole relationship is one system call, ptrace. A debugger becomes a process's tracer in one of two ways:
- Start the program itself. gdb forks; the child calls
ptrace(PTRACE_TRACEME)to make its parent its tracer, thenexecves the program. The kernel stops the new program before its first instruction runs. - Attach to a running process with
PTRACE_ATTACH(which stops it withSIGSTOP) orPTRACE_SEIZE(which attaches without stopping it). Many distributions restrict this with the Yama security module: withkernel.yama.ptrace_scopeset to 1 (Ubuntu's default, and common elsewhere), you can only attach to your own descendants unless you're root.
Every time the target stops (it hit a breakpoint, received a signal, finished a single
step), the kernel freezes that thread and the tracer's waitpid() returns to say so. The
tracer then reads registers with PTRACE_GETREGS, reads and writes memory a word at a time
with PTRACE_PEEKDATA and PTRACE_POKEDATA (or in bulk through /proc/PID/mem), and lets
the target go with PTRACE_CONT, or PTRACE_SINGLESTEP for exactly one instruction. A
thread can have only one tracer at a time.
Windows: the debugging API and debug events
Windows builds the same loop from a handful of documented functions. The debugger either
starts the program with CreateProcess and the DEBUG_PROCESS (or DEBUG_ONLY_THIS_PROCESS)
flag, or attaches to a running process with DebugActiveProcess. From then on, the system
reports what happens in the target as debug events, which the debugger collects with
WaitForDebugEvent:
CREATE_PROCESS_DEBUG_EVENTandCREATE_THREAD_DEBUG_EVENT,EXIT_THREAD_DEBUG_EVENTandEXIT_PROCESS_DEBUG_EVENT: the target's processes and threads coming and going.LOAD_DLL_DEBUG_EVENTandUNLOAD_DLL_DEBUG_EVENT: a DLL mapped or unmapped. This is when a debugger loads symbols, and how x64dbg can stop when a particular DLL arrives.EXCEPTION_DEBUG_EVENT: every exception, including breakpoints (EXCEPTION_BREAKPOINT), single steps (EXCEPTION_SINGLE_STEP) and access violations.OUTPUT_DEBUG_STRING_EVENT: the target calledOutputDebugString. AndRIP_EVENT, which reports a system debugging error.
While an event is being reported, all threads of the target are suspended. The debugger
reads registers with GetThreadContext, memory with ReadProcessMemory, changes them with
SetThreadContext and WriteProcessMemory, and resumes the target with
ContinueDebugEvent. When it continues an exception, it says whether it handled it
(DBG_CONTINUE) or wants the target's own exception handlers to see it
(DBG_EXCEPTION_NOT_HANDLED): a choice that matters when a program uses exceptions as part
of its normal control flow.
The first stop
Both systems stop the target before the program's own code runs, which is exactly what you
want: nothing has happened yet. On Linux, gdb's starti stops at the very first instruction
of the program (for a dynamically linked ELF, that's inside the dynamic loader), and start
runs to a temporary breakpoint on main when there are symbols to find it. On Windows the
first exception a debugger sees is the system breakpoint inside ntdll, raised by the
loader while it is still setting the process up; x64dbg stops there by default, and again
at the program's entry point.
Remember from the PE and ELF articles that
code can run before the entry point: TLS callbacks on Windows, constructors in
.init_array on Linux. A debugger set to stop "at the entry point" stops too late to see
that code run. x64dbg has an option to break on TLS callbacks; on Linux, start with
starti and set your breakpoints on the constructors you found statically.
Breakpoints: Three Ways to Stop
A breakpoint is a request: stop the target when it gets here, or touches this. The CPU
can't take orders from a debugger directly, so each kind of breakpoint is built from a
hardware feature that makes the CPU raise an exception, which the operating system turns into
a debug event or a SIGTRAP for the debugger. There are three such features, with very
different costs and limits.
Software breakpoints: int3 and the byte swap
The oldest trick is the most common. x86 has a one-byte instruction, int3 (opcode CC),
whose only job is to raise a breakpoint exception. To set a breakpoint at an address, the
debugger simply overwrites the first byte of the instruction there with CC, and
remembers the byte it replaced.
Here it is on our toy. The function decode_greeting starts at 0x401025 with
push rbp (55), followed by mov rbp,rsp (48 89 E5). A breakpoint on it goes through
four stages:
In pseudocode, a debugger's software-breakpoint handling looks like this:
set_breakpoint(addr):
saved[addr] = read_byte(addr)
write_byte(addr, 0xCC)
flush_instruction_cache(addr) # Windows: FlushInstructionCache
on_breakpoint_trap(thread):
addr = thread.rip - 1 # int3 is one byte, and rip is past it
if addr not in saved:
pass it to the program; return # an int3 the program contained itself
write_byte(addr, saved[addr]) # show the real code
thread.rip = addr
report "breakpoint at addr"
on_resume(thread):
addr = thread.rip
if addr in saved: # we're sitting on a breakpoint
single_step(thread) # run the original instruction once
write_byte(addr, 0xCC) # and put the trap back
continue(thread)
Real debuggers differ in the details: gdb, by default, writes all its breakpoints into memory
each time the target resumes and takes them all out each time it stops, so x/x in gdb
shows you the real bytes. The consequences are the same everywhere, and worth memorising:
- Unlimited and cheap. You can set thousands; the target runs at full speed between them.
- Execution only. A software breakpoint fires when the CPU executes the byte. It can't tell you when something reads or writes memory.
- They change the program's code. While the target is running, the byte really is
CC. Your debugger shows you the original byte when it displays memory, but what the CPU fetches, and what any code reading that address gets, isCC. - Rewritten code erases them. If the program overwrites the region at run time, your
CCgoes with it, and the breakpoint silently stops working.
Hardware breakpoints: DR0 to DR7
x86 CPUs have a second mechanism built into the chip: the debug registers. Four of them, DR0 to DR3, each hold one address. DR7, the control register, says for each of those four slots whether it's enabled and what should trigger it:
- Execute: the CPU is about to run the instruction at that address.
- Write: anything writes to that address.
- Read or write: anything touches it (x86 has no read-only condition).
- (A fourth condition, I/O port access, is rarely relevant to user-mode analysis.)
Data conditions also take a length of 1, 2, 4 or 8 bytes, and the address must be
aligned to that length. When a slot triggers, the CPU raises a debug exception, and DR6,
the status register, records which slot fired (DR4 and DR5 are reserved). An execute
breakpoint fires before the instruction runs; a data breakpoint fires after the access,
with rip already on the next instruction.
Hardware breakpoints solve the software breakpoint's problems: they don't modify a single byte of the program, so code that is rewritten at run time doesn't erase them, and they can catch reads and writes, which is how you answer "who writes this buffer?" or "when does this string change?". A data breakpoint is usually called a watchpoint. Their limit is hard and absolute: four at a time, because there are four address registers. The debug registers are also part of each thread's saved state (they live in the thread context), so the debugger has to set them on every thread it wants covered, including threads created later.
Software (int3)
Unlimited. Execution only. Rewrites one byte of code, which anything reading that
address sees, and which rewriting the code erases. x64dbg F2, WinDbg bp,
gdb break.
Hardware (DR0 to DR3)
Four per thread. Execute, write or read/write, 1 to 8 bytes. Changes no memory.
x64dbg bph, WinDbg ba, gdb hbreak and
watch.
Memory breakpoints: guard pages
What if you want to stop when the program touches anything in a 64 KB buffer, or executes anywhere in a region it filled at run time? Four hardware slots of at most 8 bytes each can't cover that. The third mechanism borrows the memory manager instead: change the protection of the page (the 4 KB unit the CPU protects memory in) so that any access faults.
On Windows the natural tool is a
guard page:
x64dbg's memory breakpoints (bpm) mark every page of the memory region as PAGE_GUARD
(or, optionally, no-access). The first access raises an exception, the debugger checks
whether it was the kind of access you asked for (read, write or execute), and, if you asked
for the breakpoint to be restored, re-protects the page after stepping past the access.
Two consequences: memory breakpoints are slow when the region is busy, because every
access to every byte of those pages stops the target; and they are coarse, because they
fire on the whole page, including unrelated data that shares it.
A common use is to put an execute memory breakpoint on a region the program writes code into at run time, run, and let the debugger stop on the first instruction executed there. gdb has no guard-page breakpoints; on Linux you'd use hardware watchpoints for small ranges or reach for other tools. gdb can fall back to software watchpoints when it runs out of hardware ones, by single-stepping the whole program and checking the value after every instruction, which works but is extremely slow.
Stepping Through Code
Breakpoints get you to the interesting place; stepping lets you walk through it.
Single-stepping and the trap flag
The CPU supports single-stepping directly. Bit 8 of rflags is the trap flag (TF). When
it's set, the CPU executes one instruction and then raises a debug exception, with the
single-step bit (BS) set in DR6. A debugger's "step into" is: set TF on the thread, resume,
wait for the exception, clear TF. PTRACE_SINGLESTEP on Linux does exactly that for you;
on Windows the debugger sets TF in the thread context itself and receives an
EXCEPTION_SINGLE_STEP event. That's also the "step one, then re-arm" in stage 4 of the
software-breakpoint picture above.
Step into, step over, run to return
The difference between the stepping commands is what they do at a call:
- Step into executes exactly one instruction. On a
call, you land on the first instruction of the called function. - Step over treats a
callas one step. Underneath, the debugger puts a temporary breakpoint on the instruction after the call (the return address) and resumes at full speed. For anything other than a call it's a single step. Beware: if the called function never returns normally (it exits, throws, or longjmps), "step over" never stops. - Run to return finishes the current function. gdb's
finishand WinDbg'sgu("go up") run until the function returns and stop in the caller; x64dbg's "Execute till return" steps over until the current instruction is aretand stops on theret, so one more step takes you back to the caller.
When a debugger can't unwind the stack (no symbols, no frame information, obfuscated code),
you can always run to return by hand: at the first instruction of a function, the return
address is at [rsp]. Read it, put a temporary breakpoint there, and continue.
| Action | x64dbg / WinDbg | gdb |
|---|---|---|
| Continue | F9 / g |
continue |
| Step into | F7 / t |
stepi |
| Step over | F8 / p |
nexti |
| Run to return | Ctrl+F9 / gu |
finish |
| Software bp | F2 / bp |
break *addr |
| Hardware bp | bph / ba e1 |
hbreak *addr |
| Write watch | bph addr, w / ba w8 |
watch |
(WinDbg steps by source line when it has source; switch to assembly mode to step by
instruction. gdb's step and next, without the i, also step by source line, and on a
stripped program there are no lines to step by.)
Reading Registers, the Stack and Memory
Whenever the target is stopped, the debugger can show you three things, and between them they are the entire state of the thread:
- Registers.
rip(where we are),rsp(the top of the stack), the general-purpose registers holding arguments and results, andrflags, shown as individual flags (ZF, CF, SF, OF, TF and the rest). - The stack. The memory at and above
rsp: return addresses, saved registers, locals, and on Windows the home space and fifth-and-later arguments. pwndbg and x64dbg annotate each slot: "this is a return address intomain", "this points to a string". - Memory. Any address you like, as bytes, words, quadwords, a string or disassembly.
The memory map (x64dbg's Memory Map tab, pwndbg's
vmmap, gdb'sinfo proc mappings) shows which regions exist and with what protection; a private region marked executable that no file explains is always worth a closer look.
The toy
Here is the toy program the rest of this section steps through. It has exactly the shape of the
58-byte buffer from the disassembly article, with different data:
main passes an 11-byte buffer, its length and the key 0x5a to decode_greeting, which
XORs the bytes in place, and then returns 0. Loaded at 0x401000:
401000: 48 8d 3d 12 00 00 00 lea rdi,[rip+0x12] # 0x401019
401007: be 0b 00 00 00 mov esi,0xb
40100c: ba 5a 00 00 00 mov edx,0x5a
401011: e8 0f 00 00 00 call 0x401025 # decode_greeting
401016: 31 c0 xor eax,eax
401018: c3 ret # return 0
401019: 32 3f 36 36 35 76 7a 36 3b 38 7b 00 # 11 encoded bytes + 00
401025: 55 push rbp # decode_greeting
401026: 48 89 e5 mov rbp,rsp
401029: 31 c0 xor eax,eax
40102b: eb 06 jmp 0x401033
40102d: 30 14 07 xor BYTE PTR [rdi+rax*1],dl
401030: 48 ff c0 inc rax
401033: 48 39 f0 cmp rax,rsi
401036: 72 f5 jb 0x40102d
401038: 5d pop rbp
401039: c3 ret
The encoded bytes happen to be printable: as text they read 2?665vz6;8{. XORed with
0x5a, they become hello, lab!.
Worked example: watching the greeting decode
Suppose we've wrapped the buffer in a minimal ELF with one read-write-execute segment, whose start-up stub calls 0x401000 and
exits with its return value. We'll stop at decode_greeting, read its arguments, watch the
buffer change one byte at a time, and run to the return. An illustrative, slightly
simplified gdb session on the Linux victim:
$ gdb -q ./toy
(gdb) starti
Program stopped.
0x0000000000401040 in ?? () # the start-up stub
(gdb) break *0x401025
Breakpoint 1 at 0x401025
(gdb) continue
Continuing.
Breakpoint 1, 0x0000000000401025 in ?? ()
(gdb) info registers rdi rsi rdx rsp
rdi 0x401019 4198425
rsi 0xb 11
rdx 0x5a 90
rsp 0x7fffffffe3f0 0x7fffffffe3f0
(gdb) x/gx $rsp
0x7fffffffe3f0: 0x0000000000401016
(gdb) x/s 0x401019
0x401019: "2?665vz6;8{"
(gdb) watch -l *(char (*)[11])0x401019
Hardware watchpoint 2: -location *(char (*)[11])0x401019
(gdb) continue
Continuing.
Hardware watchpoint 2: -location *(char (*)[11])0x401019
Old value = "2?665vz6;8{"
New value = "h?665vz6;8{"
0x0000000000401030 in ?? ()
(gdb) continue
Continuing.
Hardware watchpoint 2: -location *(char (*)[11])0x401019
Old value = "h?665vz6;8{"
New value = "he665vz6;8{"
0x0000000000401030 in ?? ()
(gdb) delete 2
(gdb) tbreak *0x401016
Temporary breakpoint 3 at 0x401016
(gdb) continue
Continuing.
Temporary breakpoint 3, 0x0000000000401016 in ?? ()
(gdb) x/s 0x401019
0x401019: "hello, lab!"
Reading the session
- The software breakpoint. While the program ran, the byte at
0x401025wasCC; now that it's stopped, gdb has put the55back, sox/xb 0x401025shows0x55. What you see in a debugger's memory view is the debugger's view, not necessarily what the CPU fetched. - The arguments are where the convention says. System V puts the
first three arguments in
rdi,rsi,rdx(calling conventions): buffer0x401019, length 11, key0x5a. Static analysis predicted exactly this; now we've seen it. - The top of the stack is the return address,
0x401016, pushed by thecall. Setting a temporary breakpoint there is "run to return" done by hand. - The watchpoint stops after each write. Each stop is at
0x401030, theinc raxafter thexor BYTE PTR [rdi+rax*1],dlthat wrote the byte, because data breakpoints are traps. gdb covers the 11 unaligned bytes by splitting them into aligned pieces, which on x86 can take every one of the four debug registers. - Before and after. The 11 bytes at
0x401019were encoded; after the function returns they readhello, lab!. On a real sample this is the moment to dump the buffer to a file for your notes.
The choice between stepping into and stepping over the call at 0x401011 decides how
much of that you see:
Step into at 0x401011
rip 0x401025 push rbp
rsp 0x7fffffffe3f0
[rsp] 0x401016 (return)
One instruction: you're at the top of decode_greeting, ready to watch
the loop.
Step over at 0x401011
rip 0x401016 xor eax,eax
rax 0xb
0x401019: "hello, lab!"
All 52 instructions inside `decode_greeting` run at full speed: the string is already decoded.
Fifty-two, because the function runs 4 set-up instructions, 11 passes of the 4-instruction
loop, one last cmp and jb that falls through (with rax and rsi both 11, ZF is set
and CF clear), then pop and ret. Step over is how you skip what you already understand;
step into, a breakpoint or a watchpoint is how you see what you don't.
Tracing Calls: The Camera Log
A debugger shows one moment in great detail. A tracer shows the whole run, one line per event, at close to full speed. On both systems the most useful boundary to watch is where the program asks the operating system to do something, because almost everything a program does to the outside world (files, registry, processes, network) has to cross it.
Linux: strace and ltrace
strace is a ptrace-based tracer built on PTRACE_SYSCALL, which stops the target at every
system call's entry and exit. At entry strace reads the arguments, at exit the
return value, and it prints one decoded line per call. The options that matter most for
analysis:
$ strace -f -tt -y -s 128 -o trace.txt ./sample.bin
# -f follow children (fork, vfork, clone): essential
# -tt wall-clock timestamps with microseconds
# -y print the path or socket behind every file descriptor
# -s 128 show up to 128 characters of each string or buffer
# -o FILE write to a file (with -f: every line starts with the PID)
$ strace -f -e trace=%file,%process,%network ./sample.bin # only these classes
$ strace -f -e trace=openat,connect,execve ./sample.bin # only these calls
$ strace -p 2207 # attach to a running PID
ltrace works one level up: it puts breakpoints on the program's
PLT entries and reports calls into shared libraries, such as getenv,
strcmp or fopen, with their arguments. That's often where the logic is: a strcmp
against a value from a config file shows you the decision directly, where a syscall trace
would show only the file being read. Its limit follows from how it works: a statically
linked binary has no PLT, so ltrace sees nothing, and plenty of Linux malware is static.
Both tools are ptrace tracers, so everything about ptrace applies: they slow the program
down, they can follow children, and they occupy the one tracer slot. For observation from
the kernel, with no tracer attached at all, use the lab's
auditd rules.
Windows: Procmon, API Monitor and ETW
Windows has no single strace, but three tools between them cover the same ground:
- Process Monitor (Procmon, from Sysinternals) records file system, registry, process and thread, image-load and network activity for every process on the machine, each event with its process, PID, operation, path, result and details, plus the call stack that produced it. It's the first thing most analysts start before a run. Its filters and highlighting are how you get from a million events to a dozen, and its Process Tree view (in the Tools menu) shows every process that started during the capture.
- API Monitor (from Rohitab) works like
ltrace: it hooks functions in the target's DLLs and logs each API call with decoded parameters and return values, and it can break on a chosen call. Because it works from inside the target process, it changes that process more than Procmon, which watches from the kernel. - ETW is the operating system's own tracing framework: providers (the kernel, the network stack, the DNS client, PowerShell, hundreds more) publish events, a session collects the ones you enable, and consumers read them, live or from a file. You rarely use it directly for a first look, but many tools, including Sysmon and much of what endpoint security products record, build on the same kinds of kernel and ETW instrumentation.
Filtering a Noisy Trace
The first time you trace even a trivial program, the volume is a shock. Before a dynamically
linked ELF reaches main, the loader has already made dozens of system calls: mapping
libc, reading /etc/ld.so.cache, setting up thread-local storage, loading locale files. A
Procmon capture of ten idle seconds on Windows holds tens of thousands of events from
Explorer, the indexer, services and Procmon itself. The skill is not reading the trace; it's
throwing most of it away without throwing away the one line that matters.
-
Scope to the program and its children
Filter by process: Procmon's Process Name is sample.exe, then add each child by PID as it appears (or use the Parent PID column). With
strace -fevery line already carries a PID; collect the PIDs fromcloneandexecve. -
Drop the start-up noise
Library and DLL loads, locale files,
mmapandbrk, thread setup, the resolver reading its own configuration. Skip everything before the first event that isn't loader work. -
Keep the operations that change things
Process creation, file writes, renames and deletes, registry value writes, network connections. Reads and queries can come back later.
-
Then look at failures, on purpose
A file or registry key the program looked for and didn't find (
ENOENT,NAME NOT FOUND) tells you about its logic: a config location it tries first, a default it falls back to, a condition it checks. Usually noise, occasionally the key to the whole run. -
Highlight the places that matter
Persistence locations (
Runkeys, services, scheduled tasks, cron and systemd directories), executable files being written, new processes, and network activity. In a report, an empty result for one of these is a finding too.
Here's that process on an illustrative, synthetic Linux trace of the harmless greeter. The
full capture from strace -f -tt -s 128 -o trace.txt ./sample.bin is 146 lines; this
excerpt keeps the start, a few kinds of noise, and every event that matters (timestamps
removed, long arguments shortened, and the domain defanged in the listing):
2207 execve("./sample.bin", ["./sample.bin"], 0x7ffc8a1e2b40 /* 21 vars */) = 0
2207 openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
2207 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
2207 mmap(NULL, 2170256, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7f3a2c000000
... 61 more lines of loader start-up ...
2207 openat(AT_FDCWD, "/home/user/.config/greeter/greeter.conf", O_RDONLY) = -1 ENOENT (No such file or directory)
2207 openat(AT_FDCWD, "/etc/greeter.conf", O_RDONLY) = 3
2207 read(3, "name=lab\nserver=lab-greeting[.]test\n", 4096) = 34
2207 mkdir("/tmp/greeter", 0700) = 0
2207 openat(AT_FDCWD, "/tmp/greeter/run.log", O_WRONLY|O_CREAT|O_APPEND, 0600) = 4
2207 write(4, "started\n", 8) = 8
2207 clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, ...) = 2208
2208 execve("/usr/bin/uname", ["uname", "-a"], ...) = 0
... 38 lines of uname's own start-up and output ...
2207 wait4(2208, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 2208
... 24 lines of the resolver reading nsswitch.conf, hosts and resolv.conf ...
2207 socket(AF_INET, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, IPPROTO_IP) = 5
2207 connect(5, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("192.0.2.1")}, 16) = 0
2207 sendto(5, "\244\37\1\0\0\1\0\0\0\0\0\0\flab-greeting\4test\0\0\1\0\1", 35, MSG_NOSIGNAL, NULL, 0) = 35
2207 recvfrom(5, "\244\37\201\200...\300\0\2\1", 2048, 0, ...) = 51
2207 socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) = 6
2207 connect(6, {sa_family=AF_INET, sin_port=htons(80), sin_addr=inet_addr("192.0.2.1")}, 16) = 0
2207 write(6, "GET /hello.txt HTTP/1.1\r\nHost: lab-greeting[.]test\r\nUser-Agent: greeter/1.0\r\n\r\n", 77) = 77
2207 read(6, "HTTP/1.1 200 OK\r\nServer: INetSim HTTP Server\r\n"..., 4096) = 312
2207 write(4, "fetched hello.txt\n", 18) = 18
2207 exit_group(0) = ?
Read it as a story, and 146 lines filter down to six facts. The program looked for a
per-user config file, didn't find it (the ENOENT is the "look at failures" step paying
off: it tells you where a user could override the settings), and read the system-wide
one instead, which names the server. It created a log file under /tmp/greeter. It
ran one child process, uname -a, and waited for it. It looked up
lab-greeting[.]test (the name is visible in the raw DNS packet, and \300\0\2\1 at the
end of the reply is the fake answer, 192.0.2.1, in strace's octal escapes), fetched
/hello.txt with a distinctive User-Agent and got INetSim's default page back, and logged
that it had done so. No persistence, no executable written, nothing deleted.
The same program's Windows build, captured in Procmon and filtered to the program and its
children (plus one svchost.exe row, explained below), tells the same story with Windows nouns (columns trimmed):
Process PID Operation Path / detail
sample.exe 4312 Load Image C:\Windows\System32\ntdll.dll
sample.exe 4312 RegOpenKey HKLM\System\CurrentControlSet\Control\Session Manager
... 1,930 more events of start-up, DLL loads and registry queries ...
sample.exe 4312 CreateFile C:\Users\analyst\AppData\Local\Greeter\greeter.ini NAME NOT FOUND
sample.exe 4312 CreateFile C:\ProgramData\Greeter\greeter.ini
sample.exe 4312 ReadFile C:\ProgramData\Greeter\greeter.ini Length: 34
sample.exe 4312 CreateFile C:\Users\analyst\AppData\Local\Temp\Greeter\run.log
sample.exe 4312 WriteFile ...\AppData\Local\Temp\Greeter\run.log Length: 9
sample.exe 4312 Process Create C:\Windows\System32\cmd.exe PID: 5124 cmd /c ver
... cmd.exe's own start-up and output ...
cmd.exe 5124 Process Exit Exit Status: 0
svchost.exe 1388 UDP Send analyst-pc:53214 -> 192.0.2.1:domain
sample.exe 4312 TCP Connect analyst-pc:49712 -> 192.0.2.1:http
sample.exe 4312 TCP Send analyst-pc:49712 -> 192.0.2.1:http Length: 77
sample.exe 4312 TCP Receive analyst-pc:49712 -> 192.0.2.1:http Length: 312
sample.exe 4312 WriteFile ...\AppData\Local\Temp\Greeter\run.log Length: 19
sample.exe 4312 Process Exit Exit Status: 0
One detail is worth spelling out. The DNS lookup belongs to svchost.exe, not to the
program: most Windows programs resolve names through the DNS Client service, which runs in
svchost, so a filter on the program's process name alone hides its DNS traffic. The fake
DNS server's log on the gateway, or the packet capture, shows which name was asked for, and
the TCP Connect that follows straight after ties the lookup back to the program.
What to Watch While It Runs
A trace is one view of a run. A full run records several, because each answers a different question and each can miss something the others catch. These are the five views analysts gather on every run, and the tools that provide them:
| Question | Windows | Linux |
|---|---|---|
| What started? | Process Explorer, Procmon | pstree, auditd |
| Which files? | Procmon | auditd, inotify |
| Which registry keys? | Procmon, Regshot | (none) |
| Who did it talk to? | Wireshark on the gateway | tcpdump on the gateway |
| Will it survive a reboot? | Autoruns, Regshot | diff cron, systemd, shell rc |
The process tree
Programs rarely stay one process. They spawn a shell to run a command, start a helper, or launch other programs. The process tree, with parent-child links, command lines and timing, is often the fastest summary of a run.
On Windows, Process Explorer shows the live tree with command lines, and Procmon's
Process Tree reconstructs it after the fact, including processes that lived for a fraction
of a second, like our cmd /c ver. On Linux, strace -f output already contains the tree
(every clone result is a new PID, every execve names its program), pstree -p and
ps -ef --forest show the live one, and the auditd execve rule from the lab records every
program start with its arguments and parent.
The file system and the registry
Two complementary approaches: record every change as it happens, or diff before and after.
- Record: Procmon on Windows, auditd watches on Linux, and
inotifywait(from inotify-tools) for a live view of a directory tree. One caveat: inotify reports what changed but not which process changed it; auditd and fanotify can tell you who. - Diff: Regshot takes a "1st shot" of the registry (and optionally chosen
directories) before the run and a "2nd shot" after, and lists every key and value
added, deleted or modified. On Linux the simplest diff is a marker file:
touch /tmp/markerbefore the run, thenfind / -xdev -newer /tmp/markerafterwards lists every file modified since. A diff catches changes a filtered trace dropped, and a trace catches changes that were undone before you took the second snapshot (temporary files, for instance). Use both.
The network
All the network evidence comes from outside the victim, which is the beauty of the lab
design: the gateway records what actually went over the wire, independently of any tool
running on the victim. Three sources: the fake DNS log (every name it resolved, which
is how you learn domains even when the program never connects), the fake services' logs
(full HTTP requests, with paths, headers and bodies; INetSim logs per service), and a
packet capture with tcpdump or Wireshark on the gateway's lab interface, which records
everything, including protocols the fake services don't speak. For the deeper reading of
those captures, see the Networking series.
Persistence
Persistence is what turns a one-off execution into a lasting compromise, so every report should say whether it was found. These are the usual places to check, and to diff:
- Windows: the
RunandRunOncekeys underHKCUandHKLM, services, scheduled tasks, the Startup folder, and WMI subscriptions. Autoruns (Sysinternals) lists them all in one place, and can save a snapshot of the list and compare it with a later one. - Linux: cron (
/etc/crontab,/etc/cron.d/, user crontabs), systemd units (system and~/.config/systemd/user/), shell start-up files (~/.bashrc,~/.profile),~/.ssh/authorized_keys, and/etc/ld.so.preload(the preloading mechanism from the ELF article).
Our greeter persists nothing, and saying so is a finding: an unchanged Autoruns list and no
new cron or systemd entries belong in the report just as clearly as a new Run key would.
The later evasion and persistence article looks at these mechanisms in depth.
Automated Sandboxes
Everything above can be automated, and for a team that sees hundreds of samples a day, it must be. An automated sandbox takes a file, starts a clean VM, runs the file with monitors in place, waits a few minutes, reverts the VM, and turns everything it recorded into a report. Many open-source sandboxes descend from Cuckoo Sandbox: its 2.x line is no longer maintained, and a Python 3 rewrite, Cuckoo3, is developed by CERT-EE. CAPE, derived from Cuckoo, added what its name stands for, Config And Payload Extraction: automated unpacking, YARA-based classification of the unpacked payloads, and extraction of malware configurations. Commercial and public online services work on the same principle.
A typical report contains:
- the process tree, with command lines;
- a log of monitored API calls per process;
- files created, modified and deleted, often with copies of created files;
- registry changes;
- DNS queries, HTTP requests and a packet capture;
- screenshots, memory dumps and extracted payloads or configurations;
- signatures: rules that turn raw behaviour into statements such as "creates a Run key" or "reads a browser's saved data", usually rolled up into a score.
Sandboxes are superb for triage at scale and for a first behavioural picture. Their limits are just as important:
- A short, fixed run time. A program that waits ten minutes, waits for a reboot, or acts only on a date shows nothing.
- One path, one environment. The program takes the branch this VM's language, domain membership, installed software and network allow. Other machines may see other behaviour.
- No human. No mouse movement, no documents opened, no clicked dialogs, unless the sandbox fakes them.
- Some samples notice. Sandboxes are analysis environments with characteristic traits, and some samples behave differently in them (next section).
- The score is not the verdict. "Nothing happened" can mean benign, broken or simply patient. Signatures produce false positives and false negatives.
- Uploading is a decision. As with cloud decompilers, a public sandbox shares your sample with someone else, and often with everyone. Run your own (CAPE runs well in a lab) for anything sensitive.
The habit to keep: read a sandbox report as a list of leads to confirm, and confirm the important ones by hand.
When the Sample Watches Back
Some samples check whether they're being observed and change their behaviour if they are:
asking the operating system whether a debugger is attached (on Windows through APIs such as
IsDebuggerPresent, on Linux through the TracerPid field of /proc/self/status),
measuring how long a piece of code takes, or looking for the traits of a virtual machine or
sandbox. You don't need the details yet. What matters now is the symptom: if a run ends
early, does nothing, or behaves differently under a debugger than in a plain run, suspect
such a check, record it as a finding, and look for it in the disassembly. The evasion and
persistence article later in the series covers how to recognise these checks.
A Dynamic Analysis Workflow
-
Arrive with questions
Bring your triage notes and your disassembler database. Write down what you want to learn: a decoded string or setting, what a created file is, whether anything persists. A run without questions produces a pile of logs and no answers.
-
Prepare the lab
Revert the victim to
CLEAN, confirm isolation, start INetSim or FakeNet-NG and the packet capture on the gateway. On the victim, start the monitors: Procmon (capturing, filters applied only for display) and Regshot's 1st shot on Windows; auditd rules and a marker file on Linux. -
Run it free first
A behavioural run, with no debugger attached: on Windows simply launch it under Procmon; on Linux under
strace -f, with auditd and the gateway watching too. Give it a few minutes. Interact with the VM as a user would. -
Collect, then revert
Stop the captures, take the 2nd Regshot shot or run your
find, run Autoruns, save the Procmon log, collect the strace output, copy created files out as password-protected archives. Then revert. -
Filter and build a timeline
Scope to the program's process tree, drop the noise, and write the run down as a short sequence of facts with timestamps: started, read X, wrote Y, started Z, looked up and contacted W. Note anything you can't yet explain.
-
Debug what's still unanswered
From a fresh
CLEANrevert, run under x64dbg or gdb, with breakpoints chosen from the timeline and the disassembly: on the API that wrote the file, the call that connected out, the decoder you found statically. Use a write watchpoint to catch the moment a buffer is filled, and dump decoded buffers. -
Feed everything back
Rename the functions you stopped in, record decoded strings and settings in the disassembler database, and write the indicators (domains, paths, keys, User-Agents) into your notes, defanged. Revert, every time.
What's Next
You can now run a program under control on either platform: start or attach a debugger and know what the operating system is doing underneath, choose between software, hardware and memory breakpoints and know what each one costs, step into, over and out of functions, watch a buffer change byte by byte, and read the registers, stack and memory that confirm a static hypothesis. You can trace a run with strace, ltrace, Procmon and API Monitor, filter a 146-line trace down to the events that matter, collect the five views of a run, and read a sandbox report for what it is.
The next article in the series, behavioural analysis, steps back from single instructions and single system calls to the bigger picture: turning a run's events into a description of what the sample is, mapping its behaviours to the techniques defenders track, and capturing them in a form that detects the next sample like it.