Python os.getuid() Examples

The following are code examples for showing how to use os.getuid(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def check_environ ():
    """Ensure that 'os.environ' has all the environment variables we
    guarantee that users can use in config files, command-line options,
    etc.  Currently this includes:
      HOME - user's home directory (Unix only)
      PLAT - description of the current platform, including hardware
             and OS (see 'get_platform()')
    """
    global _environ_checked
    if _environ_checked:
        return

    if os.name == 'posix' and 'HOME' not in os.environ:
        import pwd
        os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]

    if 'PLAT' not in os.environ:
        os.environ['PLAT'] = get_platform()

    _environ_checked = 1 
Example 2
Project: pyblish-win   Author: pyblish   File: webbrowser.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _find_grail_rc(self):
        import glob
        import pwd
        import socket
        import tempfile
        tempdir = os.path.join(tempfile.gettempdir(),
                               ".grail-unix")
        user = pwd.getpwuid(os.getuid())[0]
        filename = os.path.join(tempdir, user + "-*")
        maybes = glob.glob(filename)
        if not maybes:
            return None
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        for fn in maybes:
            # need to PING each one until we find one that's live
            try:
                s.connect(fn)
            except socket.error:
                # no good; attempt to clean it out, but don't fail:
                try:
                    os.unlink(fn)
                except IOError:
                    pass
            else:
                return s 
Example 3
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testNoArgFunctions(self):
        # test posix functions which take no arguments and have
        # no side-effects which we need to cleanup (e.g., fork, wait, abort)
        NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname",
                             "times", "getloadavg", "tmpnam",
                             "getegid", "geteuid", "getgid", "getgroups",
                             "getpid", "getpgrp", "getppid", "getuid",
                           ]

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", "", DeprecationWarning)
            for name in NO_ARG_FUNCTIONS:
                posix_func = getattr(posix, name, None)
                if posix_func is not None:
                    posix_func()
                    self.assertRaises(TypeError, posix_func, 1) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_initgroups(self):
        # It takes a string and an integer; check that it raises a TypeError
        # for other argument lists.
        self.assertRaises(TypeError, posix.initgroups)
        self.assertRaises(TypeError, posix.initgroups, None)
        self.assertRaises(TypeError, posix.initgroups, 3, "foo")
        self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())

        # If a non-privileged user invokes it, it should fail with OSError
        # EPERM.
        if os.getuid() != 0:
            try:
                name = pwd.getpwuid(posix.getuid()).pw_name
            except KeyError:
                # the current UID may not have a pwd entry
                raise unittest.SkipTest("need a pwd entry")
            try:
                posix.initgroups(name, 13)
            except OSError as e:
                self.assertEqual(e.errno, errno.EPERM)
            else:
                self.fail("Expected OSError to be raised by initgroups") 
Example 5
Project: pyblish-win   Author: pyblish   File: site.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def check_enableusersite():
    """Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    """
    if sys.flags.no_user_site:
        return False

    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
        # check process uid == effective uid
        if os.geteuid() != os.getuid():
            return None
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
        # check process gid == effective gid
        if os.getegid() != os.getgid():
            return None

    return True 
Example 6
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: rhsm_repository.py    MIT License 6 votes vote down vote up
def run_subscription_manager(module, arguments):
    # Execute subuscription-manager with arguments and manage common errors
    rhsm_bin = module.get_bin_path('subscription-manager')
    if not rhsm_bin:
        module.fail_json(msg='The executable file subscription-manager was not found in PATH')

    rc, out, err = module.run_command("%s %s" % (rhsm_bin, " ".join(arguments)))

    if rc == 1 and (err == 'The password you typed is invalid.\nPlease try again.\n' or os.getuid() != 0):
        module.fail_json(msg='The executable file subscription-manager must be run using root privileges')
    elif rc == 0 and out == 'This system has no repositories available through subscriptions.\n':
        module.fail_json(msg='This system has no repositories available through subscriptions')
    elif rc == 1:
        module.fail_json(msg='subscription-manager failed with the following error: %s' % err)
    else:
        return rc, out, err 
Example 7
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: cron.py    MIT License 6 votes vote down vote up
def __init__(self, module, user=None, cron_file=None):
        self.module = module
        self.user = user
        self.root = (os.getuid() == 0)
        self.lines = None
        self.ansible = "#Ansible: "
        self.existing = ''

        if cron_file:
            if os.path.isabs(cron_file):
                self.cron_file = cron_file
            else:
                self.cron_file = os.path.join('/etc/cron.d', cron_file)
        else:
            self.cron_file = None

        self.read() 
Example 8
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: cronvar.py    MIT License 6 votes vote down vote up
def _read_user_execute(self):
        """
        Returns the command line for reading a crontab
        """
        user = ''

        if self.user:
            if platform.system() == 'SunOS':
                return "su %s -c '%s -l'" % (pipes.quote(self.user), pipes.quote(CRONCMD))
            elif platform.system() == 'AIX':
                return "%s -l %s" % (pipes.quote(CRONCMD), pipes.quote(self.user))
            elif platform.system() == 'HP-UX':
                return "%s %s %s" % (CRONCMD, '-l', pipes.quote(self.user))
            elif pwd.getpwuid(os.getuid())[0] != self.user:
                user = '-u %s' % pipes.quote(self.user)
        return "%s %s %s" % (CRONCMD, user, '-l') 
Example 9
Project: saasy_boi   Author: netskopeoss   File: agent.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_admin():
    global is_admin
    if os.name == 'nt':
        try:
            f = open("\\\\.\\PHYSICALDRIVE0")
            f.close()
            is_admin = True
            return "admin"
        except IOError:
            return "not admin"
    else:
        if os.getuid() == 0:
            is_admin = True
            return "admin"
        else:
            return "not admin" 
Example 10
Project: flasky   Author: RoseOu   File: site.py    MIT License 6 votes vote down vote up
def check_enableusersite():
    """Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    """
    if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
        return False

    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
        # check process uid == effective uid
        if os.geteuid() != os.getuid():
            return None
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
        # check process gid == effective gid
        if os.getegid() != os.getgid():
            return None

    return True 
Example 11
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: utils.py    Apache License 2.0 6 votes vote down vote up
def temporary_chown(path, owner_uid=None):
    """Temporarily chown a path.

    :param owner_uid: UID of temporary owner (defaults to current user)
    """
    if owner_uid is None:
        owner_uid = os.getuid()

    orig_uid = os.stat(path).st_uid

    if orig_uid != owner_uid:
        execute('chown', owner_uid, path, run_as_root=True)
    try:
        yield
    finally:
        if orig_uid != owner_uid:
            execute('chown', orig_uid, path, run_as_root=True) 
Example 12
Project: XFLTReaT   Author: earthquake   File: common.py    MIT License 6 votes vote down vote up
def get_privilege_level():
	os_type = get_os_type()
	if (os_type == OS_LINUX) or (os_type == OS_MACOSX) or (os_type == OS_FREEBSD):
		if os.getuid() == 0:
			return True
		else:
			return False

	if os_type == OS_WINDOWS:
		import ctypes
		if ctypes.windll.shell32.IsUserAnAdmin():
			return True
		else:
			return False

	return False


# check if the forwarding was set properly. 
Example 13
Project: sic   Author: Yanixos   File: site.py    GNU General Public License v3.0 6 votes vote down vote up
def check_enableusersite():
    """Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    """
    if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
        return False

    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
        # check process uid == effective uid
        if os.geteuid() != os.getuid():
            return None
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
        # check process gid == effective gid
        if os.getegid() != os.getgid():
            return None

    return True 
