Running python-daemon as an irreconcilable user and maintaining group memberships

I am writing a daemon in python using python-daemon . the daemon starts at boot time (init.d) and needs to access various devices. the daemon runs on the embedded system ( beaglebone ) running ubuntu.

Now my problem is that I want to run the daemon as an unprivileged user rather (like mydaemon ) than root .

To allow daemons to access devices, I added this user to the desired groups. in python code i am using daemon.DaemonContext(uid=uidofmydamon) .

a process starting with root is perfectly dismounted and belongs to the correct user, but I get permission to refuse when I try to access devices. I wrote a small test application, and it seems that the process does not inherit user group membership.

 #!/usr/bin/python import logging, daemon, os if __name__ == '__main__': lh=logging.StreamHandler() logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(lh) uid=1001 ## UID of the daemon user with daemon.DaemonContext(uid=uid, files_preserve=[lh.stream], stderr=lh.stream): logger.warn("UID : %s" % str(os.getuid())) logger.warn("groups: %s" % str(os.getgroups())) 

when I run the above code as user with uid = 1001, I get something like

 $ ./testdaemon.py UID: 1001 groups: [29,107,1001] 

then when I run the above code as root (or su ), I get:

 $ sudo ./testdaemon.py UID: 1001 groups: [0] 

How can I create a daemon process running as root, but with a different effective uid and intact group membership?

+6
source share
1 answer

my current solution involves dropping root privileges before starting the actual daemon using the chuid argument to start-stop-daemon :

  start-stop-daemon \ --start \ --chuid daemonuser \ --name testdaemon \ --pidfile /var/run/testdaemon/test.pid \ --startas /tmp/testdaemon.py \ -- \ --pidfile /var/run/testdaemon/test.pid \ --logfile=/var/log/testdaemon/testdaemon.log 

The disadvantage of this solution is that I need to create all the directories where the daemons should write (notably /var/run/testdaemon and /var/log/testdaemon ) before starting the actual daemon (with the appropriate file permissions).

I would rather write this logic in python rather than bash.

while it works, but I think that it should be available for the solution more elegantly.

+2
source

Source: https://habr.com/ru/post/948473/


All Articles