How to track newly created processes in Linux?

If kprobes are enabled in the kernel you can use execsnoop from perf-tools:

In first terminal:

% while true; do uptime; sleep 1; done

In another terminal:

% git clone https://github.com/brendangregg/perf-tools.git
% cd perf-tools
% sudo ./execsnoop
Tracing exec()s. Ctrl-C to end.
Instrumenting sys_execve
   PID   PPID ARGS
 83939  83937 cat -v trace_pipe
 83938  83934 gawk -v o=1 -v opt_name=0 -v name= -v opt_duration=0 [...]
 83940  76640 uptime
 83941  76640 sleep 1
 83942  76640 uptime
 83943  76640 sleep 1
 83944  76640 uptime
 83945  76640 sleep 1
^C
Ending tracing...

The easiest way is to enable system call auditing

See the following link for details,

Does anyone know a simple way to monitor root process spawn | Server Fault

If you're monitoring all processes, just remove the -F uid=0 part

Logs are written to /var/log/audit/audit.log


Some examples of bpftrace usage to achieve the goal.

  1. The simplest one is tracing all exec calls in the system:

    sudo bpftrace -e 'tracepoint:syscalls:sys_enter_exec*{ printf("pid: %d, comm: %s, args: ", pid, comm); join(args->argv); }'
    

    There are at least two tracepoints you need to watch sys_enter_execve and enter_execveat. In the example I use the * symbol to match both syscalls (this syntax works since 2019).

  2. One may also want to monitor all threads being created in the system as:

    sudo bpftrace -e 'kprobe:_do_fork{ printf("pid = %d, comm = %s\n", pid, comm); }'
    

    No process arguments for you in this case though, nevertheless it may be useful.

To see the list of all available events execute bpftrace -l.

Tags:

Linux

Process