Example 14
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 6 votes vote down vote up
def getUserDict():
	uid = os.getuid()
	if not uid:
		return None
	userinfo = pwd.getpwuid(uid)
	if not userinfo or len(userinfo) < 6:
		return None
	userdict = {
		'username': userinfo[0],
		'uid': int(userinfo[2]),
		'gid': int(userinfo[3]),
		'fullname': userinfo[4],
		'homedir': userinfo[5],
		'unixshell': os.path.basename(userinfo[6]),
	}
	return userdict

#===================== 
Example 15
Project: certidude   Author: laurivosandi   File: common.py    MIT License 6 votes vote down vote up
def drop_privileges():
    from certidude import config
    import pwd
    _, _, uid, gid, gecos, root, shell = pwd.getpwnam("certidude")
    restricted_groups = []
    restricted_groups.append(gid)

    # PAM needs access to /etc/shadow
    if config.AUTHENTICATION_BACKENDS == {"pam"}:
        import grp
        name, passwd, num, mem = grp.getgrnam("shadow")
        click.echo("Adding current user to shadow group due to PAM authentication backend")
        restricted_groups.append(num)

    os.setgroups(restricted_groups)
    os.setgid(gid)
    os.setuid(uid)
    click.echo("Switched %s (pid=%d) to user %s (uid=%d, gid=%d); member of groups %s" %
        (getproctitle(), os.getpid(), "certidude", os.getuid(), os.getgid(), ", ".join([str(j) for j in os.getgroups()])))
    os.umask(0o007) 
Example 16
Project: pyrex   Author: garmin   File: test.py    Apache License 2.0 6 votes vote down vote up
def test_ownership(self):
        # Test that files created in the container are the same UID/GID as the
        # user running outside

        test_file = os.path.join(self.thread_dir, "ownertest")
        if os.path.exists(test_file):
            os.unlink(test_file)

        self.assertPyrexContainerShellCommand(
            'echo "$(id -un):$(id -gn)" > %s' % test_file
        )

        s = os.stat(test_file)

        self.assertEqual(s.st_uid, os.getuid())
        self.assertEqual(s.st_gid, os.getgid())

        with open(test_file, "r") as f:
            (username, groupname) = f.read().rstrip().split(":")

        self.assertEqual(username, pwd.getpwuid(os.getuid()).pw_name)
        self.assertEqual(groupname, grp.getgrgid(os.getgid()).gr_name) 
Example 17
Project: Repobot   Author: Desgard   File: site.py    MIT License 6 votes vote down vote up
def check_enableusersite():
    """Check if user site directory is safe for inclusion

    The function tests for the command line flag (including environment var),
    process uid/gid equal to effective uid/gid.

    None: Disabled for security reasons
    False: Disabled by user (command line option)
    True: Safe and enabled
    """
    if hasattr(sys, 'flags') and getattr(sys.flags, 'no_user_site', False):
        return False

    if hasattr(os, "getuid") and hasattr(os, "geteuid"):
        # check process uid == effective uid
        if os.geteuid() != os.getuid():
            return None
    if hasattr(os, "getgid") and hasattr(os, "getegid"):
        # check process gid == effective gid
        if os.getegid() != os.getgid():
            return None

    return True 
Example 18
Project: osg-configure   Author: opensciencegrid   File: utilities.py    Apache License 2.0 6 votes vote down vote up
def make_directory(dir_name, perms=0o755, uid=None, gid=None):
    """
    Create a directory with specified permissions and uid/gid.  Will use the
    current user's uid and gid if not specified.

    returns True is successful
    """

    if uid is None:
        uid = os.getuid()
    if gid is None:
        gid = os.getgid()
    try:
        os.makedirs(dir_name, perms)
        os.chown(dir_name, uid, gid)
        return True
    except IOError:
        return False 
Example 19
Project: exoduscli   Author: cthlo   File: webbrowser.py    MIT License 6 votes vote down vote up
def _find_grail_rc(self):
        import glob
        import pwd
        import socket
        import tempfile
        tempdir = os.path.join(tempfile.gettempdir(),
                               ".grail-unix")
        user = pwd.getpwuid(os.getuid())[0]
        filename = os.path.join(tempdir, user + "-*")
        maybes = glob.glob(filename)
        if not maybes:
            return None
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        for fn in maybes:
            # need to PING each one until we find one that's live
            try:
                s.connect(fn)
            except socket.error:
                # no good; attempt to clean it out, but don't fail:
                try:
                    os.unlink(fn)
                except IOError:
                    pass
            else:
                return s 
Example 20
Project: NiujiaoDebugger   Author: MrSrc   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def check_environ ():
    """Ensure that 'os.environ' has all the environment variables we
    guarantee that users can use in config files, command-line options,
    etc.  Currently this includes:
      HOME - user's home directory (Unix only)
      PLAT - description of the current platform, including hardware
             and OS (see 'get_platform()')
    """
    global _environ_checked
    if _environ_checked:
        return

    if os.name == 'posix' and 'HOME' not in os.environ:
        import pwd
        os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]

    if 'PLAT' not in os.environ:
        os.environ['PLAT'] = get_platform()

    _environ_checked = 1 
Example 21
Project: pyblish-win   Author: pyblish   File: mimetools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def choose_boundary():
    """Return a string usable as a multipart boundary.

    The string chosen is unique within a single program run, and
    incorporates the user id (if available), process id (if available),
    and current time.  So it's very unlikely the returned string appears
    in message text, but there's no guarantee.

    The boundary contains dots so you have to quote it in the header."""

    global _prefix
    import time
    if _prefix is None:
        import socket
        try:
            hostid = socket.gethostbyname(socket.gethostname())
        except socket.gaierror:
            hostid = '127.0.0.1'
        try:
            uid = repr(os.getuid())
        except AttributeError:
            uid = '1'
        try:
            pid = repr(os.getpid())
        except AttributeError:
            pid = '1'
        _prefix = hostid + '.' + uid + '.' + pid
    return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())


# Subroutines for decoding some common content-transfer-types 
Example 22
Project: pyblish-win   Author: pyblish   File: subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _demo_posix():
    #
    # Example 1: Simple redirection: Get process list
    #
    plist = Popen(["ps"], stdout=PIPE).communicate()[0]
    print "Process list:"
    print plist

    #
    # Example 2: Change uid before executing child
    #
    if os.getuid() == 0:
        p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
        p.wait()

    #
    # Example 3: Connecting several subprocesses
    #
    print "Looking for 'hda'..."
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
    print repr(p2.communicate()[0])

    #
    # Example 4: Catch execution error
    #
    print
    print "Trying a weird file..."
    try:
        print Popen(["/this/path/does/not/exist"]).communicate()
    except OSError, e:
        if e.errno == errno.ENOENT:
            print "The file didn't exist.  I thought so..."
            print "Child traceback:"
            print e.child_traceback
        else:
            print "Error", e.errno 
Example 23
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_setuid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.setuid, 0)
        self.assertRaises(OverflowError, os.setuid, 1<<32) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_setgid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.setgid, 0)
        self.assertRaises(OverflowError, os.setgid, 1<<32) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_seteuid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.seteuid, 0)
        self.assertRaises(OverflowError, os.seteuid, 1<<32) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_setegid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.setegid, 0)
        self.assertRaises(OverflowError, os.setegid, 1<<32) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_setreuid(self):
        if os.getuid() != 0:
            self.assertRaises(os.error, os.setreuid, 0, 0)
        self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
        self.assertRaises(OverflowError, os.setreuid, 0, 1<<32) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        if posix.getuid() != 0:
            raise unittest.SkipTest("not enough privileges")
        if not hasattr(posix, 'getgroups'):
            raise unittest.SkipTest("need posix.getgroups")
        if sys.platform == 'darwin':
            raise unittest.SkipTest("getgroups(2) is broken on OSX")
        self.saved_groups = posix.getgroups() 
