Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing a subprocess started via sudo

In a project I am working on, there is some code that starts up a long-running process using sudo:

subprocess.Popen(['sudo', '/usr/bin/somecommand', ...])

I would like to clean up this process when the parent exits. Currently, the subprocess keeps running when the parent exits (re-attached to init, of course).

I am not sure of the best solution to this problem. The code is limited to only running certain commands via sudo, and granting blanket authority to run sudo kill would be sketchy at best.

I don't have an open pipe to the child process that I can close (the child process is not reading from stdin), and I am not able to modify the code of the child process.

Are there any other mechanisms that might work in this situation?

like image 392
larsks Avatar asked Feb 19 '14 16:02

larsks


1 Answers

First of all I just answer the question. Though I do not think it is a good thing to do, it is what you asked for. I would wrap that child process into a small program that can listen stdin. Then you may sudo that program, and it will be able to run the process without sudo, and will know its pid and have the rights needed to kill the process when you ask it through stdin to do so.

However, generally such a situation means sudo with no password and poor security. The most common technique is to use lowering your program's privileges, not elevating them. In such case you should create a runner program that is started by superuser, than it starts your main program with lowering of privileges and listens for a pipe to communicate. When it is necessary to run a command, your main program tells that to the runner program, and runner program does the job. When it is necessary to terminate command, you again tell this to a runner program via the pipe.

The common rules are:

  1. If you need superuser rights, you should give them to the very parent process.
  2. If a child process needs to do a privileged operation, it requests the top-level process to do that for him.
  3. The top-level process should be kept as small as possible and do as little as possible. The larger it is, the more holes in security it creates.

That's what many applications do. The first example that comes into my mind is Apache web server (at least on *nix) that has a small top-level program and preforked working programs that are not run as root/wheel/whatever-else-is-the-superuser-username.

like image 174
Ellioh Avatar answered Nov 18 '22 11:11

Ellioh