Systemtap — find who access the file

Ramesh Sahoo
2 min readMay 10, 2022

Systemtap provides information similar to the output of tools like netstat, ps, top, and iostat, but is designed to provide more filtering and analysis options for collected information. SystemTap provides the infrastructure to monitor the running Linux kernel for detailed analysis.

In this post, we’ll see how a systemtap script traces which application accesses a specific file on the system.

# cat file_open.stp#! /usr/bin/env stap
## Stap script to monitor a specific file path and provide information about the accessing application.
## Pre-requisites
# Install systemtap
# yum install systemtap
# stap-prep
## Execution:
# stap -v file_open.stp provide_absolute_file_path
global file_name = @1probe vfs.{open}.return
{
if (file_name == pathname){
ts = task_current()
printf("Trace of present task:\n%s\n", pstrace(ts))
ts = ts->parent
printf("Trace of parent task:\n%s\n", pstrace(ts))
printf ("TIME %s UID(%ld) PID(%d) PPID(%ld) Parent_proc_name(%s) PP_Function(%s) CMD_LINE(%s)\n",
ctime(gettimeofday_s()), uid(), pid(), ppid(), pexecname(), ppfunc(), cmdline_str())
printf("\n")
}
}

Sample script execution Output

# stap -v file_open.stp /tmp/filechange.txt 
Pass 1: parsed user script and 481 library scripts using 273336virt/70976res/3792shr/67184data kb, in 1340usr/30sys/1367real ms.
Pass 2: analyzed script: 2 probes, 55 functions, 12 embeds, 7 globals using 442496virt/238364res/5116shr/236344data kb, in 2500usr/510sys/3006real ms.
Pass 3: translated to C into "/tmp/stapD1kbi3/stap_57557a72b98aaf00558dfb392f95d833_30108_src.c" using 442496virt/238696res/5448shr/236344data kb, in 10usr/90sys/110real ms.
Pass 4: compiled C into "stap_57557a72b98aaf00558dfb392f95d833_30108.ko" in 2900usr/480sys/3193real ms.
Pass 5: starting run.
Process trace of current task:
bash(14414) sshd(14369) sshd(1254)
Process trace of parent task:
sshd(14369) sshd(1254)
TIME Tue May 10 17:41:19 2022 UID(0) PID(14414) PPID(14369) Parent_proc_name(sshd) PP_Function(vfs_open) CMD_LINE(-bash)

The above output says that root user from a ssh’s bash session tried to access /tmp/filechange.txt file.

--

--

Ramesh Sahoo

I describe myself as a troubleshooter, problem solver, techie, quick learner, and good mentor. I have 11+ years of IT industry experience in many MNCs.