Example 29
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        if hasattr(posix, 'setgroups'):
            posix.setgroups(self.saved_groups)
        elif hasattr(posix, 'initgroups'):
            name = pwd.getpwuid(posix.getuid()).pw_name
            posix.initgroups(name, self.saved_groups[0]) 
Example 30
Project: pyblish-win   Author: pyblish   File: posixpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def expanduser(path):
    """Expand ~ and ~user constructions.  If user or $HOME is unknown,
    do nothing."""
    if not path.startswith('~'):
        return path
    i = path.find('/', 1)
    if i < 0:
        i = len(path)
    if i == 1:
        if 'HOME' not in os.environ:
            import pwd
            userhome = pwd.getpwuid(os.getuid()).pw_dir
        else:
            userhome = os.environ['HOME']
    else:
        import pwd
        try:
            pwent = pwd.getpwnam(path[1:i])
        except KeyError:
            return path
        userhome = pwent.pw_dir
    userhome = userhome.rstrip('/')
    return (userhome + path[i:]) or '/'


# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existent variables are left unchanged. 
Example 31
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: bccache.py    Apache License 2.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)
        try:
            os.mkdir(actual_dir, stat.S_IRWXU) # 0o700
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
                or not stat.S_ISDIR(actual_dir_stat.st_mode) \
                or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            raise RuntimeError('Temporary directory \'%s\' has an incorrect '
	                       'owner, permissions, or type.' % actual_dir)

        return actual_dir 
Example 32
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: bccache.py    Apache License 2.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)
        try:
            os.mkdir(actual_dir, stat.S_IRWXU) # 0o700
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
                or not stat.S_ISDIR(actual_dir_stat.st_mode) \
                or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            raise RuntimeError('Temporary directory \'%s\' has an incorrect '
	                       'owner, permissions, or type.' % actual_dir)

        return actual_dir 
Example 33
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: bccache.py    MIT License 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example 34
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: cron.py    MIT License 5 votes vote down vote up
def _write_execute(self, path):
        """
        Return the command line for writing a crontab
        """
        user = ''
        if self.user:
            if platform.system() in ['SunOS', 'HP-UX', 'AIX']:
                return "chown %s %s ; su '%s' -c '%s %s'" % (pipes.quote(self.user), pipes.quote(path), pipes.quote(self.user), CRONCMD, pipes.quote(path))
            elif pwd.getpwuid(os.getuid())[0] != self.user:
                user = '-u %s' % pipes.quote(self.user)
        return "%s %s %s" % (CRONCMD, user, pipes.quote(path)) 
Example 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: cronvar.py    MIT License 5 votes vote down vote up
def _write_execute(self, path):
        """
        Return the command line for writing a crontab
        """
        user = ''
        if self.user:
            if platform.system() in ['SunOS', 'HP-UX', 'AIX']:
                return "chown %s %s ; su '%s' -c '%s %s'" % (pipes.quote(self.user), pipes.quote(path), pipes.quote(self.user), CRONCMD, pipes.quote(path))
            elif pwd.getpwuid(os.getuid())[0] != self.user:
                user = '-u %s' % pipes.quote(self.user)
        return "%s %s %s" % (CRONCMD, user, pipes.quote(path))


# ================================================== 
Example 36
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: dconf.py    MIT License 5 votes vote down vote up
def _get_existing_dbus_session(self):
        """
        Detects and returns an existing D-Bus session bus address.

        :returns: string -- D-Bus session bus address. If a running D-Bus session was not detected, returns None.
        """

        # We'll be checking the processes of current user only.
        uid = os.getuid()

        # Go through all the pids for this user, try to extract the D-Bus
        # session bus address from environment, and ensure it is possible to
        # connect to it.
        self.module.debug("Trying to detect existing D-Bus user session for user: %d" % uid)

        for pid in psutil.pids():
            process = psutil.Process(pid)
            process_real_uid, _, _ = process.uids()
            try:
                if process_real_uid == uid and 'DBUS_SESSION_BUS_ADDRESS' in process.environ():
                    dbus_session_bus_address_candidate = process.environ()['DBUS_SESSION_BUS_ADDRESS']
                    self.module.debug("Found D-Bus user session candidate at address: %s" % dbus_session_bus_address_candidate)
                    command = ['dbus-send', '--address=%s' % dbus_session_bus_address_candidate, '--type=signal', '/', 'com.example.test']
                    rc, _, _ = self.module.run_command(command)

                    if rc == 0:
                        self.module.debug("Verified D-Bus user session candidate as usable at address: %s" % dbus_session_bus_address_candidate)

                        return dbus_session_bus_address_candidate

            # This can happen with things like SSH sessions etc.
            except psutil.AccessDenied:
                pass

        self.module.debug("Failed to find running D-Bus user session, will use dbus-run-session")

        return None 
Example 37
Project: flasky   Author: RoseOu   File: posixpath.py    MIT License 5 votes vote down vote up
def expanduser(path):
    """Expand ~ and ~user constructions.  If user or $HOME is unknown,
    do nothing."""
    if not path.startswith('~'):
        return path
    i = path.find('/', 1)
    if i < 0:
        i = len(path)
    if i == 1:
        if 'HOME' not in os.environ:
            import pwd
            userhome = pwd.getpwuid(os.getuid()).pw_dir
        else:
            userhome = os.environ['HOME']
    else:
        import pwd
        try:
            pwent = pwd.getpwnam(path[1:i])
        except KeyError:
            return path
        userhome = pwent.pw_dir
    userhome = userhome.rstrip('/')
    return (userhome + path[i:]) or '/'


# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existent variables are left unchanged. 
Example 38
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: driver.py    Apache License 2.0 5 votes vote down vote up
def _chown_console_log_for_instance(self, instance):
        console_log = self._get_console_log_path(instance)
        if os.path.exists(console_log):
            libvirt_utils.chown(console_log, os.getuid()) 
Example 39
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: driver.py    Apache License 2.0 5 votes vote down vote up
def _chown_disk_config_for_instance(self, instance):
        disk_config = self._get_disk_config_path(instance)
        if os.path.exists(disk_config):
            libvirt_utils.chown(disk_config, os.getuid()) 
Example 40
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: configdrive.py    Apache License 2.0 5 votes vote down vote up
def _make_vfat(self, path, tmpdir):
        # NOTE(mikal): This is a little horrible, but I couldn't find an
        # equivalent to genisoimage for vfat filesystems.
        with open(path, 'wb') as f:
            f.truncate(CONFIGDRIVESIZE_BYTES)

        utils.mkfs('vfat', path, label='config-2')

        with utils.tempdir() as mountdir:
            mounted = False
            try:
                _, err = utils.trycmd(
                    'mount', '-o', 'loop,uid=%d,gid=%d' % (os.getuid(),
                                                           os.getgid()),
                    path,
                    mountdir,
                    run_as_root=True)
                if err:
                    raise exception.ConfigDriveMountFailed(operation='mount',
                                                           error=err)
                mounted = True

                # NOTE(mikal): I can't just use shutils.copytree here,
                # because the destination directory already
                # exists. This is annoying.
                for ent in os.listdir(tmpdir):
                    shutil.copytree(os.path.join(tmpdir, ent),
                                    os.path.join(mountdir, ent))

            finally:
                if mounted:
                    utils.execute('umount', mountdir, run_as_root=True) 
