有没有办法获取unix套接字连接另一端的uid [英] Is there a way to get the uid of the other end of a unix socket connection

查看:182
本文介绍了有没有办法获取unix套接字连接另一端的uid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法使UNIX域套接字侦听器仅接受来自特定用户的连接(chmod/chown对于抽象套接字afaik不起作用),或者换句话说,获取传入连接的uid(在Linux上)?

Is there a way for a UNIX domain socket listener to only accept connection from certain user (chmod/chown does not work for abstract socket afaik), or in another word, get the uid of the incoming connection (on Linux)?

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

Dbus, which uses abstract unix socket on Linux, has a function GetConnectionUnixUser which is used by polkit to determine the caller. So I suppose the dbus-daemon must have a way to do that. Does anyone know how that works?

推荐答案

检查对等凭据的最简单方法是使用

The easiest way to check peer credentials is with SO_PEERCRED. To do this for socket 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 有一些其他unices的变种.

From a tlpi example. PostgreSQL has a few variants for other unices.

这篇关于有没有办法获取unix套接字连接另一端的uid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