Python os.getgid() Examples

The following are code examples for showing how to use os.getgid(). 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
Project: threatdetectionservice   Author: flyballlabs   File: site.py    Apache License 2.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 10
Project: neo4j-social-network   Author: bestvibes   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: neo4j-social-network   Author: bestvibes   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 12
Project: beam   Author: axbaretto   File: site.py    Apache License 2.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 13
Project: beam   Author: axbaretto   File: site.py    Apache License 2.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: userspacefs   Author: rianhunter   File: fuse_adapter.py    GNU General Public License v3.0 6 votes vote down vote up
def _fs_stat_to_fuse_attrs(self, st):
        toret = {}

        toret['st_birthtime'] = utctimestamp(getattr(st, "birthtime", datetime.datetime.utcfromtimestamp(0)))
        toret['st_mtime'] = utctimestamp(getattr(st, "mtime", datetime.datetime.utcfromtimestamp(toret['st_birthtime'])))
        toret['st_ctime'] = utctimestamp(getattr(st, "ctime", datetime.datetime.utcfromtimestamp(toret['st_mtime'])))
        toret['st_atime'] = utctimestamp(getattr(st, "atime", datetime.datetime.utcfromtimestamp(toret['st_ctime'])))

        toret['st_size'] = st.size

        toret['st_mode'] = ((stat.S_IFDIR | 0o777)
                            if st.type == 'directory' else
                            (stat.S_IFREG | 0o777))

        # NB: st_nlink on directories is really inconsistent across filesystems
        #     and OSes. it arguably doesn't matter at all but we set it to
        #     non-zero just in case
        toret['st_nlink'] = 1
        toret['st_uid'] = os.getuid()
        toret['st_gid'] = os.getgid()

        return toret 
Example 15
Project: AneMo   Author: jspargo   File: site.py    GNU General Public License v2.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 16
Project: Mahjong-Solitaire   Author: MEASHY   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 17
Project: Mahjong-Solitaire   Author: MEASHY   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: oa_qian   Author: sunqb   File: site.py    Apache License 2.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 19
Project: sam-s-club-auctions   Author: sameer2800   File: site.py    Apache License 2.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 20
Project: rpython-lang-scheme   Author: tomoh1r   File: test_extfunc.py    MIT License 6 votes vote down vote up
def test_os_chown_lchown():
        path1 = udir.join('test_os_chown_lchown-1.txt')
        path2 = udir.join('test_os_chown_lchown-2.txt')
        path1.write('foobar')
        path2.mksymlinkto('some-broken-symlink')
        tmpfile1 = str(path1)
        tmpfile2 = str(path2)
        def does_stuff():
            # xxx not really a test, just checks that they are callable
            os.chown(tmpfile1, os.getuid(), os.getgid())
            os.lchown(tmpfile1, os.getuid(), os.getgid())
            os.lchown(tmpfile2, os.getuid(), os.getgid())
            try:
                os.chown(tmpfile2, os.getuid(), os.getgid())
            except OSError:
                pass
            else:
                raise AssertionError("os.chown(broken symlink) should raise")
        f1 = compile(does_stuff, [])
        f1() 
Example 21
Project: rpython-lang-scheme   Author: tomoh1r   File: test_sandlib.py    MIT License 6 votes vote down vote up
def test_getuid():
    if not hasattr(os, 'getuid'):
        py.test.skip("posix only")

    def entry_point(argv):
        import os
        print "uid is %s" % os.getuid()
        print "euid is %s" % os.geteuid()
        print "gid is %s" % os.getgid()
        print "egid is %s" % os.getegid()
        return 0
    exe = compile(entry_point)

    proc = SandboxedProcWithFiles([exe])
    output, error = proc.communicate("")
    assert output == "uid is 1000\neuid is 1000\ngid is 1000\negid is 1000\n"
    assert error == "" 
Example 22
Project: SandwichApp   Author: lovexiaov   File: site.py    Apache License 2.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 23
Project: ironpython2   Author: IronLanguages   File: test_posix.py    Apache License 2.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 24
Project: ironpython2   Author: IronLanguages   File: site.py    Apache License 2.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 25
Project: paradux   Author: paradux   File: settings.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _image_set_permissions(self):
        """
        Set the correct permissions on a new mounted image.

        return: void
        """
        paradux.logging.trace('_image_set_permissions')

        # must be performed as root
        if paradux.paradux.utils.myexec("sudo chown " + str(os.getuid()) + ":" + str(os.getgid()) + " '" + self.image_mount_point + "'"):
            paradux.logging.fatal('chown failed')

        if paradux.paradux.utils.myexec("sudo chmod 0700 '" + self.image_mount_point + "'"):
            paradux.logging.fatal('chmod failed')

        paradux.logging.debugAndSuspend( 'Check permissions' ) 