Example 41
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_driver.py    Apache License 2.0 5 votes vote down vote up
def test_chown_disk_config_for_instance(self):
        drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
        instance = objects.Instance(**self.test_instance)
        self.mox.StubOutWithMock(fake_libvirt_utils, 'get_instance_path')
        self.mox.StubOutWithMock(os.path, 'exists')
        self.mox.StubOutWithMock(fake_libvirt_utils, 'chown')
        fake_libvirt_utils.get_instance_path(instance).AndReturn('/tmp/uuid')
        os.path.exists('/tmp/uuid/disk.config').AndReturn(True)
        fake_libvirt_utils.chown('/tmp/uuid/disk.config', os.getuid())

        self.mox.ReplayAll()
        drvr._chown_disk_config_for_instance(instance) 
Example 42
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_utils.py    Apache License 2.0 5 votes vote down vote up
def test_temporary_chown(self):
        def fake_execute(*args, **kwargs):
            if args[0] == 'chown':
                fake_execute.uid = args[1]
        self.stub_out('nova.utils.execute', fake_execute)

        with tempfile.NamedTemporaryFile() as f:
            with utils.temporary_chown(f.name, owner_uid=2):
                self.assertEqual(fake_execute.uid, 2)
            self.assertEqual(fake_execute.uid, os.getuid()) 
Example 43
Project: tmanager   Author: ssh3ll   File: commands.py    MIT License 5 votes vote down vote up
def get_user_login() -> str:
    """
    Check user uid and return user name

    :return str: user name
    """
    return "root" if os.getuid() == 0 else os.getlogin() 
Example 44
Project: ngo-addons-backport   Author: camptocamp   File: web_services.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def exp_list(self, document=False):
        if not tools.config['list_db'] and not document:
            raise openerp.exceptions.AccessDenied()
        chosen_template = tools.config['db_template']
        templates_list = tuple(set(['template0', 'template1', 'postgres', chosen_template]))
        db = sql_db.db_connect('postgres')
        cr = db.cursor()
        try:
            try:
                db_user = tools.config["db_user"]
                if not db_user and os.name == 'posix':
                    import pwd
                    db_user = pwd.getpwuid(os.getuid())[0]
                if not db_user:
                    cr.execute("select usename from pg_user where usesysid=(select datdba from pg_database where datname=%s)", (tools.config["db_name"],))
                    res = cr.fetchone()
                    db_user = res and str(res[0])
                if db_user:
                    cr.execute("select datname from pg_database where datdba=(select usesysid from pg_user where usename=%s) and datname not in %s order by datname", (db_user, templates_list))
                else:
                    cr.execute("select datname from pg_database where datname not in %s order by datname", (templates_list,))
                res = [tools.ustr(name) for (name,) in cr.fetchall()]
            except Exception:
                res = []
        finally:
            cr.close()
        res.sort()
        return res 
Example 45
Project: ngo-addons-backport   Author: camptocamp   File: server.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def check_root_user():
    """ Exit if the process's user is 'root' (on POSIX system)."""
    if os.name == 'posix':
        import pwd
        if pwd.getpwuid(os.getuid())[0] == 'root' :
            sys.stderr.write("Running as user 'root' is a security risk, aborting.\n")
            sys.exit(1) 
Example 46
Project: openhatch   Author: campbe13   File: platforms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def seteuid(uid):
    """Set effective user id."""
    uid = parse_uid(uid)
    if uid != os.getuid():
        os.seteuid(uid) 
Example 47
Project: aridi   Author: dpgon   File: gathering0.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.uid = os.getuid()
        self.gid = os.getgid()
        self.gids = os.getgroups()
        self.root = self.amiroot()
        self.files = {}
        self._examinefiles() 
Example 48
Project: certidude   Author: laurivosandi   File: test_cli.py    MIT License 5 votes vote down vote up
def clean_client():
    assert os.getuid() == 0 and os.getgid() == 0
    files = [
        "/etc/certidude/client.conf",
        "/etc/certidude/services.conf",
        "/etc/certidude/client.conf.d/ca.conf",
        "/etc/certidude/services.conf.d/ca.conf",
        "/etc/certidude/authority/ca.example.lan/ca_cert.pem",
        "/etc/certidude/authority/ca.example.lan/client_key.pem",
        "/etc/certidude/authority/ca.example.lan/server_key.pem",
        "/etc/certidude/authority/ca.example.lan/client_req.pem",
        "/etc/certidude/authority/ca.example.lan/server_req.pem",
        "/etc/certidude/authority/ca.example.lan/client_cert.pem",
        "/etc/certidude/authority/ca.example.lan/server_cert.pem",
        "/etc/NetworkManager/system-connections/IPSec to ipsec.example.lan",
        "/etc/NetworkManager/system-connections/OpenVPN to vpn.example.lan",
    ]
    for path in files:
        if os.path.exists(path):
            os.unlink(path)

    # Remove client storage area
    if os.path.exists("/tmp/ca.example.lan"):
        for filename in os.listdir("/tmp/ca.example.lan"):
            if filename.endswith(".pem"):
                os.unlink(os.path.join("/tmp/ca.example.lan", filename))

    # Reset IPsec stuff
    with open("/etc/ipsec.conf", "w") as fh: # TODO: make compatible with Fedora
        pass
    with open("/etc/ipsec.secrets", "w") as fh: # TODO: make compatible with Fedora
        pass 
Example 49
Project: certidude   Author: laurivosandi   File: test_cli.py    MIT License 5 votes vote down vote up
def assert_cleanliness():
    assert os.getuid() == 0, "Environment contaminated, UID: %d" % os.getuid()
    assert os.getgid() == 0, "Environment contaminated, GID: %d" % os.getgid()
    assert not os.environ.get("KRB5_KTNAME"), "Environment contaminated, KRB5_KTNAME=%s" % os.environ.get("KRB5_KTNAME")
    assert not os.environ.get("KRB5CCNAME"), "Environment contaminated, KRB5CCNAME=%s" % os.environ.get("KRB5CCNAME") 
Example 50
Project: gcp-variant-transforms   Author: googlegenomics   File: setup.py    Apache License 2.0 5 votes vote down vote up
def run(self):
    try:
      # For superuser UID is 0, so attempt to install pysam's C dependencies.
      if not os.getuid():
        for command in PYSAM_DEPENDENCY_COMMANDS:
          self.RunCustomCommand(command)
      self.RunCustomCommand(PYSAM_INSTALLATION_COMMAND)

    except RuntimeError:
      raise RuntimeError(
          'PySam installation has failed. Make sure you have the ' + \
          'following packages installed: autoconf automake gcc libbz2-dev ' + \
          'liblzma-dev libcurl4-openssl-dev libssl-dev make perl zlib1g-dev') 
Example 51
Project: jawfish   Author: war-and-code   File: posixpath.py    MIT License 5 votes vote down vote up
def expanduser(path):
    """Expand ~ and ~user constructions.  If user or $HOME is unknown,
    do nothing."""
    if isinstance(path, bytes):
        tilde = b'~'
    else:
        tilde = '~'
    if not path.startswith(tilde):
        return path
    sep = _get_sep(path)
    i = path.find(sep, 1)
    if i < 0:
        i = len(path)
    if i == 1:
        if 'HOME' not in os.environ:
            import pwd
            userhome = pwd.getpwuid(os.getuid()).pw_dir
        else:
            userhome = os.environ['HOME']
    else:
        import pwd
        name = path[1:i]
        if isinstance(name, bytes):
            name = str(name, 'ASCII')
        try:
            pwent = pwd.getpwnam(name)
        except KeyError:
            return path
        userhome = pwent.pw_dir
    if isinstance(path, bytes):
        userhome = os.fsencode(userhome)
        root = b'/'
    else:
        root = '/'
    userhome = userhome.rstrip(root)
    return (userhome + path[i:]) or root


# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existent variables are left unchanged. 
Example 52
Project: pyrex   Author: garmin   File: test.py    Apache License 2.0 5 votes vote down vote up
def test_users(self):
        users = set(
            self.assertPyrexContainerShellCommand(
                "getent passwd | cut -f1 -d:", quiet_init=True, capture=True
            ).split()
        )
        self.assertEqual(users, {"root", pwd.getpwuid(os.getuid()).pw_name}) 
