TExcelTAD
Home › Reverse Engineering & Binary Analysis › Tracing System and Library Calls: strace and ltrace

Tracing System and Library Calls: strace and ltrace

A debugger answers precise questions at one point in a program. Tracers answer a broader one: what does this program do to the system, from start to finish? strace prints every system call (files opened, bytes read and written, processes started, network connections attempted) with its arguments and results; ltrace prints calls into shared libraries (strcmp, getenv, fopen, malloc). Ten seconds of tracing in a lab often answers what an hour of static analysis would: which configuration file is read, where output goes, what string an input is compared with. Malware sandboxes are, at their core, automated tracers. The System Calls lesson of the OS course explains the mechanism underneath.

Definitions

  • System call: the program's request to the kernel (openat, read, write, connect, execve, clone, mmap...). Almost everything a process does outside its own memory goes through one, so a complete syscall trace is close to a complete record of its effects (the exception: writes into memory-mapped files or shared memory, where only the mmap call shows).
  • strace: uses ptrace to stop the program at each syscall entry and exit. Useful options: -f (follow child processes), -e trace=file,network,process,read,write (filter by class or name), -o file (write the trace to a file), -s 128 (show longer strings), -y (show file paths for descriptors), -c (summary counts).
  • ltrace: intercepts calls through the PLT to shared libraries; -e 'strcmp+getenv' filters by function. It sees only dynamically linked library calls, not static code or inlined functions.
  • Library call vs system call: fopen (libc) eventually calls openat (kernel); strcmp never reaches the kernel, so only ltrace sees it.

Tracing a toy configuration tool

The session builds a toy that reads settings.conf, reads an environment variable, compares the setting with a constant and writes a log. Then it traces it both ways. Everything happens in the session's own working directory.

