Reputation: 15682
I am running into an issue regard dropping root privileges when opening a file in /tmp. Here is the line in question:
open(filepath, 'wb')
When the program is not run with a sudo command everything works fine and here are the permissions when I so os.stat
posix.stat_result(st_mode=17407, st_ino=261652, st_dev=64512L, st_nlink=206, st_uid=1000, st_gid=1000, st_size=12288, st_atime=1352314677, st_mtime=1352316340, st_ctime=1352316340)
I run into an issue when the program is run with a sudo command. I try to drop privileges with the following
os.setegid(int(os.getenv("SUDO_GID")))
os.seteuid(int(os.getenv("SUDO_UID")))
and reenable them with
os.seteuid(0)
os.setegid(0)
The error message is
IOError: [Errno 13] Permission denied:
os.stat yields
posix.stat_result(st_mode=17407, st_ino=261652, st_dev=64512L, st_nlink=204, st_uid=1000, st_gid=1000, st_size=4096, st_atime=1352314677, st_mtime=1352316329, st_ctime=1352316329)
Ideally I'd like the run a particular function as if the user never called sudo by dropping and enabling root privileges accordingly.
Upvotes: 3
Views: 1251
Reputation: 2885
You will probably need to change from root in a process that you spawn somehow, because, if you drop root, you can't get it back again. You could try using os.fork() for this.
import os
def drop_permissions():
os.setegid(int(os.getenv("SUDO_GID")))
os.seteuid(int(os.getenv("SUDO_UID")))
def call_without_permissions(func, *args, **kw):
in_parent = os.fork()
if not in_parent:
drop_permissions()
func(*args, **kw)
os._exit(0)
else:
os.waitpid(0)
Upvotes: 2