Python socket.SO_PEERCRED Examples

The following are 6 code examples of socket.SO_PEERCRED(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: peercredprotocol.py    From treadmill with Apache License 2.0 6 votes vote down vote up
def lineReceived(self, line):
        """Process line from the clien."""
        creds = self.transport.socket.getsockopt(
            socket.SOL_SOCKET,
            socket.SO_PEERCRED,
            struct.calcsize('3i')
        )

        pid, uid, gid = struct.unpack('3i', creds)
        _LOGGER.info('Connection from pid: %d, uid: %d, gid %d', pid, uid, gid)

        try:
            self.username = utils.get_username(uid)
            self.uid = uid
            self.gid = gid

            decoded = base64.standard_b64decode(line)
            assert isinstance(decoded, bytes), repr(decoded)
            self.got_line(decoded)
        except KeyError:
            _LOGGER.warning('Unable to get username for uid: %d', uid)
            self.username = None
            self.transport.loseConnection() 
Example #2
Source File: manhole.py    From mautrix-python with Mozilla Public License 2.0 5 votes vote down vote up
def __call__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
                       ) -> None:
        sock = writer.transport.get_extra_info("socket")
        # TODO support non-linux OSes
        # I think FreeBSD uses SCM_CREDS
        creds = sock.getsockopt(SOL_SOCKET, SO_PEERCRED, struct.calcsize('3i'))
        pid, uid, gid = struct.unpack('3i', creds)
        user_info = pwd.getpwuid(uid)
        username = f"{user_info.pw_name} ({uid})" if user_info and user_info.pw_name else uid
        if len(self.whitelist) > 0 and uid not in self.whitelist:
            writer.write(b"You are not whitelisted to use the manhole.")
            log.warning(f"Non-whitelisted user {username} tried to connect from PID {pid}")
            await writer.drain()
            writer.close()
            return

        namespace = {**self.namespace}
        if AWAIT_TRANSFORM:
            namespace[AWAIT_FUNC_NAME] = AWAIT_FALLBACK
        interpreter = self.interpreter_class(namespace=namespace, banner=self.banner,
                                             loop=self.loop)
        namespace["exit"] = interpreter.close
        self.clients.append(interpreter)
        conn_id = self.conn_id

        log.info(f"Manhole connection OPENED: {conn_id} from PID {pid} by {username}")
        await asyncio.ensure_future(interpreter(reader, writer))
        log.info(f"Manhole connection CLOSED: {conn_id} from PID {pid} by {username}")
        self.clients.remove(interpreter) 
Example #3
Source File: manhole.py    From mautrix-python with Mozilla Public License 2.0 5 votes vote down vote up
def start_manhole(path: str, banner: str = "", namespace: Optional[Dict[str, Any]] = None,
                        loop: asyncio.AbstractEventLoop = None, whitelist: Set[int] = None,
                        ) -> Tuple[asyncio.AbstractServer, Callable[[], None]]:
    """
    Starts a manhole server on a given UNIX address.

    Args:
        path: The path to create the UNIX socket at.
        banner: The banner to show when clients connect.
        namespace: The globals to provide to connected clients.
        loop: The asyncio event loop to use.
        whitelist: List of user IDs to allow connecting.
    """
    if not SO_PEERCRED:
        raise ValueError("SO_PEERCRED is not supported on this platform")
    loop = loop or asyncio.get_event_loop()
    factory = InterpreterFactory(namespace=namespace, banner=banner,
                                 interpreter_class=AsyncInterpreter, loop=loop,
                                 whitelist=whitelist)
    server = await asyncio.start_unix_server(factory, path=path, loop=loop)
    os.chmod(path, 0o666)

    def stop():
        for client in factory.clients:
            client.close()
        server.close()

    return server, stop 
Example #4
Source File: cgroup.py    From jd4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def accept(self, sock):
        loop = get_event_loop()
        accept_sock, _ = await loop.sock_accept(sock)
        pid = accept_sock.getsockopt(SOL_SOCKET, SO_PEERCRED)
        write_text_file(path.join(self.cpuacct_cgroup_dir, 'tasks'), str(pid))
        write_text_file(path.join(self.memory_cgroup_dir, 'tasks'), str(pid))
        write_text_file(path.join(self.pids_cgroup_dir, 'tasks'), str(pid))
        accept_sock.close() 
