From 5792e0593509edcd615ee3a0c99d4daaa5c1724a Mon Sep 17 00:00:00 2001 From: Scott Kitterman Date: Sun, 11 Feb 2018 20:53:42 -0500 Subject: [PATCH] Add util.py with drop_privileges function to start --- util.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 util.py diff --git a/util.py b/util.py new file mode 100644 index 0000000..274df6c --- /dev/null +++ b/util.py @@ -0,0 +1,37 @@ +# drop_priviledges (from https://github.com/nigelb/Static-UPnP) +# Copyright (C) 2016 NigelB +# Copyright (C) 2018 Scott Kitterman +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +def drop_privileges(uid_name, gid_name, umask=0o077): + if os.getuid() != 0: + # We're not root so, like, whatever dude + self.logger.info("Not running as root. Cannot drop permissions.") + return + + # Get the uid/gid from the name + running_uid = pwd.getpwnam(uid_name).pw_uid + running_gid = grp.getgrnam(gid_name).gr_gid + + # Remove group privileges + os.setgroups([]) + + # Try setting the new uid/gid + os.setgid(running_gid) + os.setuid(running_uid) + + # Ensure a very conservative umask + old_umask = os.umask(umask)