Example 26
Project: brainspell-neo   Author: glass-bead-labs   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 27
Project: banruo   Author: yingshang   File: platforms.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def check_privileges(accept_content):
    uid = os.getuid() if hasattr(os, 'getuid') else 65535
    gid = os.getgid() if hasattr(os, 'getgid') else 65535
    euid = os.geteuid() if hasattr(os, 'geteuid') else 65535
    egid = os.getegid() if hasattr(os, 'getegid') else 65535

    if hasattr(os, 'fchown'):
        if not all(hasattr(os, attr)
                   for attr in ['getuid', 'getgid', 'geteuid', 'getegid']):
            raise AssertionError('suspicious platform, contact support')

    if not uid or not gid or not euid or not egid:
        if ('pickle' in accept_content or
                'application/x-python-serialize' in accept_content):
            if not C_FORCE_ROOT:
                try:
                    print(ROOT_DISALLOWED.format(
                        uid=uid, euid=euid, gid=gid, egid=egid,
                    ), file=sys.stderr)
                finally:
                    os._exit(1)
        warnings.warn(RuntimeWarning(ROOT_DISCOURAGED.format(
            uid=uid, euid=euid, gid=gid, egid=egid,
        ))) 
Example 28
Project: kobo-predict   Author: awemulya   File: site.py    BSD 2-Clause "Simplified" 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 29
Project: XMorbid   Author: NMTech0x90   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 30
Project: Where2Eat   Author: thetimothyp   File: site.py    Creative Commons Zero v1.0 Universal 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 31
Project: PennApps2015-Heartmates   Author: natanlailari   File: site.py    Apache License 2.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 32
Project: IronHydra   Author: microdee   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 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 33
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 34
Project: openhatch   Author: campbe13   File: platforms.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def setegid(gid):
    """Set effective group id."""
    gid = parse_gid(gid)
    if gid != os.getgid():
        os.setegid(gid) 
Example 35
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 36
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 37
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 38
Project: pyrex   Author: garmin   File: test.py    Apache License 2.0 5 votes vote down vote up
def test_groups(self):
        groups = set(
            self.assertPyrexContainerShellCommand(
                "getent group | cut -f1 -d:", quiet_init=True, capture=True
            ).split()
        )
        self.assertEqual(groups, {"root", grp.getgrgid(os.getgid()).gr_name}) 
Example 39
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 40
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 41
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 42
Project: NiujiaoDebugger   Author: MrSrc   File: test_posix.py    GNU General Public License v3.0 5 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", "getcwdb", "uname",
                             "times", "getloadavg",
                             "getegid", "geteuid", "getgid", "getgroups",
                             "getpid", "getpgrp", "getppid", "getuid", "sync",
                           ]

        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 43
Project: NiujiaoDebugger   Author: MrSrc   File: test_posix.py    GNU General Public License v3.0 5 votes vote down vote up
def test_chown_dir_fd(self):
        support.unlink(support.TESTFN)
        support.create_empty_file(support.TESTFN)

        f = posix.open(posix.getcwd(), posix.O_RDONLY)
        try:
            posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
        finally:
            posix.close(f) 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: site.py    GNU General Public License v3.0 5 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


# NOTE: sysconfig and it's dependencies are relatively large but site module
# needs very limited part of them.
# To speedup startup time, we have copy of them.
#
# See https://bugs.python.org/issue29585

# Copy of sysconfig._getuserbase() 
Example 45
Project: Health-Checker   Author: KriAga   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 46
Project: autopyfactory   Author: PanDAWMS   File: factory.py    Apache License 2.0 5 votes vote down vote up
def __checkroot(self): 
        """
        If running as root, drop privileges to --runas' account.
        """
        starting_uid = os.getuid()
        starting_gid = os.getgid()
        starting_uid_name = pwd.getpwuid(starting_uid)[0]

        hostname = socket.gethostname()
        
        if os.getuid() != 0:
            self.log.info("Already running as unprivileged user %s at %s" % (starting_uid_name, hostname))
            
        if os.getuid() == 0:
            try:
                runuid = pwd.getpwnam(self.options.runAs).pw_uid
                rungid = pwd.getpwnam(self.options.runAs).pw_gid
                os.chown(self.options.logfile, runuid, rungid)
                
                os.setgid(rungid)
                os.setuid(runuid)
                os.seteuid(runuid)
                os.setegid(rungid)

                self._changehome()
                self._changewd()

                self.log.info("Now running as user %d:%d at %s..." % (runuid, rungid, hostname))
                self._printenv()

            
            except KeyError as e:
                self.log.error('No such user %s, unable run properly. Error: %s' % (self.options.runAs, e))
                sys.exit(1)
                
            except OSError as e:
                self.log.error('Could not set user or group id to %s:%s. Error: %s' % (runuid, rungid, e))
                sys.exit(1) 