bash · try it yourself
cat > cfgtool.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
    char line[64] = "";
    FILE *f = fopen("settings.conf", "r");
    if (f) { if (!fgets(line, sizeof line, f)) line[0] = 0; fclose(f); }
    line[strcspn(line, "\n")] = 0;
    const char *token = getenv("LAB_TOKEN");
    int verbose = strcmp(line, "mode=verbose") == 0;
    FILE *log = fopen("out.log", "w");
    if (!log) return 1;
    fprintf(log, "mode=%s token=%s\n", verbose ? "verbose" : "quiet", token ? "set" : "unset");
    fclose(log);
    return 0;
}
SRC
gcc -O1 cfgtool.c -o cfgtool
echo "mode=debug" > settings.conf
echo "== strace: what the program does to the system (loader noise removed)"
strace -e trace=openat,read,write,exit_group ./cfgtool 2>&1 | grep -vE 'ld.so|libc.so|832\)'
echo "== ltrace: the library calls that decide it"
LAB_TOKEN=lab-only-token ltrace -e 'fopen+getenv+strcmp' ./cfgtool 2>&1
== strace: what the program does to the system (loader noise removed)
openat(AT_FDCWD, "settings.conf", O_RDONLY) = 3
read(3, "mode=debug\n", 4096)           = 11
openat(AT_FDCWD, "out.log", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
write(3, "mode=quiet token=unset\n", 23) = 23
exit_group(0)                           = ?
+++ exited with 0 +++
== ltrace: the library calls that decide it
cfgtool->fopen("settings.conf", "r")             = 0x5cc29327a2a0
cfgtool->getenv("LAB_TOKEN")                     = "lab-only-token"
cfgtool->strcmp("mode=debug", "mode=verbose")    = -18
cfgtool->fopen("out.log", "w")                   = 0x5cc29327a2a0
+++ exited (status 0) +++

The syscall trace is the behaviour summary: it opens settings.conf for reading, reads 11 bytes, creates out.log and writes one line. The library trace explains the decision behind that line: the setting is compared with the constant "mode=verbose", which was never in the configuration, so the tool runs quiet. Two more facts fall out for free. The comparison constant is now known without reading any code (the basis of every "crackme" shortcut, see the crackme). And the token's value is visible in the trace: anything a program receives in an environment variable or an argument can be read by anyone allowed to trace it (and arguments by anyone who can read /proc/<pid>/cmdline).

Seeing network attempts

The second session builds the socket toy from Imports as Behaviour Hints, which connects to 127.0.0.1:9000. Nothing listens there inside the sandbox, so the connection is refused, and the trace records the attempt with its full destination: exactly what a sandbox report lists under "network activity".

bash · try it yourself
cat > net.c <<'SRC'
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void) {
    int s = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(9000) };
    inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);
    int r = connect(s, (struct sockaddr *)&a, sizeof a);
    close(s);
    return r == 0 ? 0 : 3;
}
SRC
gcc -O1 net.c -o net
strace -e trace=network ./net 2>&1
echo "exit code: $?"
socket(AF_INET, SOCK_STREAM, IPPROTO_IP) = 3
connect(3, {sa_family=AF_INET, sin_port=htons(9000), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 ECONNREFUSED (Connection refused)
+++ exited with 3 +++
exit code: 3

socket, then connect to 127.0.0.1 port 9000, refused (ECONNREFUSED), and the program exits with its error code 3. In a malware lab, the same trace (with a fake DNS server and a sinkhole on the lab network) reveals the addresses a sample tries to reach, which become indicators of compromise.

How tracing is detected, and what defenders use it for

  • A traced process can know: TracerPid in /proc/self/status is non-zero, and a second ptrace(PTRACE_TRACEME) fails. Malware and some protected software check this and behave differently under strace (Anti-Debugging). If a program's behaviour under the tracer differs from the sandbox report, suspect such a check.
  • Defenders trace too: Linux audit (auditd rules on execve, connect, file paths), eBPF-based tools (Falco, Tetragon, bpftrace) and EDR agents record the same events system-wide without ptrace, so they are harder to notice (Instrumentation).
  • Unexpected tracers on production hosts are themselves an alert: a process attached with ptrace to sshd is a classic credential-theft technique, which is why kernel.yama.ptrace_scope restricts attaching.

How developers avoid leaking through traces

  • Don't pass secrets in arguments or environment variables when you can avoid it; read them from a file with strict permissions or a secrets manager socket (Secrets Management), and never log them.
  • Compare secrets with constant-time functions and don't compare against a plaintext copy at all: store a hash (for passwords, a slow KDF) so that a library trace shows nothing useful.
  • Treat anything on a user's own machine as observable by that user.

Pitfalls

  • Loader noise: the first dozen syscalls of every dynamically linked program open ld.so.cache and libc.so.6; filter them as above.
  • Truncated strings: strace shows 32 characters by default; use -s 256.
  • ltrace and static or -fno-plt binaries: ltrace relies on PLT entries (it copes with BIND_NOW, as the session above shows); statically linked or -fno-plt programs show little or nothing; strace still works.
  • Timing changes: tracing slows the program a lot, which a timing check can notice, and races may disappear or appear.
  • Children: without -f, everything a program does in a child process is invisible.

Practice

1. Change settings.conf to mode=verbose. Which lines of the two traces change?

read returns 13 bytes; write writes mode=verbose token=...; strcmp returns 0.

2. Which strace option set would you use to see only which files a program touches, with full paths for descriptors?

strace -f -y -e trace=file,read,write ./prog (-y prints the path next to each descriptor).

3. A program compares its licence key with strcmp against a plaintext constant. What does ltrace -e strcmp reveal, and what is the fix?

The correct key, as the second argument. Fix: don't store the key at all; verify a signed licence with a public key, or check on a server (the crackme shows both).

Test yourself

Which tool shows the arguments of strcmp calls?

  1. strace
  2. ltrace
  3. readelf
  4. checksec

Why is a complete syscall trace close to a complete record of a program's effects on the system?

  1. Because strace runs as root
  2. Because file, network and process operations must go through a system call
  3. Because it includes library calls
  4. Because programs cannot use memory

What did the strace of net show?

  1. A successful HTTP request
  2. socket and a connect to 127.0.0.1:9000 refused with ECONNREFUSED
  3. No network activity
  4. A DNS query

Why is passing a token in an environment variable risky?

  1. Environment variables are encrypted
  2. Anyone allowed to trace or inspect the process can read it (ltrace showed its value)
  3. It is slower
  4. Environment variables can't hold secrets