Example 53
Project: pyatn-client   Author: ATNIO   File: private_key.py    MIT License 5 votes vote down vote up
def check_permission_safety(path):
    """Check if the file at the given path is safe to use as a state file.

    This checks that group and others have no permissions on the file and that the current user is
    the owner.
    """
    f_stats = os.stat(path)
    return (f_stats.st_mode & (stat.S_IRWXG | stat.S_IRWXO)) == 0 and f_stats.st_uid == os.getuid() 
Example 54
Project: Repobot   Author: Desgard   File: utils.py    MIT License 5 votes vote down vote up
def is_executable_file(path):
    """Checks that path is an executable regular file, or a symlink towards one.

    This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
    """
    # follow symlinks,
    fpath = os.path.realpath(path)

    if not os.path.isfile(fpath):
        # non-files (directories, fifo, etc.)
        return False

    mode = os.stat(fpath).st_mode

    if (sys.platform.startswith('sunos')
            and os.getuid() == 0):
        # When root on Solaris, os.X_OK is True for *all* files, irregardless
        # of their executability -- instead, any permission bit of any user,
        # group, or other is fine enough.
        #
        # (This may be true for other "Unix98" OS's such as HP-UX and AIX)
        return bool(mode & (stat.S_IXUSR |
                            stat.S_IXGRP |
                            stat.S_IXOTH))

    return os.access(fpath, os.X_OK) 
Example 55
Project: razzy-spinner   Author: rafasashi   File: internals.py    GNU General Public License v3.0 5 votes vote down vote up
def is_writable(path):
    # Ensure that it exists.
    if not os.path.exists(path):
        return False

    # If we're on a posix system, check its permissions.
    if hasattr(os, 'getuid'):
        statdata = os.stat(path)
        perm = stat.S_IMODE(statdata.st_mode)
        # is it world-writable?
        if (perm & 0o002):
            return True
        # do we own it?
        elif statdata.st_uid == os.getuid() and (perm & 0o200):
            return True
        # are we in a group that can write to it?
        elif (statdata.st_gid in [os.getgid()] + os.getgroups()) \
            and (perm & 0o020):
            return True
        # otherwise, we can't write to it.
        else:
            return False

    # Otherwise, we'll assume it's writable.
    # [xx] should we do other checks on other platforms?
    return True

######################################################################
# NLTK Error reporting
###################################################################### 
Example 56
Project: inmanta   Author: inmanta   File: test_io.py    Apache License 2.0 5 votes vote down vote up
def test_check_chown(io, testdir):
    # chown to the same user so we do not need root to run this test
    path = os.path.join(testdir, "chown" + str(io))
    with open(path, "w+") as fd:
        fd.write("")

    assert os.path.exists(path)

    user = pwd.getpwuid(os.getuid())[0]
    groups = [grp.getgrgid(g).gr_name for g in os.getgroups()]

    if len(groups) == 0:
        # fix for jenkins docker
        groups = [user]

    io.chown(path, user)
    stat = io.file_stat(path)
    assert stat["owner"] == user

    io.chown(path, user, groups[0])
    stat = io.file_stat(path)
    assert stat["owner"] == user
    assert stat["group"] == groups[0]

    io.chown(path, None, groups[0])
    stat = io.file_stat(path)
    assert stat["group"] == groups[0] 
Example 57
Project: ssrspeed_backup   Author: mazhenting   File: daemon.py    GNU General Public License v3.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

    try:
        pwrec = pwd.getpwnam(username)
    except KeyError:
        logging.error('user not found: %s' % username)
        raise
    user = pwrec[0]
    uid = pwrec[2]
    gid = pwrec[3]

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # will raise later

    # inspired by supervisor
    if hasattr(os, 'setgroups'):
        groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
        groups.insert(0, gid)
        os.setgroups(groups)
    os.setgid(gid)
    os.setuid(uid) 
Example 58
Project: shadowsocksr   Author: dsmnoi   File: daemon.py    Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

    try:
        pwrec = pwd.getpwnam(username)
    except KeyError:
        logging.error('user not found: %s' % username)
        raise
    user = pwrec[0]
    uid = pwrec[2]
    gid = pwrec[3]

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # will raise later

    # inspired by supervisor
    if hasattr(os, 'setgroups'):
        groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
        groups.insert(0, gid)
        os.setgroups(groups)
    os.setgid(gid)
    os.setuid(uid) 
Example 59
Project: JukeBox   Author: gauravsarkar97   File: _stdlib.py    MIT License 5 votes vote down vote up
def _get_userdir(user=None):
    """Returns the user dir or None"""

    if user is not None and not isinstance(user, fsnative):
        raise TypeError

    if is_win:
        if "HOME" in environ:
            path = environ["HOME"]
        elif "USERPROFILE" in environ:
            path = environ["USERPROFILE"]
        elif "HOMEPATH" in environ and "HOMEDRIVE" in environ:
            path = os.path.join(environ["HOMEDRIVE"], environ["HOMEPATH"])
        else:
            return

        if user is None:
            return path
        else:
            return os.path.join(os.path.dirname(path), user)
    else:
        import pwd

        if user is None:
            if "HOME" in environ:
                return environ["HOME"]
            else:
                try:
                    return path2fsn(pwd.getpwuid(os.getuid()).pw_dir)
                except KeyError:
                    return
        else:
            try:
                return path2fsn(pwd.getpwnam(user).pw_dir)
            except KeyError:
                return 
Example 60
Project: misp42splunk   Author: remg427   File: bccache.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example 61
Project: peanuts   Author: sensepost   File: peanuts.py    MIT License 5 votes vote down vote up
def startup_checks():
    if getuid() != 0:
        if not args.quiet:
            print R + "User is not Root."
        sys.exit()

    if uname()[0].startswith("Linux") and not "Darwin" not in uname():
        if not args.quiet:
            print R + "Wrong OS."
        sys.exit()
	return; 
Example 62
Project: docker-ssr-client   Author: storezhang   File: daemon.py    Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

    try:
        pwrec = pwd.getpwnam(username)
    except KeyError:
        logging.error('user not found: %s' % username)
        raise
    user = pwrec[0]
    uid = pwrec[2]
    gid = pwrec[3]

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # will raise later

    # inspired by supervisor
    if hasattr(os, 'setgroups'):
        groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
        groups.insert(0, gid)
        os.setgroups(groups)
    os.setgid(gid)
    os.setuid(uid) 
Example 63
Project: TornadoWeb   Author: VxCoder   File: bccache.py    Apache License 2.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example 64
Project: OpenYuma-WE   Author: Melacon   File: utils.py    Apache License 2.0 5 votes vote down vote up
def ensureRoot():
    if os.getuid() != 0:
        print("##### OpenYumaWE should be run as root #####")
        exit(1) 
Example 65
Project: shadowsocksr   Author: emacsenli   File: daemon.py    Apache License 2.0 5 votes vote down vote up
def set_user(username):
    if username is None:
        return

    import pwd
    import grp

    try:
        pwrec = pwd.getpwnam(username)
    except KeyError:
        logging.error('user not found: %s' % username)
        raise
    user = pwrec[0]
    uid = pwrec[2]
    gid = pwrec[3]

    cur_uid = os.getuid()
    if uid == cur_uid:
        return
    if cur_uid != 0:
        logging.error('can not set user as nonroot user')
        # will raise later

    # inspired by supervisor
    if hasattr(os, 'setgroups'):
        groups = [grprec[2] for grprec in grp.getgrall() if user in grprec[3]]
        groups.insert(0, gid)
        os.setgroups(groups)
    os.setgid(gid)
    os.setuid(uid) 