Example 47
Project: autopyfactory   Author: PanDAWMS   File: factorylib.py    Apache License 2.0 5 votes vote down vote up
def __checkroot(self): 
        """
        If running as root, drop privileges to --runas' account.
        """
        starting_uid = os.getuid()
        starting_gid = os.getgid()
        starting_uid_name = pwd.getpwuid(starting_uid)[0]

        hostname = socket.gethostname()
        
        if os.getuid() != 0:
            self.log.info("Already running as unprivileged user %s at %s" % (starting_uid_name, hostname))
            
        if os.getuid() == 0:
            try:
                runuid = pwd.getpwnam(self.options.runAs).pw_uid
                rungid = pwd.getpwnam(self.options.runAs).pw_gid
                os.chown(self.options.logfile, runuid, rungid)
                
                os.setgid(rungid)
                os.setuid(runuid)
                os.seteuid(runuid)
                os.setegid(rungid)

                self._changehome()
                self._changewd()

                self.log.info("Now running as user %d:%d at %s..." % (runuid, rungid, hostname))
                self._printenv()

            
            except KeyError, e:
                self.log.error('No such user %s, unable run properly. Error: %s' % (self.options.runAs, e))
                sys.exit(1)
                
            except OSError, e:
                self.log.error('Could not set user or group id to %s:%s. Error: %s' % (runuid, rungid, e))
                sys.exit(1) 
Example 48
Project: squeakspace   Author: eek6   File: _util.py    GNU General Public License v3.0 5 votes vote down vote up
def _make_passphrase(length=None, save=False, file=None):
    """Create a passphrase and write it to a file that only the user can read.

    This is not very secure, and should not be relied upon for actual key
    passphrases.

    :param int length: The length in bytes of the string to generate.

    :param file file: The file to save the generated passphrase in. If not
        given, defaults to 'passphrase-<the real user id>-<seconds since
        epoch>' in the top-level directory.
    """
    if not length:
        length = 40

    passphrase = _make_random_string(length)

    if save:
        ruid, euid, suid = os.getresuid()
        gid = os.getgid()
        now = mktime(localtime())

        if not file:
            filename = str('passphrase-%s-%s' % uid, now)
            file = os.path.join(_repo, filename)

        with open(file, 'a') as fh:
            fh.write(passphrase)
            fh.flush()
            fh.close()
            os.chmod(file, stat.S_IRUSR | stat.S_IWUSR)
            os.chown(file, ruid, gid)

        log.warn("Generated passphrase saved to %s" % file)
    return passphrase 
Example 49
Project: httpfs   Author: bgaifullin   File: httpfs.py    GNU General Public License v2.0 5 votes vote down vote up
def getattr(self, path, fh=None):
        try:
            url = self._url(path)
            logging.debug("getattr %s (%s), %s", path, url, fh)
            response = self.opener.open(HTTPRequest(url, method='HEAD'))
            url = response.geturl()
            logging.debug("getattr %s", url)

            if url.endswith('/'):
                m_mode = 040444
                m_time = 0
                m_size = 0
            else:
                m_mode = 0100444
                m_size = int(response.headers.get('Content-Length', 0))
                try:
                    m_time = int(time.mktime(dateutil.parser.parse(response.headers['Last-Modified']).timetuple()))
                except KeyError:
                    m_time = 0

            result = dict(st_atime=m_time, st_ctime=m_time, st_mtime=m_time, st_gid=os.getgid(),
                          st_mode=m_mode, st_nlink=1, st_uid=os.getuid(), st_size=m_size)
            logging.debug("getattr -> %s", result)
            return result

        except urllib.HTTPError as e:
            logging.error("getattr -> %r", e)
            raise self._error(e)
        except Exception as e:
            logging.exception("getattr -> %r", e)
            raise FuseOSError(errno.EAGAIN) 
Example 50
Project: nova   Author: ZhanHan   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 51
Project: benchexec   Author: sosy-lab   File: container.py    Apache License 2.0 5 votes vote down vote up
def setup_user_mapping(
    pid,
    uid=os.getuid(),
    gid=os.getgid(),
    parent_uid=os.getuid(),
    parent_gid=os.getgid(),
):
    """Write uid_map and gid_map in /proc to create a user mapping
    that maps our user from outside the container to the same user inside the container
    (and no other users are mapped).
    @see: http://man7.org/linux/man-pages/man7/user_namespaces.7.html
    @param pid: The PID of the process in the container.
    @param uid: The UID that shall be used in the container.
    @param gid: The GID that shall be used in the container.
    @param parent_uid: The UID that is used in the parent namespace.
    @param parent_gid: The GID that is used in the parent namespace.
    """
    proc_child = os.path.join("/proc", str(pid))
    try:
        # map uid internally to our uid externally
        uid_map = "{0} {1} 1".format(uid, parent_uid)
        util.write_file(uid_map, proc_child, "uid_map")
    except IOError as e:
        logging.warning("Creating UID mapping into container failed: %s", e)

    try:
        util.write_file("deny", proc_child, "setgroups")
    except IOError as e:
        # Not all systems have this file (depends on the kernel version),
        # but if it does not exist, we do not need to write to it.
        if e.errno != errno.ENOENT:
            logging.warning("Could not write to setgroups file in /proc: %s", e)

    try:
        # map gid internally to our gid externally
        gid_map = "{0} {1} 1".format(gid, parent_gid)
        util.write_file(gid_map, proc_child, "gid_map")
    except IOError as e:
        logging.warning("Creating GID mapping into container failed: %s", e) 
