From 3cfdf6972c46f2dc86e12e0c258a217676a11b59 Mon Sep 17 00:00:00 2001 From: Pratik Vyas Date: Mon, 10 Nov 2014 21:21:45 +0530 Subject: [PATCH] better drop_privileges --- bench/cli.py | 6 +++--- bench/utils.py | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/bench/cli.py b/bench/cli.py index 2c6caf58..28cb458e 100644 --- a/bench/cli.py +++ b/bench/cli.py @@ -11,8 +11,8 @@ from .utils import set_nginx_port as _set_nginx_port from .utils import set_nginx_port as _set_nginx_port from .utils import set_default_site as _set_default_site from .utils import (build_assets, patch_sites, exec_cmd, update_bench, get_frappe, setup_logging, - get_config, update_config, restart_supervisor_processes, put_config, default_config, update_requirements, - backup_all_sites, backup_site, get_sites, prime_wheel_cache, is_root, set_mariadb_host) + get_config, update_config, restart_supervisor_processes, put_config, default_config, update_requirements, + backup_all_sites, backup_site, get_sites, prime_wheel_cache, is_root, set_mariadb_host, drop_privileges) from .app import get_app as _get_app from .app import new_app as _new_app from .app import pull_all_apps @@ -49,7 +49,7 @@ def change_uid(): if is_root() and not cmd_requires_root(): frappe_user = get_config().get('frappe_user') if frappe_user: - os.seteuid(pwd.getpwnam(frappe_user).pw_uid) + drop_privileges(uid_name=frappe_user, gid_name=frappe_user) os.environ['HOME'] = pwd.getpwnam(frappe_user).pw_dir else: print 'You should not run this command as root' diff --git a/bench/utils.py b/bench/utils.py index 6c68ebf5..b1812438 100644 --- a/bench/utils.py +++ b/bench/utils.py @@ -293,3 +293,22 @@ def update_json_file(filename, ddict): with open(filename, 'w') as f: content = json.dump(content, f, indent=1) +def drop_privileges(uid_name='nobody', gid_name='nogroup'): + # from http://stackoverflow.com/a/2699996 + if os.getuid() != 0: + # We're not root so, like, whatever dude + 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(077)