10

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, 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?

2 Answers 2

11

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.

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

2
  • Actually this seems to be what I end up using although I didn't notice the difference between them until now. :P
    – yuyichao
    Sep 23, 2013 at 18:02
  • It also might be worth mentioning that some Linux systems require you to #define _GNU_SOURCE before you <include ...> any of the header files in order to get struct ucred defined.
    – mormegil
    Oct 14, 2013 at 23:18
4

Yes -- this operation, along with FD passing, is supported via an ancilliary message with the SCM_CREDENTIALS type. The calls involved are documented in man 7 unix.

3
  • So by using SCM_CREDENTIALS the message is checked by the kernel, but it still require the client to send the message. Is there a way to do this on server side only?
    – yuyichao
    Mar 28, 2012 at 0:41
  • No; as far as I know, there's no way to get credentials without the other end sending them.
    – user149341
    Mar 28, 2012 at 3:55
  • I C. Probably can check /proc/pid/fd (like what lsof does) if really need that ~~
    – yuyichao
    Mar 28, 2012 at 21:08

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.