Is there a way to get the uid of the other end of a unix socket connection

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

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

+4
source share
2 answers

The easiest way to verify credentials is 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. 

From tlpi example . PostgreSQL has several options for other nodes.

+6
source

Yes - this operation together with the FD transmission is supported through an auxiliary message of type SCM_CREDENTIALS . Accepted calls are documented in man 7 unix .

+4
source

Source: https://habr.com/ru/post/1403772/


All Articles