有没有办法获取unix套接字连接另一端的uid

yuy*_*hao 6 sockets linux dbus unix-socket uid

有没有办法让UNIX域套接字侦听器只接受来自某个用户的连接(chmod/ chown不适用于抽象套接字afaik),换句话说,获取传入连接的uid(在Linux上)?

在Linux上使用抽象unix套接字的Dbus有一个GetConnectionUnixUser由polkit用来确定调用者的函数.所以我想dbus-daemon必须有办法做到这一点.有谁知道它是如何工作的?

Gab*_*iel 9

检查对等凭据的最简单方法是使用SO_PEERCRED.要为套接字执行此操作sock:

int len;
struct ucred ucred;

len = sizeof(struct ucred);
if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == -1)
    // check errno

printf("Credentials from SO_PEERCRED: pid=%ld, euid=%ld, egid=%ld\n",
        (long) ucred.pid, (long) ucred.uid, (long) ucred.gid);
Run Code Online (Sandbox Code Playgroud)
SO_PEERCRED
          Return the credentials of the foreign process connected to
          this socket.  This is possible only for connected AF_UNIX
          stream sockets and AF_UNIX stream and datagram socket pairs
          created using socketpair(2); see unix(7).  The returned
          credentials are those that were in effect at the time of the
          call to connect(2) or socketpair(2).  The argument is a ucred
          structure; define the _GNU_SOURCE feature test macro to obtain
          the definition of that structure from <sys/socket.h>.  This
          socket option is read-only.
Run Code Online (Sandbox Code Playgroud)

从一个tlpi的 例子. PostgreSQL有一些其他unices的变种.