Example 52
Project: pysshrp   Author: ybulach   File: serverthread.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, request, client_address, server):
		# Change user and group (only when runned as root)
		if (os.getgid() == 0) and pysshrp.common.config.userId:
			os.setgid(pysshrp.common.config.userId)
		if (os.getuid() == 0) and pysshrp.common.config.groupId:
			os.setuid(pysshrp.common.config.groupId)

		SocketServer.BaseRequestHandler.__init__(self, request, client_address, server) 
Example 53
Project: cog   Author: drone115b   File: source.py    Apache License 2.0 5 votes vote down vote up
def execute_code( compiled_obj, globals_dict ):
  uid = os.getuid()
  gid = os.getgid()
  if uid == 0 or gid == 0 :
      raise SystemError( "Permission Denied" )
  else:
      exec( compiled_obj, globals_dict ) 
Example 54
Project: rpython-lang-scheme   Author: tomoh1r   File: test_posix.py    MIT License 5 votes vote down vote up
def test_chown(self):
            f = open(path, "w")
            f.write("xyz")
            f.close()
            def f():
                try:
                    posix.chown(path, os.getuid(), os.getgid())
                    return 1
                except OSError:
                    return 2

            assert self.interpret(f, []) == 1
            os.unlink(path)
            assert self.interpret(f, []) == 2 
Example 55
Project: rpython-lang-scheme   Author: tomoh1r   File: test_posix.py    MIT License 5 votes vote down vote up
def test_getgid(self):
            def f():
                return os.getgid()
            assert self.interpret(f, []) == f() 
Example 56
Project: rpython-lang-scheme   Author: tomoh1r   File: test_extfunc.py    MIT License 5 votes vote down vote up
def test_os_fchown():
        path1 = udir.join('test_os_fchown.txt')
        tmpfile1 = str(path1)
        def does_stuff():
            # xxx not really a test, just checks that it is callable
            fd = os.open(tmpfile1, os.O_WRONLY | os.O_CREAT, 0777)
            os.fchown(fd, os.getuid(), os.getgid())
            os.close(fd)
        f1 = compile(does_stuff, [])
        f1() 
Example 57
Project: agentless-system-crawler   Author: cloudviz   File: test_functional_fprobe.py    Apache License 2.0 5 votes vote down vote up
def test_remove_datafiles(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: datafiles of disappeared interface '
                    'being removed')

        fc = FprobeContainerCrawler()
        assert fc.get_feature() == 'fprobe'

        # we pretend that an interface test.eth0 existed
        ifname = 'test.eth0'
        FprobeContainerCrawler.fprobes_started[ifname] = 1234

        self.params['output_filepattern'] = 'fprobe-{ifname}-{timestamp}'

        # create a datafile for this fake interface
        timestamp = int(time.time())
        filepattern = 'fprobe-{ifname}-{timestamp}'.format(ifname=ifname,
                                                           timestamp=timestamp)
        params = [
            'socket-datacollector',
            '--dir', self.output_dir,
            '--filepattern', filepattern,
        ]

        # have the fake socket-datacollector write a file with the ifname in
        # the filename
        fc.setup_outputdir(self.output_dir, os.getuid(), os.getgid())
        simulate_socket_datacollector(params)
        written_file = os.path.join(self.output_dir, filepattern)
        assert os.path.isfile(written_file)

        FprobeContainerCrawler.next_cleanup = 0
        # calling fc.crawl() will trigger a cleanup of that file
        # since our fake interface never existed
        fc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should be gone now
        assert not os.path.isfile(written_file) 
Example 58
Project: agentless-system-crawler   Author: cloudviz   File: test_functional_ctprobe.py    Apache License 2.0 5 votes vote down vote up
def test_remove_datafiles(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: datafiles of disappeared interface '
                    'being removed')

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        # we pretend that an interface test.eth0 existed
        ifname = 'test.eth0'
        CTProbeContainerCrawler.ifaces_monitored.append(ifname)

        self.params['output_filepattern'] = 'ctprobe-{ifname}-{timestamp}'

        # create a datafile for this fake interface
        timestamp = int(time.time())
        filepattern = 'ctprobe-{ifname}-{timestamp}' \
                      .format(ifname=ifname, timestamp=timestamp)
        # have the ctprobe write a file with the ifname in
        # the filename
        ctc.setup_outputdir(self.output_dir, os.getuid(), os.getgid())
        simulate_ctprobe('file+json://%s/%s' % (self.output_dir, filepattern))
        written_file = os.path.join(self.output_dir, filepattern)
        assert os.path.isfile(written_file)

        CTProbeContainerCrawler.next_cleanup = 0
        # calling ctc.crawl() will trigger a cleanup of that file
        # since our fake interface never existed
        ctc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should be gone now
        assert not os.path.isfile(written_file) 