Example 66
Project: OpenBottle   Author: xiaozhuchacha   File: internals.py    MIT License 5 votes vote down vote up
def is_writable(path):
    # Ensure that it exists.
    if not os.path.exists(path):
        return False

    # If we're on a posix system, check its permissions.
    if hasattr(os, 'getuid'):
        statdata = os.stat(path)
        perm = stat.S_IMODE(statdata.st_mode)
        # is it world-writable?
        if (perm & 0o002):
            return True
        # do we own it?
        elif statdata.st_uid == os.getuid() and (perm & 0o200):
            return True
        # are we in a group that can write to it?
        elif (statdata.st_gid in [os.getgid()] + os.getgroups()) \
            and (perm & 0o020):
            return True
        # otherwise, we can't write to it.
        else:
            return False

    # Otherwise, we'll assume it's writable.
    # [xx] should we do other checks on other platforms?
    return True

######################################################################
# NLTK Error reporting
###################################################################### 
Example 67
Project: OpenBottle   Author: xiaozhuchacha   File: internals.py    MIT License 5 votes vote down vote up
def is_writable(path):
    # Ensure that it exists.
    if not os.path.exists(path):
        return False

    # If we're on a posix system, check its permissions.
    if hasattr(os, 'getuid'):
        statdata = os.stat(path)
        perm = stat.S_IMODE(statdata.st_mode)
        # is it world-writable?
        if (perm & 0o002):
            return True
        # do we own it?
        elif statdata.st_uid == os.getuid() and (perm & 0o200):
            return True
        # are we in a group that can write to it?
        elif (statdata.st_gid in [os.getgid()] + os.getgroups()) \
            and (perm & 0o020):
            return True
        # otherwise, we can't write to it.
        else:
            return False

    # Otherwise, we'll assume it's writable.
    # [xx] should we do other checks on other platforms?
    return True

######################################################################
# NLTK Error reporting
###################################################################### 
Example 68
Project: senf   Author: quodlibet   File: _stdlib.py    MIT License 5 votes vote down vote up
def _get_userdir(user=None):
    """Returns the user dir or None"""

    if user is not None and not isinstance(user, fsnative):
        raise TypeError

    if is_win:
        if "HOME" in environ:
            path = environ["HOME"]
        elif "USERPROFILE" in environ:
            path = environ["USERPROFILE"]
        elif "HOMEPATH" in environ and "HOMEDRIVE" in environ:
            path = os.path.join(environ["HOMEDRIVE"], environ["HOMEPATH"])
        else:
            return

        if user is None:
            return path
        else:
            return os.path.join(os.path.dirname(path), user)
    else:
        import pwd

        if user is None:
            if "HOME" in environ:
                return environ["HOME"]
            else:
                try:
                    return path2fsn(pwd.getpwuid(os.getuid()).pw_dir)
                except KeyError:
                    return
        else:
            try:
                return path2fsn(pwd.getpwnam(user).pw_dir)
            except KeyError:
                return 
Example 69
Project: Flask_Blog   Author: sugarguo   File: bccache.py    GNU General Public License v3.0 5 votes vote down vote up
def _get_default_cache_dir(self):
        def _unsafe_dir():
            raise RuntimeError('Cannot determine safe temp directory.  You '
                               'need to explicitly provide one.')

        tmpdir = tempfile.gettempdir()

        # On windows the temporary directory is used specific unless
        # explicitly forced otherwise.  We can just use that.
        if os.name == 'nt':
            return tmpdir
        if not hasattr(os, 'getuid'):
            _unsafe_dir()

        dirname = '_jinja2-cache-%d' % os.getuid()
        actual_dir = os.path.join(tmpdir, dirname)

        try:
            os.mkdir(actual_dir, stat.S_IRWXU)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        try:
            os.chmod(actual_dir, stat.S_IRWXU)
            actual_dir_stat = os.lstat(actual_dir)
            if actual_dir_stat.st_uid != os.getuid() \
               or not stat.S_ISDIR(actual_dir_stat.st_mode) \
               or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
                _unsafe_dir()
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise

        actual_dir_stat = os.lstat(actual_dir)
        if actual_dir_stat.st_uid != os.getuid() \
           or not stat.S_ISDIR(actual_dir_stat.st_mode) \
           or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:
            _unsafe_dir()

        return actual_dir 
Example 70
Project: LaserTOF   Author: kyleuckert   File: __init__.py    MIT License 5 votes vote down vote up
def _create_tmp_config_dir():
    """
    If the config directory can not be created, create a temporary
    directory.

    Returns None if a writable temporary directory could not be created.
    """
    import getpass
    import tempfile
    from matplotlib.cbook import mkdirs

    try:
        tempdir = tempfile.gettempdir()
    except NotImplementedError:
        # Some restricted platforms (such as Google App Engine) do not provide
        # gettempdir.
        return None
    try:
        username = getpass.getuser()
    except KeyError:
        username = str(os.getuid())

    tempdir = tempfile.mkdtemp(prefix='matplotlib-%s-' % username, dir=tempdir)

    os.environ['MPLCONFIGDIR'] = tempdir

    return tempdir 
Example 71
Project: NiujiaoDebugger   Author: MrSrc   File: pathlib.py    GNU General Public License v3.0 5 votes vote down vote up
def gethomedir(self, username):
        if not username:
            try:
                return os.environ['HOME']
            except KeyError:
                import pwd
                return pwd.getpwuid(os.getuid()).pw_dir
        else:
            import pwd
            try:
                return pwd.getpwnam(username).pw_dir
            except KeyError:
                raise RuntimeError("Can't determine home directory "
                                   "for %r" % username) 
Example 72
Project: fs_image   Author: facebookincubator   File: volume_for_repo.py    MIT License 4 votes vote down vote up
def get_volume_for_current_repo(min_free_bytes, artifacts_dir):
    '''
    Multiple repos need to be able to concurrently build images on the same
    host.  The cleanest way to achieve such isolation is to supply each repo
    with its own volume, which will store the repo's image build outputs.

    It is easiest to back this volume with a loop device. The appropriate
    size of the loop device depends on the expected size of the target being
    built.  To address this this by ensuring that prior to every build, the
    volume has at least a specified amount of space.  The default in
    `image_layer` is large enough for most builds, but really huge
    `image_layer` targets can further increase their requested
    `min_free_bytes`.

    Image-build tooling **must never** access paths in this volume without
    going through this function.  Otherwise, the volume will not get
    remounted correctly if the host containing the repo got rebooted.

    PRE-CONDITION: `artifacts_dir` exists and is writable by `root`.
    '''
    if not os.path.exists(artifacts_dir):  # pragma: no cover
        raise RuntimeError(f'{artifacts_dir} must exist')

    volume_dir = os.path.join(artifacts_dir, VOLUME_DIR)
    subprocess.check_call([
        # While Buck probably does not call this concurrently under normal
        # circumstances, the worst-case outcome is that we lose or corrupt
        # the whole buld cache, so add some locking to be on the safe side.
        'flock',
        os.path.join(artifacts_dir, '.lock.set_up_volume.sh.never.rm.or.mv'),
        'sudo',
        os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            'set_up_volume.sh',
        ),
        str(int(min_free_bytes)),  # Accepts floats & ints
        os.path.join(artifacts_dir, IMAGE_FILE),
        volume_dir,
    ])
    # We prefer to have the volume owned by the repo user, instead of root:
    #  - The trusted repo user has to be able to access the built
    #    subvolumes, but nobody else should be able to (they might contain
    #    setuid binaries & similar).  Thus, subvols ought to have wrapper
    #    directories owned by the user, with mode 0700.
    #  - This reduces the number of places we have to `sudo` to create
    #    directories inside the subvolume.
    subprocess.check_call([
        'sudo', 'chown', f'{os.getuid()}:{os.getgid()}', volume_dir,
    ])
    return volume_dir 