Example #5
Source File: server.py    From cheroot with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_peer_creds(self):  # LRU cached on per-instance basis, see __init__
        """Return the PID/UID/GID tuple of the peer socket for UNIX sockets.

        This function uses SO_PEERCRED to query the UNIX PID, UID, GID
        of the peer, which is only available if the bind address is
        a UNIX domain socket.

        Raises:
            NotImplementedError: in case of unsupported socket type
            RuntimeError: in case of SO_PEERCRED lookup unsupported or disabled

        """
        PEERCRED_STRUCT_DEF = '3i'

        if IS_WINDOWS or self.socket.family != socket.AF_UNIX:
            raise NotImplementedError(
                'SO_PEERCRED is only supported in Linux kernel and WSL',
            )
        elif not self.peercreds_enabled:
            raise RuntimeError(
                'Peer creds lookup is disabled within this server',
            )

        try:
            peer_creds = self.socket.getsockopt(
                # FIXME: Use LOCAL_CREDS for BSD-like OSs
                # Ref: https://gist.github.com/LucaFilipozzi/e4f1e118202aff27af6aadebda1b5d91  # noqa
                socket.SOL_SOCKET, socket.SO_PEERCRED,
                struct.calcsize(PEERCRED_STRUCT_DEF),
            )
        except socket.error as socket_err:
            """Non-Linux kernels don't support SO_PEERCRED.

            Refs:
            http://welz.org.za/notes/on-peer-cred.html
            https://github.com/daveti/tcpSockHack
            msdn.microsoft.com/en-us/commandline/wsl/release_notes#build-15025
            """
            six.raise_from(  # 3.6+: raise RuntimeError from socket_err
                RuntimeError,
                socket_err,
            )
        else:
            pid, uid, gid = struct.unpack(PEERCRED_STRUCT_DEF, peer_creds)
            return pid, uid, gid 
Example #6
Source File: server.py    From Tautulli with GNU General Public License v3.0 4 votes vote down vote up
def get_peer_creds(self):  # LRU cached on per-instance basis, see __init__
        """Return the PID/UID/GID tuple of the peer socket for UNIX sockets.

        This function uses SO_PEERCRED to query the UNIX PID, UID, GID
        of the peer, which is only available if the bind address is
        a UNIX domain socket.

        Raises:
            NotImplementedError: in case of unsupported socket type
            RuntimeError: in case of SO_PEERCRED lookup unsupported or disabled

        """
        PEERCRED_STRUCT_DEF = '3i'

        if IS_WINDOWS or self.socket.family != socket.AF_UNIX:
            raise NotImplementedError(
                'SO_PEERCRED is only supported in Linux kernel and WSL',
            )
        elif not self.peercreds_enabled:
            raise RuntimeError(
                'Peer creds lookup is disabled within this server',
            )

        try:
            peer_creds = self.socket.getsockopt(
                # FIXME: Use LOCAL_CREDS for BSD-like OSs
                # Ref: https://gist.github.com/LucaFilipozzi/e4f1e118202aff27af6aadebda1b5d91  # noqa
                socket.SOL_SOCKET, socket.SO_PEERCRED,
                struct.calcsize(PEERCRED_STRUCT_DEF),
            )
        except socket.error as socket_err:
            """Non-Linux kernels don't support SO_PEERCRED.

            Refs:
            http://welz.org.za/notes/on-peer-cred.html
            https://github.com/daveti/tcpSockHack
            msdn.microsoft.com/en-us/commandline/wsl/release_notes#build-15025
            """
            six.raise_from(  # 3.6+: raise RuntimeError from socket_err
                RuntimeError,
                socket_err,
            )
        else:
            pid, uid, gid = struct.unpack(PEERCRED_STRUCT_DEF, peer_creds)
            return pid, uid, gid