10

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

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

4

2 回答 2

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);
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.

来自tlpi 示例PostgreSQL有一些其他版本的变体。

于 2013-09-22T16:57:50.950 回答
4

是的——这个操作,连同 FD 传递,是通过带有SCM_CREDENTIALS类型的辅助消息来支持的。所涉及的调用记录在man 7 unix.

于 2012-03-27T23:27:17.330 回答