Example 73
Project: pyblish-win   Author: pyblish   File: test_sdist.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_make_distribution_owner_group(self):
        # now building a sdist
        dist, cmd = self.get_cmd()

        # creating a gztar and specifying the owner+group
        cmd.formats = ['gztar']
        cmd.owner = pwd.getpwuid(0)[0]
        cmd.group = grp.getgrgid(0)[0]
        cmd.ensure_finalized()
        cmd.run()

        # making sure we have the good rights
        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close()

        # building a sdist again
        dist, cmd = self.get_cmd()

        # creating a gztar
        cmd.formats = ['gztar']
        cmd.ensure_finalized()
        cmd.run()

        # making sure we have the good rights
        archive_name = join(self.tmp_dir, 'dist', 'fake-1.0.tar.gz')
        archive = tarfile.open(archive_name)

        # note that we are not testing the group ownership here
        # because, depending on the platforms and the container
        # rights (see #7408)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, os.getuid())
        finally:
            archive.close()

    # the following tests make sure there is a nice error message instead
    # of a traceback when parsing an invalid manifest template 
Example 74
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def _test_all_chown_common(self, chown_func, first_param, stat_func):
        """Common code for chown, fchown and lchown tests."""
        def check_stat(uid, gid):
            if stat_func is not None:
                stat = stat_func(first_param)
                self.assertEqual(stat.st_uid, uid)
                self.assertEqual(stat.st_gid, gid)
        uid = os.getuid()
        gid = os.getgid()
        # test a successful chown call
        chown_func(first_param, uid, gid)
        check_stat(uid, gid)
        chown_func(first_param, -1, gid)
        check_stat(uid, gid)
        chown_func(first_param, uid, -1)
        check_stat(uid, gid)

        if uid == 0:
            # Try an amusingly large uid/gid to make sure we handle
            # large unsigned values.  (chown lets you use any
            # uid/gid you like, even if they aren't defined.)
            #
            # This problem keeps coming up:
            #   http://bugs.python.org/issue1747858
            #   http://bugs.python.org/issue4591
            #   http://bugs.python.org/issue15301
            # Hopefully the fix in 4591 fixes it for good!
            #
            # This part of the test only runs when run as root.
            # Only scary people run their tests as root.

            big_value = 2**31
            chown_func(first_param, big_value, big_value)
            check_stat(big_value, big_value)
            chown_func(first_param, -1, -1)
            check_stat(big_value, big_value)
            chown_func(first_param, uid, gid)
            check_stat(uid, gid)
        elif platform.system() in ('HP-UX', 'SunOS'):
            # HP-UX and Solaris can allow a non-root user to chown() to root
            # (issue #5113)
            raise unittest.SkipTest("Skipping because of non-standard chown() "
                                    "behavior")
        else:
            # non-root cannot chown to root, raises OSError
            self.assertRaises(OSError, chown_func, first_param, 0, 0)
            check_stat(uid, gid)
            self.assertRaises(OSError, chown_func, first_param, 0, -1)
            check_stat(uid, gid)
            if 0 not in os.getgroups():
                self.assertRaises(OSError, chown_func, first_param, -1, 0)
                check_stat(uid, gid)
        # test illegal types
        for t in str, float:
            self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
            check_stat(uid, gid)
            self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
            check_stat(uid, gid) 
Example 75
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: lxc_container.py    MIT License 4 votes vote down vote up
def _create(self):
        """Create a new LXC container.

        This method will build and execute a shell command to build the
        container. It would have been nice to simply use the lxc python library
        however at the time this was written the python library, in both py2
        and py3 didn't support some of the more advanced container create
        processes. These missing processes mainly revolve around backing
        LXC containers with block devices.
        """

        build_command = [
            self.module.get_bin_path('lxc-create', True),
            '--name %s' % self.container_name,
            '--quiet'
        ]

        build_command = self._add_variables(
            variables_dict=self._get_vars(
                variables=LXC_COMMAND_MAP['create']['variables']
            ),
            build_command=build_command
        )

        # Load logging for the instance when creating it.
        if self.module.params.get('container_log') in BOOLEANS_TRUE:
            # Set the logging path to the /var/log/lxc if uid is root. else
            # set it to the home folder of the user executing.
            try:
                if os.getuid() != 0:
                    log_path = os.getenv('HOME')
                else:
                    if not os.path.isdir('/var/log/lxc/'):
                        os.makedirs('/var/log/lxc/')
                    log_path = '/var/log/lxc/'
            except OSError:
                log_path = os.getenv('HOME')

            build_command.extend([
                '--logfile %s' % os.path.join(
                    log_path, 'lxc-%s.log' % self.container_name
                ),
                '--logpriority %s' % self.module.params.get(
                    'container_log_level'
                ).upper()
            ])

        # Add the template commands to the end of the command if there are any
        template_options = self.module.params.get('template_options', None)
        if template_options:
            build_command.append('-- %s' % template_options)

        rc, return_data, err = self._run_command(build_command)
        if rc != 0:
            message = "Failed executing lxc-create."
            self.failure(
                err=err, rc=rc, msg=message, command=' '.join(build_command)
            )
        else:
            self.state_change = True 
Example 76
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: unarchive.py    MIT License 4 votes vote down vote up
def is_unarchived(self):
        cmd = [self.cmd_path, '--diff', '-C', self.dest]
        if self.zipflag:
            cmd.append(self.zipflag)
        if self.opts:
            cmd.extend(['--show-transformed-names'] + self.opts)
        if self.file_args['owner']:
            cmd.append('--owner=' + quote(self.file_args['owner']))
        if self.file_args['group']:
            cmd.append('--group=' + quote(self.file_args['group']))
        if self.module.params['keep_newer']:
            cmd.append('--keep-newer-files')
        if self.excludes:
            cmd.extend(['--exclude=' + quote(f) for f in self.excludes])
        cmd.extend(['-f', self.src])
        rc, out, err = self.module.run_command(cmd, cwd=self.dest, environ_update=dict(LANG='C', LC_ALL='C', LC_MESSAGES='C'))

        # Check whether the differences are in something that we're
        # setting anyway

        # What is different
        unarchived = True
        old_out = out
        out = ''
        run_uid = os.getuid()
        # When unarchiving as a user, or when owner/group/mode is supplied --diff is insufficient
        # Only way to be sure is to check request with what is on disk (as we do for zip)
        # Leave this up to set_fs_attributes_if_different() instead of inducing a (false) change
        for line in old_out.splitlines() + err.splitlines():
            # FIXME: Remove the bogus lines from error-output as well !
            # Ignore bogus errors on empty filenames (when using --split-component)
            if EMPTY_FILE_RE.search(line):
                continue
            if run_uid == 0 and not self.file_args['owner'] and OWNER_DIFF_RE.search(line):
                out += line + '\n'
            if run_uid == 0 and not self.file_args['group'] and GROUP_DIFF_RE.search(line):
                out += line + '\n'
            if not self.file_args['mode'] and MODE_DIFF_RE.search(line):
                out += line + '\n'
            if MOD_TIME_DIFF_RE.search(line):
                out += line + '\n'
            if MISSING_FILE_RE.search(line):
                out += line + '\n'
        if out:
            unarchived = False
        return dict(unarchived=unarchived, rc=rc, out=out, err=err, cmd=cmd) 
