【问题标题】:Is there a way to get the uid of the other end of a unix socket connection有没有办法获取unix套接字连接另一端的uid
【发布时间】:2012-04-11 12:58:29
【问题描述】:

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

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

【问题讨论】:

    标签: linux sockets dbus uid unix-socket


    【解决方案1】:

    检查对等凭据的最简单方法是使用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.
    

    来自tlpiexamplePostgreSQL 有一些其他版本的变体。

    【讨论】:

    • 实际上这似乎是我最终使用的,尽管直到现在我才注意到它们之间的区别。 :P
    • 还可能值得一提的是,某些 Linux 系统要求您在 &lt;include ...&gt; 任何头文件之前先 #define _GNU_SOURCE 才能定义 struct ucred
    【解决方案2】:

    是的——该操作以及 FD 传递通过 SCM_CREDENTIALS 类型的辅助消息得到支持。所涉及的调用记录在man 7 unix

    【讨论】:

    • 所以通过使用SCM_CREDENTIALS,内核会检查消息,但仍然需要客户端发送消息。有没有办法只在服务器端做到这一点?
    • 否;据我所知,如果没有另一端发送凭据,就无法获得凭据。
    • I C. 如果真的需要,可能可以检查 /proc/pid/fd(就像 lsof 所做的那样)~~
    猜你喜欢
    • 2012-08-07
    • 2017-04-27
    • 2018-02-23
    • 2021-08-25
    • 2017-06-24
    • 2014-11-19
    • 2010-10-25
    • 2015-02-08
    • 1970-01-01
    相关资源
    最近更新 更多