Example 59
Project: open-recipe   Author: dspray95   File: mailmail.py    The Unlicense 5 votes vote down vote up
def deny(conf):
    uid = os.getuid()
    gid = os.getgid()

    if conf.useraccess == 'deny':
        if uid in conf.denyUIDs:
            return True
        if uid in conf.allowUIDs:
            return False
    else:
        if uid in conf.allowUIDs:
            return False
        if uid in conf.denyUIDs:
            return True

    if conf.groupaccess == 'deny':
        if gid in conf.denyGIDs:
            return True
        if gid in conf.allowGIDs:
            return False
    else:
        if gid in conf.allowGIDs:
            return False
        if gid in conf.denyGIDs:
            return True

    return not conf.defaultAccess 
Example 60
Project: open-recipe   Author: dspray95   File: test_process.py    The Unlicense 5 votes vote down vote up
def getgid(self):
        """
        Override C{os.getgid}. Return a dumb number.
        """
        return 1235 
Example 61
Project: open-recipe   Author: dspray95   File: inetd.py    The Unlicense 5 votes vote down vote up
def connectionMade(self):
        sockFD = self.transport.fileno()
        childFDs = {0: sockFD, 1: sockFD}
        if self.factory.stderrFile:
            childFDs[2] = self.factory.stderrFile.fileno()

        # processes run by inetd expect blocking sockets
        # FIXME: maybe this should be done in process.py?  are other uses of
        #        Process possibly affected by this?
        fdesc.setBlocking(sockFD)
        if 2 in childFDs:
            fdesc.setBlocking(childFDs[2])

        service = self.factory.service
        uid = service.user
        gid = service.group

        # don't tell Process to change our UID/GID if it's what we
        # already are
        if uid == os.getuid():
            uid = None
        if gid == os.getgid():
            gid = None

        process.Process(None, service.program, service.programArgs, os.environ,
                        None, None, uid, gid, childFDs)

        reactor.removeReader(self.transport)
        reactor.removeWriter(self.transport) 
Example 62
Project: vnpy_crypto   Author: birforce   File: test_process.py    MIT License 5 votes vote down vote up
def test_gids(self):
        p = psutil.Process()
        real, effective, saved = p.gids()
        # os.getuid() refers to "real" uid
        self.assertEqual(real, os.getgid())
        # os.geteuid() refers to "effective" uid
        self.assertEqual(effective, os.getegid())
        # No such thing as os.getsgid() ("saved" gid), but starting
        # from python 2.7 we have os.getresgid() which returns all
        # of them.
        if hasattr(os, "getresuid"):
            self.assertEqual(os.getresgid(), p.gids()) 
Example 63
Project: btw-backup   Author: mangalam-research   File: tests.py    Mozilla Public License 2.0 5 votes vote down vote up
def test_uid(self):
        # We are limited as to what we can test. This only tests that
        # the code that is run when --uid is specified does not crash,
        # but it does not test that the operation is happening.
        uid = os.getuid()
        gid = os.getgid()
        uid_str = pwd.getpwuid(uid).pw_name
        gid_str = grp.getgrgid(gid).gr_name
        self.backup(["--uid", uid_str + ":" + gid_str]) 
Example 64
Project: lightex   Author: ofnote   File: config_containers.py    Apache License 2.0 5 votes vote down vote up
def __post_init__(self):
        self.command = ' '.join(self.command)
        for key, value in self.resources.items():
            setattr(self, key, value)
        #self.group_add = [os.getgid()]

        print (f'dockerconfig: {self.command}') 
Example 65
Project: Comparative-Annotation-Toolkit   Author: ComparativeGenomicsToolkit   File: procOps.py    Apache License 2.0 5 votes vote down vote up
def getDockerCommand(image, cmd):
    """
    Takes in a command (as a list of arguments like ['halStats',
    'file']) and outputs another list of arguments that will run it in
    the given Docker container, binding directories when necessary.

    image: the Docker image to use, e.g. 'quay.io/comparative-genomics-toolkit/cactus:latest'
    cmd: list of arguments
    """
    dockerPreamble = ['docker', 'run', '-i', '--rm', '-u', "%s:%s" % (os.getuid(), os.getgid())]
    work_dirs = []
    for i, arg in enumerate(cmd):
        if arg.startswith('-') and '=' in arg:
            # We assume this is -option=value syntax. Special-case
            # this to check if the value is a path.
            arg = arg.split('=')[1]
        dirname = os.path.dirname(arg)
        if os.path.exists(dirname):
            # The dirname exists, so we will try to mount it.
            arg = os.path.abspath(arg)
            if arg.startswith('/dev'):
                continue
            add_to_work_dirs(dirname, work_dirs)
    for work_dir in work_dirs:
        work_dir = os.path.abspath(work_dir)
        dockerPreamble += ['-v', work_dir + ':' + work_dir]
    return dockerPreamble + [image] + cmd 
