pgrep/pkill and pidof segfault if /proc is not available
pgrep/pkill and pidof segfault if /proc is not available
pgrep/pkill and pidof crash with a segmentation fault if /proc is not available instead of printing a helpful error message.
To reproduce this issue, execute the following:
# chmod go-rx /proc
$ ./pgrep foobar
Segmentation fault (core dumped)
$ ./pidof foobar
Segmentation fault (core dumped)
$ ./pkill foobar
Segmentation fault (core dumped)
Stacktraces
pgrep/pkill
#0 readproc (PT=0x0, p=0x7fff3905ac10) at proc/readproc.c:1237
#1 0x000055b1001a5890 in select_procs (num=0x7fff3905e8f4) at pgrep.c:513
#2 0x000055b1001a62ef in main (argc=2, argv=0x7fff3905ea18) at pgrep.c:921
#3 0x00007f8b263bff6a in __libc_start_main () from /usr/lib/libc.so.6
#4 0x000055b1001a3ada in _start ()
pidof
#0 readproc (PT=0x0, p=0x7ffdc8988350) at proc/readproc.c:1237
#1 0x000055d0f2f22b9d in select_procs () at pidof.c:151
#2 0x000055d0f2f22f3f in main (argc=2, argv=0x7ffdc8988878) at pidof.c:350
#3 0x00007efe969ccf6a in __libc_start_main () from /usr/lib/libc.so.6
#4 0x000055d0f2f2220a in _start ()
Analysis
The select_procs
function of pgrep/pkill calls do_openproc
which forwards
the return value of openproc
. The result, a PROCTAB
pointer, is fed into
readproc
(pgrep.c).
498 ptp = do_openproc();
...
513 while(readproc(ptp, &task)) {
The select_procs
function of pidof
directly calls openproc
and feeds the
result into readproc
(pidof.c).
147 ptp = openproc (PROC_FILLCOM | PROC_FILLSTAT);
...
151 while(readproc(ptp, &task)) {
openproc
returns NULL
in case opendir
fails (proc/readproc.c).
1382 PT->procfs = opendir("/proc");
1383 if (!PT->procfs) { free(PT); return NULL; }
This null pointer is dereferenced by readproc
(proc/readproc.c).
1237 PT->did_fake=0;
The return value of openproc
or the argument of readproc
should be checked
for being NULL
and an error message should be printed in that case. However,
I am not sure which is the best place to do that.
Other Tools
pmap
fails silently
$ echo $$
13370
$ ./pmap 13370
whereas the other tools print varying error message:
$ ./pwdx 13370
13370: Permission denied
$ ./slabtop
fopen /proc/slabinfo: Permission denied
$ ./sysctl -a
lt-sysctl: unable to open directory "/proc/sys/"
$ ./free # or tload, uptime, vmstat, w
Error: /proc must be mounted
To mount /proc at boot you need an /etc/fstab line like:
proc /proc proc defaults
In the meantime, run "mount proc /proc -t proc"