Esempio n. 1
0
def droppriv(user, group=None, umask=0022):
    """Drops the privileges of the running process.

    Drops privileges to the user, group, and umask given, changes the
    process to session leader, and changes working directories to /. If
    a group is not given, the user's default group will be used. Will
    raise an Exception with an explanatory message if the user or group
    cannot be found or if permission is denied while attempting the
    switch.

    :param user: The user to switch to.
    :param group: The group to switch to; defaults to the default group
        of the user.
    :param umask: The umask to set; defaults 0022.
    """
    if user or group:
        uid = geteuid()
        try:
            setgroups([])
        except OSError as err:
            if err.errno != EPERM:
                raise
        gid = getegid()
        if user:
            try:
                pw = getpwnam(user)
            except KeyError as err:
                raise Exception('Cannot switch to unknown user %r.' % user)
            uid = pw.pw_uid
            gid = pw.pw_gid
        if group:
            try:
                gr = getgrnam(group)
            except KeyError as err:
                raise Exception('Cannot switch to unknown group %r.' % group)
            gid = gr.gr_gid
        try:
            setgid(gid)
        except OSError as err:
            raise Exception(
                'Permission denied when switching to group %r.' % group)
        try:
            setuid(uid)
        except OSError as err:
            raise Exception(
                'Permission denied when switching to user %r.' % user)
    os_umask(umask)
    try:
        setsid()  # Become session leader.
    except OSError as err:
        if err.errno != EPERM:
            raise
    chdir('/')
Esempio n. 2
0
            try:
                gr = getgrnam(group)
            except KeyError, err:
                raise Exception('Cannot switch to unknown group %r.' % group)
            gid = gr.gr_gid
        try:
            setgid(gid)
        except OSError, err:
            raise Exception(
                'Permission denied when switching to group %r.' % group)
        try:
            setuid(uid)
        except OSError, err:
            raise Exception(
                'Permission denied when switching to user %r.' % user)
    os_umask(umask)
    try:
        setsid()  # Become session leader until already so.
    except OSError, err:
        if err.errno != EPERM:
            raise
    chdir('/')


def get_listening_tcp_socket(ip, port, backlog=4096, retry=30, certfile=None,
                             keyfile=None, style=None):
    """
    Returns a socket.socket bound to the given ip and tcp port with
    other optional parameters.

    :param ip: The ip address to listen on. ``''`` and ``'*'`` are