Example 77
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: seboolean.py    MIT License 4 votes vote down vote up
def semanage_boolean_value(module, name, state):
    rc = 0
    value = 0
    if state:
        value = 1
    handle = semanage.semanage_handle_create()
    if handle is None:
        module.fail_json(msg="Failed to create semanage library handle")
    try:
        managed = semanage.semanage_is_managed(handle)
        if managed < 0:
            module.fail_json(msg="Failed to determine whether policy is manage")
        if managed == 0:
            if os.getuid() == 0:
                module.fail_json(msg="Cannot set persistent booleans without managed policy")
            else:
                module.fail_json(msg="Cannot set persistent booleans; please try as root")
        if semanage.semanage_connect(handle) < 0:
            module.fail_json(msg="Failed to connect to semanage")

        if semanage.semanage_begin_transaction(handle) < 0:
            module.fail_json(msg="Failed to begin semanage transaction")

        rc, sebool = semanage.semanage_bool_create(handle)
        if rc < 0:
            module.fail_json(msg="Failed to create seboolean with semanage")
        if semanage.semanage_bool_set_name(handle, sebool, name) < 0:
            module.fail_json(msg="Failed to set seboolean name with semanage")
        semanage.semanage_bool_set_value(sebool, value)

        rc, boolkey = semanage.semanage_bool_key_extract(handle, sebool)
        if rc < 0:
            module.fail_json(msg="Failed to extract boolean key with semanage")

        if semanage.semanage_bool_modify_local(handle, boolkey, sebool) < 0:
            module.fail_json(msg="Failed to modify boolean key with semanage")

        if semanage.semanage_bool_set_active(handle, boolkey, sebool) < 0:
            module.fail_json(msg="Failed to set boolean key active with semanage")

        semanage.semanage_bool_key_free(boolkey)
        semanage.semanage_bool_free(sebool)

        semanage.semanage_set_reload(handle, 0)
        if semanage.semanage_commit(handle) < 0:
            module.fail_json(msg="Failed to commit changes to semanage")

        semanage.semanage_disconnect(handle)
        semanage.semanage_handle_destroy(handle)
    except Exception as e:
        module.fail_json(msg="Failed to manage policy for boolean %s: %s" % (name, str(e)))
    return True 
Example 78
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: build.py    Apache License 2.0 4 votes vote down vote up
def build_docker(platform: str, docker_binary: str, registry: str, num_retries: int, use_cache: bool) -> str:
    """
    Build a container for the given platform
    :param platform: Platform
    :param docker_binary: docker binary to use (docker/nvidia-docker)
    :param registry: Dockerhub registry name
    :param num_retries: Number of retries to build the docker image
    :param use_cache: will pass cache_from to docker to use the previously pulled tag
    :return: Id of the top level image
    """
    tag = get_docker_tag(platform=platform, registry=registry)
    logging.info("Building docker container tagged '%s' with %s", tag, docker_binary)
    #
    # We add a user with the same group as the executing non-root user so files created in the
    # container match permissions of the local user. Same for the group.
    #
    # These variables are used in the docker files to create user and group with these ids.
    # see: docker/install/ubuntu_adduser.sh
    #
    # cache-from is needed so we use the cached images tagged from the remote via
    # docker pull see: docker_cache.load_docker_cache
    #
    # This also prevents using local layers for caching: https://github.com/moby/moby/issues/33002
    # So to use local caching, we should omit the cache-from by using --no-dockerhub-cache argument to this
    # script.
    #
    # This doesn't work with multi head docker files.
    #
    cmd = [docker_binary, "build",
           "-f", get_dockerfile(platform),
           "--build-arg", "USER_ID={}".format(os.getuid()),
           "--build-arg", "GROUP_ID={}".format(os.getgid())]
    if use_cache:
        cmd.extend(["--cache-from", tag])
    cmd.extend(["-t", tag, get_dockerfiles_path()])

    @retry(subprocess.CalledProcessError, tries=num_retries)
    def run_cmd():
        logging.info("Running command: '%s'", ' '.join(cmd))
        check_call(cmd)

    run_cmd()
    # Get image id by reading the tag. It's guaranteed (except race condition) that the tag exists. Otherwise, the
    # check_call would have failed
    image_id = _get_local_image_id(docker_binary=docker_binary, docker_tag=tag)
    if not image_id:
        raise FileNotFoundError('Unable to find docker image id matching with {}'.format(tag))
    return image_id 
Example 79
Project: sic   Author: Yanixos   File: posixpath.py    GNU General Public License v3.0 4 votes vote down vote up
def expanduser(path):
    """Expand ~ and ~user constructions.  If user or $HOME is unknown,
    do nothing."""
    path = os.fspath(path)
    if isinstance(path, bytes):
        tilde = b'~'
    else:
        tilde = '~'
    if not path.startswith(tilde):
        return path
    sep = _get_sep(path)
    i = path.find(sep, 1)
    if i < 0:
        i = len(path)
    if i == 1:
        if 'HOME' not in os.environ:
            import pwd
            userhome = pwd.getpwuid(os.getuid()).pw_dir
        else:
            userhome = os.environ['HOME']
    else:
        import pwd
        name = path[1:i]
        if isinstance(name, bytes):
            name = str(name, 'ASCII')
        try:
            pwent = pwd.getpwnam(name)
        except KeyError:
            return path
        userhome = pwent.pw_dir
    if isinstance(path, bytes):
        userhome = os.fsencode(userhome)
        root = b'/'
    else:
        root = '/'
    userhome = userhome.rstrip(root)
    return (userhome + path[i:]) or root


# Expand paths containing shell variable substitutions.
# This expands the forms $variable and ${variable} only.
# Non-existent variables are left unchanged. 
Example 80
Project: certidude   Author: laurivosandi   File: authority.py    MIT License 4 votes vote down vote up
def self_enroll(skip_notify=False):
    assert os.getuid() == 0 and os.getgid() == 0, "Can self-enroll only as root"

    from certidude import const, config
    common_name = const.FQDN
    os.umask(0o0177)

    try:
        path, buf, cert, signed, expires = get_signed(common_name)
        self_public_key = asymmetric.load_public_key(path)
        private_key = asymmetric.load_private_key(config.SELF_KEY_PATH)
    except FileNotFoundError: # certificate or private key not found
        click.echo("Generating private key for frontend: %s" % config.SELF_KEY_PATH)
        with open(config.SELF_KEY_PATH, 'wb') as fh:
            if public_key.algorithm == "ec":
                self_public_key, private_key = asymmetric.generate_pair("ec", curve=public_key.curve)
            elif public_key.algorithm == "rsa":
                self_public_key, private_key = asymmetric.generate_pair("rsa", bit_size=public_key.bit_size)
            else:
                raise NotImplemented("CA certificate public key algorithm %s not supported" % public_key.algorithm)
            fh.write(asymmetric.dump_private_key(private_key, None))
    else:
        now = datetime.utcnow()
        if now + timedelta(days=1) < expires:
            click.echo("Certificate %s still valid, delete to self-enroll again" % path)
            return

    builder = CSRBuilder({"common_name": common_name}, self_public_key)
    request = builder.build(private_key)
    pid = os.fork()
    if not pid:
        from certidude import authority, config
        from certidude.common import drop_privileges
        drop_privileges()
        assert os.getuid() != 0 and os.getgid() != 0
        path = os.path.join(config.REQUESTS_DIR, common_name + ".pem")
        click.echo("Writing certificate signing request for frontend: %s" % path)
        with open(path, "wb") as fh:
            fh.write(pem_armor_csr(request)) # Write CSR with certidude permissions
        authority.sign(common_name, skip_notify=skip_notify, skip_push=True, overwrite=True, profile=config.PROFILES["srv"])
        click.echo("Frontend certificate signed")
        sys.exit(0)
    else:
        os.waitpid(pid, 0)
        os.system("systemctl reload nginx")