Example 66
Project: IronHydra   Author: microdee   File: tarfile.py    MIT License 5 votes vote down vote up
def chown(self, tarinfo, targetpath):
        """Set owner of targetpath according to tarinfo.
        """
        if pwd and hasattr(os, "geteuid") and os.geteuid() == 0:
            # We have to be root to do so.
            try:
                g = grp.getgrnam(tarinfo.gname)[2]
            except KeyError:
                try:
                    g = grp.getgrgid(tarinfo.gid)[2]
                except KeyError:
                    g = os.getgid()
            try:
                u = pwd.getpwnam(tarinfo.uname)[2]
            except KeyError:
                try:
                    u = pwd.getpwuid(tarinfo.uid)[2]
                except KeyError:
                    u = os.getuid()
            try:
                if tarinfo.issym() and hasattr(os, "lchown"):
                    os.lchown(targetpath, u, g)
                else:
                    if sys.platform != "os2emx":
                        os.chown(targetpath, u, g)
            except EnvironmentError, e:
                raise ExtractError("could not change owner") 
Example 67
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 68
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 69
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 70
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") 
Example 71
Project: NiujiaoDebugger   Author: MrSrc   File: test_shutil.py    GNU General Public License v3.0 4 votes vote down vote up
def test_chown(self):

        # cleaned-up automatically by TestShutil.tearDown method
        dirname = self.mkdtemp()
        filename = tempfile.mktemp(dir=dirname)
        write_file(filename, 'testing chown function')

        with self.assertRaises(ValueError):
            shutil.chown(filename)

        with self.assertRaises(LookupError):
            shutil.chown(filename, user='non-existing username')

        with self.assertRaises(LookupError):
            shutil.chown(filename, group='non-existing groupname')

        with self.assertRaises(TypeError):
            shutil.chown(filename, b'spam')

        with self.assertRaises(TypeError):
            shutil.chown(filename, 3.14)

        uid = os.getuid()
        gid = os.getgid()

        def check_chown(path, uid=None, gid=None):
            s = os.stat(filename)
            if uid is not None:
                self.assertEqual(uid, s.st_uid)
            if gid is not None:
                self.assertEqual(gid, s.st_gid)

        shutil.chown(filename, uid, gid)
        check_chown(filename, uid, gid)
        shutil.chown(filename, uid)
        check_chown(filename, uid)
        shutil.chown(filename, user=uid)
        check_chown(filename, uid)
        shutil.chown(filename, group=gid)
        check_chown(filename, gid=gid)

        shutil.chown(dirname, uid, gid)
        check_chown(dirname, uid, gid)
        shutil.chown(dirname, uid)
        check_chown(dirname, uid)
        shutil.chown(dirname, user=uid)
        check_chown(dirname, uid)
        shutil.chown(dirname, group=gid)
        check_chown(dirname, gid=gid)

        user = pwd.getpwuid(uid)[0]
        group = grp.getgrgid(gid)[0]
        shutil.chown(filename, user, group)
        check_chown(filename, uid, gid)
        shutil.chown(dirname, user, group)
        check_chown(dirname, uid, gid) 
