5.15. Killing Processes via sudo
Problem
Allow a user to kill a certain process but no others.
Solution
Create a script that kills the process by looking up its PID dynamically and safely. Add the script to /etc/sudoers .
Discussion
Because we don’t know a process’s PID until runtime, we cannot solve this problem with /etc/sudoers alone, which is written before runtime. You need a script to deduce the PID for killing.
For example, to let users restart sshd :
#!/bin/sh pidfile=/var/run/sshd.pid sshd=/usr/sbin/sshd # sanity check that pid is numeric pid=`/usr/bin/perl -ne 'print if /^\d+$/; last;' $pidfile` if [ -z "$pid" ] then echo "$0: error: non-numeric pid $pid found in $pidfile" 1>&2 exit 1 fi # sanity check that pid is a running process if [ ! -d "/proc/$pid" ] then echo "$0: no such process" 1>&2 exit 1 fi # sanity check that pid is sshd if [ `readlink "/proc/$pid/exe"` != "$sshd" ] then echo "$0: error: attempt to kill non-sshd process" 1>&2 exit 1 fi kill -HUP "$pid"
Call the script /usr/local/bin/sshd-restart and let users invoke it via sudo:
# /etc/sudoers: smith ALL = /usr/local/bin/sshd-restart ""
The empty double-quotes prevent arguments from being passed to the script. [Recipe 5.9]
Our script carefully signals only the parent sshd process, not its child processes for SSH sessions already in progress. If you prefer to kill all processes with a given name, use the pidof command:
# kill -USR1 `pidof mycommand
`
or the skill command:
# skill -USR1 mycommand
See Also
kill(1), ...
Get Linux Security Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.