API Calls and System-Call Traces
Everything a program does to the outside world goes through the operating system: opening a file, writing a registry value, resolving a name, connecting a socket, starting a process. On Linux those requests are system calls; on Windows programs call documented API functions (CreateFileW, RegSetValueExW, InternetOpenUrlA) in system DLLs, which end in system calls into the kernel. A trace of those calls is the most detailed behavioural record there is. Sandboxes build their reports from it, EDR products collect a filtered version of it, and an analyst can read it directly.
The mechanics of strace and ltrace are taught in Tracing System and Library Calls. This lesson uses them the way a malware analyst does: run a program in a sandbox, trace it, and turn the trace into a list of behaviours.
Definitions
- System call trace: every call with arguments and result, for example
openat(AT_FDCWD, "state/agent.dat", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 3. - API call trace (Windows): the same idea one level higher, recorded by API Monitor, a debugger with logging breakpoints, Frida hooks, or the sandbox's monitor. API names are more readable than raw system calls (
NtCreateFile,NtSetValueKey). - Behaviour pattern: a sequence of calls with linked arguments, for example "open a file, write it, set a registry value pointing at it": the handle or path returned by one call is used in the next.
- ETW (Event Tracing for Windows): the kernel's tracing framework, the source many EDR products and Sysmon build on.
Tracing a harmless toy
The session writes and compiles a small, harmless C program that behaves a little like the lab sample: it reads a configuration file, collects the host name, writes a state file and renames it into place, and tries to connect to 127.0.0.1:8081, where nothing listens (no network exists in the sandbox anyway). Then strace records the calls of interest, and a short Python script turns the trace into behaviours.
cat > toy.c <<'SRC'
#include <arpa/inet.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <unistd.h>
int main(void) {
char cfg[128] = {0}, line[256];
struct utsname u;
int fd = open("agent.conf", O_RDONLY);
if (fd >= 0) { read(fd, cfg, sizeof cfg - 1); close(fd); }
uname(&u);
mkdir("state", 0700);
snprintf(line, sizeof line, "host=%s %s", u.nodename, cfg);
fd = open("state/agent.tmp", O_WRONLY | O_CREAT | O_TRUNC, 0600);
write(fd, line, strlen(line));
close(fd);
rename("state/agent.tmp", "state/agent.dat");
int s = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(8081) };
inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);
if (connect(s, (struct sockaddr *)&a, sizeof a) != 0) perror("connect");
close(s);
return 0;
}
SRC
gcc -O1 -o toy toy.c 2>/dev/null # (silences warnings about unchecked read/write results)
printf 'server=127.0.0.1:8081 interval=60' > agent.conf
strace -o trace.txt -e trace=openat,read,write,uname,mkdir,rename,socket,connect ./toy 2>/dev/null
grep -v -e '/etc/ld.so' -e '/lib/' -e 'ELF' -e 'resumed' trace.txt
echo "--- behaviours"
python3 - <<'PY'
import re
RULES = [
(r'^openat\(.*"([^"]+)", O_RDONLY', "reads file {0}"),
(r'^openat\(.*"([^"]+)", O_WRONLY\|O_CREAT', "creates file {0}"),
(r'^rename\("([^"]+)", "([^"]+)"\)', "renames {0} -> {1} (atomic replace)"),
(r'^uname\(', "collects host information"),
(r'^connect\(.*sin_port=htons\((\d+)\).*inet_addr\("([^"]+)"\).*= (-?\d+)( \w+)?', "connects to {1}:{0} -> result {2}{3}"),
]
for line in open("trace.txt"):
for rx, text in RULES:
m = re.search(rx, line)
if m and "/lib/" not in line and "ld.so" not in line:
print(" -", text.format(*[g or "" for g in m.groups()]))
PY
cat state/agent.dat; echoopenat(AT_FDCWD, "agent.conf", O_RDONLY) = 3
read(3, "server=127.0.0.1:8081 interval=6"..., 127) = 33
uname({sysname="Linux", nodename="tad", ...}) = 0
mkdir("state", 0700) = 0
openat(AT_FDCWD, "state/agent.tmp", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 3
write(3, "host=tad server=127.0.0.1:8081 i"..., 42) = 42
rename("state/agent.tmp", "state/agent.dat") = 0
socket(AF_INET, SOCK_STREAM, IPPROTO_IP) = 3
connect(3, {sa_family=AF_INET, sin_port=htons(8081), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 ECONNREFUSED (Connection refused)
write(2, "connect: Connection refused\n", 28) = 28
+++ exited with 0 +++
--- behaviours
- reads file agent.conf
- collects host information
- creates file state/agent.tmp
- renames state/agent.tmp -> state/agent.dat (atomic replace)
- connects to 127.0.0.1:8081 -> result -1 ECONNREFUSED
host=tad server=127.0.0.1:8081 interval=60
The raw trace is already readable, but the behaviour list is what goes into a report: it reads a configuration, collects host information, creates a temporary file and renames it into place, and tries a TCP connection that fails with ECONNREFUSED. A sandbox does the same mapping with hundreds of rules. Note the host name in the state file: tad, the sandbox container's name, which a real sample would send to its server.
Windows API patterns analysts recognise
No code is needed to recognise behaviour from an API trace; these sequences are what sandboxes and EDR rules look for. Each one is also used by legitimate software, so context decides.
| Sequence (simplified) | Behaviour | ATT&CK |
|---|---|---|
RegOpenKeyExW(HKCU\…\Run) → RegSetValueExW(name, path to self) |
autostart persistence | T1547.001 |
OpenProcess on another process → VirtualAllocEx → WriteProcessMemory → CreateRemoteThread |
code injected into another process | T1055 |
CreateToolhelp32Snapshot → Process32FirstW/NextW comparing names |
looks for specific processes (analysis tools, security products) | T1057, T1497 |
InternetOpenA → InternetOpenUrlA → InternetReadFile → CreateFileW → WriteFile |
downloads a file | T1105 |
FindFirstFileW/FindNextFileW over many folders → CreateFileW + WriteFile + MoveFileExW per file at high rate |
mass file rewrite (ransomware-like) | T1486 |
OpenProcess(lsass.exe, PROCESS_VM_READ) → MiniDumpWriteDump |
credential dumping from LSASS memory | T1003.001 |
CryptStringToBinaryA / custom loop → VirtualAlloc(…, PAGE_EXECUTE_READWRITE) |
decode and run in memory (unpacking, loaders) | T1140, T1027 |
How call-level behaviour is detected
- EDR hooks or ETW providers (for example the Microsoft-Windows-Threat-Intelligence provider for memory operations across processes) report injection and LSASS access; Sysmon event 8 (
CreateRemoteThread) and event 10 (process access, with the access mask) cover two of the rows above. - Linux: auditd rules on
execve,connectand writes to sensitive paths; eBPF-based tools (Falco, Tetragon) evaluate syscall sequences in real time. - Sandboxes turn traces into signatures and ATT&CK mappings automatically (sandboxes).
How it is prevented
- Protect LSASS: with RunAsPPL,
OpenProcesswith read access fails for ordinary processes, and Credential Guard moves the most valuable secrets into an isolated process so that a dump of LSASS holds far less (LSASS). - Attack-surface-reduction rules and application control stop the first link of most chains: an Office process starting a child, or an unsigned program running from a user folder.
- On Linux, seccomp profiles and least-privilege service accounts limit which calls a compromised service can make.
Pitfalls
- Tracing changes behaviour. Samples can detect a tracer (
ptracealready attached, timing) and behave differently (anti-debugging). - Library noise. The first hundred lines of any trace are the dynamic loader; filter them, but don't filter away a library the sample loads itself.
- Missing the child. Without
-f,stracedoesn't follow child processes; a sample that does its work in a child looks idle. - One call is not a behaviour.
VirtualAllocalone means nothing; the sequence and the arguments do.
Practice
1. Why does the toy write agent.tmp and then rename it, and how would you describe it in a report?
Writing to a temporary name and renaming makes the replacement atomic (readers never see a half-written file); many legitimate programs do it. Report it as "creates state/agent.dat (via a temporary file and rename)".
2. Which strace option would you add for a program that starts a child process, and what changes in the output?
-f follows children (-ff -o trace writes one file per process). With -f and one output file, each line is prefixed with the process ID, so the parser must handle that prefix.
3. In the injection row of the table, which arguments link the four calls into one behaviour?
The process handle returned by OpenProcess is passed to the next three calls, and the address returned by VirtualAllocEx is where WriteProcessMemory writes and where CreateRemoteThread starts the thread. Detection logic follows those handles and addresses.
Test yourself
What turns a list of calls into a behaviour?
- The number of calls
- A sequence of calls linked by their arguments and results
- The alphabetical order of API names
- The file size
Which Sysmon event records a thread created in another process?
- 1
- 8
- 11
- 22
What did the toy's connect() call return in the sandbox?
- 0, success
- -1 ECONNREFUSED, because nothing listens on 127.0.0.1:8081
- A DNS error
- It was never called
Which control stops OpenProcess-based reads of LSASS memory?
- Disabling DNS
- Running LSASS as a protected process (RunAsPPL) or Credential Guard
- Sysmon event 3
- Larger page files