Example 72
Project: NiujiaoDebugger   Author: MrSrc   File: test_posix.py    GNU 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 73
Project: ironpython2   Author: IronLanguages   File: test_posix.py    Apache License 2.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 74
Project: agentless-system-crawler   Author: cloudviz   File: test_functional_fprobe.py    Apache License 2.0 4 votes vote down vote up
def test_remove_stale_files(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: stale file being removed')

        fc = FprobeContainerCrawler()
        assert fc.get_feature() == 'fprobe'

        # we pretend that an interface test.eth0 existed
        ifname = 'test.eth0'
        FprobeContainerCrawler.fprobes_started[ifname] = 1234

        self.params['output_filepattern'] = 'fprobe-{ifname}-{timestamp}'

        # have the fake socket-datacollector write a file with the ifname in
        # the filename
        fc.setup_outputdir(self.output_dir, os.getuid(), os.getgid())

        written_file = os.path.join(self.output_dir, 'test.output')
        with open(written_file, 'a') as f:
            f.write('hello')

        assert os.path.isfile(written_file)

        # mock the stale file timeout so that our file will get removed
        # with in reasonable time
        FprobeContainerCrawler.STALE_FILE_TIMEOUT = 5

        # calling fc.crawl() will not trigger a cleanup of that file
        # the first time
        logger.info('1st crawl')
        fc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should still be here
        assert os.path.isfile(written_file)

        # the next time we will crawl, the file will be removed
        FprobeContainerCrawler.next_cleanup = time.time()
        time.sleep(FprobeContainerCrawler.STALE_FILE_TIMEOUT + 1)

        logger.info('2nd crawl')
        fc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should be gone now
        assert not os.path.isfile(written_file) 
Example 75
Project: agentless-system-crawler   Author: cloudviz   File: test_functional_ctprobe.py    Apache License 2.0 4 votes vote down vote up
def test_remove_stale_files(self):
        logger = logging.getLogger("crawlutils")
        logger.info('>>> Testcase: stale file being removed')

        ctc = CTProbeContainerCrawler()
        assert ctc.get_feature() == 'ctprobe'

        # we pretend that an interface test.eth0 existed
        ifname = 'test.eth0'
        CTProbeContainerCrawler.ifaces_monitored.append(ifname)

        self.params['output_filepattern'] = 'ctprobe-{ifname}-{timestamp}'

        # have the fake socket-datacollector write a file with the ifname in
        # the filename
        ctc.setup_outputdir(self.output_dir, os.getuid(), os.getgid())

        written_file = os.path.join(self.output_dir, 'test.output')
        with open(written_file, 'a') as f:
            f.write('hello')

        assert os.path.isfile(written_file)

        # mock the stale file timeout so that our file will get removed
        # with in reasonable time
        CTProbeContainerCrawler.STALE_FILE_TIMEOUT = 5

        # calling ctc.crawl() will not trigger a cleanup of that file
        # the first time
        logger.info('1st crawl')
        ctc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should still be here
        assert os.path.isfile(written_file)

        # the next time we will crawl, the file will be removed
        CTProbeContainerCrawler.next_cleanup = time.time()
        time.sleep(CTProbeContainerCrawler.STALE_FILE_TIMEOUT + 1)

        logger.info('2nd crawl')
        ctc.crawl(self.container['Id'], avoid_setns=False, **self.params)

        # file should be gone now
        assert not os.path.isfile(written_file) 
Example 76
Project: banruo   Author: yingshang   File: platforms.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def maybe_drop_privileges(uid=None, gid=None):
    """Change process privileges to new user/group.

    If UID and GID is specified, the real user/group is changed.

    If only UID is specified, the real user is changed, and the group is
    changed to the users primary group.

    If only GID is specified, only the group is changed.

    """
    if sys.platform == 'win32':
        return
    if os.geteuid():
        # no point trying to setuid unless we're root.
        if not os.getuid():
            raise AssertionError('contact support')
    uid = uid and parse_uid(uid)
    gid = gid and parse_gid(gid)

    if uid:
        # If GID isn't defined, get the primary GID of the user.
        if not gid and pwd:
            gid = pwd.getpwuid(uid).pw_gid
        # Must set the GID before initgroups(), as setgid()
        # is known to zap the group list on some platforms.

        # setgid must happen before setuid (otherwise the setgid operation
        # may fail because of insufficient privileges and possibly stay
        # in a privileged group).
        setgid(gid)
        initgroups(uid, gid)

        # at last:
        setuid(uid)
        # ... and make sure privileges cannot be restored:
        try:
            setuid(0)
        except OSError as exc:
            if get_errno(exc) != errno.EPERM:
                raise
            pass  # Good: cannot restore privileges.
        else:
            raise RuntimeError(
                'non-root user able to restore privileges after setuid.')
    else:
        gid and setgid(gid)

    if uid and (not os.getuid()) and not (os.geteuid()):
        raise AssertionError('Still root uid after drop privileges!')
    if gid and (not os.getgid()) and not (os.getegid()):
        raise AssertionError('Still root gid after drop privileges!') 
Example 77
Project: cdn-cache   Author: gbrunacci   File: plugins.py    Apache License 2.0 4 votes vote down vote up
def start(self):
        # uid/gid
        def current_ids():
            """Return the current (uid, gid) if available."""
            name, group = None, None
            if pwd:
                name = pwd.getpwuid(os.getuid())[0]
            if grp:
                group = grp.getgrgid(os.getgid())[0]
            return name, group

        if self.finalized:
            if not (self.uid is None and self.gid is None):
                self.bus.log('Already running as uid: %r gid: %r' %
                             current_ids())
        else:
            if self.uid is None and self.gid is None:
                if pwd or grp:
                    self.bus.log('uid/gid not set', level=30)
            else:
                self.bus.log('Started as uid: %r gid: %r' % current_ids())
                if self.gid is not None:
                    os.setgid(self.gid)
                    os.setgroups([])
                if self.uid is not None:
                    os.setuid(self.uid)
                self.bus.log('Running as uid: %r gid: %r' % current_ids())

        # umask
        if self.finalized:
            if self.umask is not None:
                self.bus.log('umask already set to: %03o' % self.umask)
        else:
            if self.umask is None:
                self.bus.log('umask not set', level=30)
            else:
                old_umask = os.umask(self.umask)
                self.bus.log('umask old: %03o, new: %03o' %
                             (old_umask, self.umask))

        self.finalized = True
    # This is slightly higher than the priority for server.start
    # in order to facilitate the most common use: starting on a low
    # port (which requires root) and then dropping to another user. 
Example 78
Project: open-recipe   Author: dspray95   File: test_mailmail.py    The Unlicense 4 votes vote down vote up
def test_readInvalidConfig(self):
        """
        Error messages for illegal UID value, illegal GID value, and illegal
        identity entry will be sent to stderr.
        """
        stdin = NativeStringIO('\n')
        self.patch(sys, 'stdin', stdin)

        filename = self.mktemp()
        myUid = os.getuid()
        myGid = os.getgid()

        with open(filename, "w") as f:
            # Create a config file with some invalid values
            f.write("[useraccess]\n"
                    "allow=invaliduser2,invaliduser1\n"
                    "deny=invaliduser3,invaliduser4,{}\n"
                    "order=allow,deny\n"
                    "[groupaccess]\n"
                    "allow=invalidgid1,invalidgid2\n"
                    "deny=invalidgid1,invalidgid2,{}\n"
                    "order=deny,allow\n"
                    "[identity]\n"
                    "localhost=funny\n"
                    "[addresses]\n"
                    "smarthost=localhost\n"
                    "default_domain=example.com\n".format(myUid, myGid))

        # The mailmail script looks in
        # the twisted.mail.scripts.GLOBAL_CFG variable
        # and then the twisted.mail.scripts.LOCAL_CFG
        # variable for the path to it's  config file.
        #
        # Override twisted.mail.scripts.LOCAL_CFG with the file we just
        # created.
        self.patch(mailmail, "LOCAL_CFG", filename)

        argv = ("test_mailmail.py", "[email protected]", "-oep")
        self.patch(sys, 'argv', argv)
        mailmail.run()
        self.assertRegex(self.out.getvalue(),
                         "Illegal UID in \\[useraccess\\] section: "
                         "invaliduser1")
        self.assertRegex(self.out.getvalue(),
                         "Illegal GID in \\[groupaccess\\] section: "
                         "invalidgid1")
        self.assertRegex(self.out.getvalue(),
                         'Illegal entry in \\[identity\\] section: funny') 
Example 79
Project: open-recipe   Author: dspray95   File: test_twistd.py    The Unlicense 4 votes vote down vote up
def patchUserDatabase(patch, user, uid, group, gid):
    """
    Patch L{pwd.getpwnam} so that it behaves as though only one user exists
    and patch L{grp.getgrnam} so that it behaves as though only one group
    exists.

    @param patch: A function like L{TestCase.patch} which will be used to
        install the fake implementations.

    @type user: C{str}
    @param user: The name of the single user which will exist.

    @type uid: C{int}
    @param uid: The UID of the single user which will exist.

    @type group: C{str}
    @param group: The name of the single user which will exist.

    @type gid: C{int}
    @param gid: The GID of the single group which will exist.
    """
    # Try not to be an unverified fake, but try not to depend on quirks of
    # the system either (eg, run as a process with a uid and gid which
    # equal each other, and so doesn't reliably test that uid is used where
    # uid should be used and gid is used where gid should be used). -exarkun
    pwent = pwd.getpwuid(os.getuid())
    grent = grp.getgrgid(os.getgid())

    database = UserDatabase()
    database.addUser(
        user, pwent.pw_passwd, uid, gid,
        pwent.pw_gecos, pwent.pw_dir, pwent.pw_shell)

    def getgrnam(name):
        result = list(grent)
        result[result.index(grent.gr_name)] = group
        result[result.index(grent.gr_gid)] = gid
        result = tuple(result)
        return {group: result}[name]

    patch(pwd, "getpwnam", database.getpwnam)
    patch(grp, "getgrnam", getgrnam)
    patch(pwd, "getpwuid", database.getpwuid) 
Example 80
Project: lightex   Author: ofnote   File: docker_utils.py    Apache License 2.0 4 votes vote down vote up
def create_job(expt, log_to_file=True):
    er = expt.er
    ctr = er.ctr
    run = expt.run

    #print (run.output_dir)
    uid = os.getuid()
    gid = os.getgid()

    # hack to add ubuntu user with right gid

    run_cmd = f'groupadd --gid {gid} ubuntu; useradd -rm -d /home/ubuntu -s /bin/bash ubuntu -u {uid} -g {gid}\
                && mkdir -p {run.output_dir}\
                && chown -R ubuntu:ubuntu {run.output_dir}/..\
                && su - ubuntu\
                && ls -ld {run.output_dir}; whoami'

    #&& echo "ubuntu ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers\
    #   && su - ubuntu\ # this doesnt work!!
               
    run_cmd += f'&& {render_command(expt)}'
    command = ['sh', '-c', f'\"{run_cmd}\"']

    mount_list = er.get_volume_mounts() #[{name, mount_path, host_path}]
    mounts = create_mounts(mount_list)
    #print (f'mounts: {mounts}')
    env = create_env(expt)
    network = run.get_network()


    D = DockerConfig(
            image=ctr.build.image_url,
            name=run.run_name,
            command=command,
            working_dir=ctr.working_dir,
            mounts=mounts,
            resources={'mem_limit': run.max_memory},
            auto_remove=(not run.persist),
            environment=env,
            network=network
        )
    #print ("==========")
    #print (D.to_dict())
    
    container = run_container(D)

    if log_to_file:
        storage_out_dir = expt.er.storage.output_dir
        run_output_log_file = f'{storage_out_dir}/{run.run_name}.log'
        print (f'Logging output to {run_output_log_file}')

        with open(run_output_log_file, 'wb') as fp:
            for line in container.logs(stream=True):
                #print(line)
                fp.write(line)

    return container