2012-03-27 88 views
4

有沒有辦法讓UNIX域套接字偵聽器只接受來自某個用戶的連接(chmod/chown不適用於抽象套接字afaik),或換句話說,獲取傳入連接的uid(在Linux上)?有沒有辦法獲得unix套接字連接的另一端的uid

Dbus在Linux上使用抽象的unix套接字,它有一個函數GetConnectionUnixUser,polkit用它來確定調用者。所以我想dbus-daemon必須有辦法做到這一點。有誰知道這是如何工作的?

回答

5

檢查對等憑證的最簡單方法是使用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有其他unices幾個變種。

+0

其實這似乎是我最終使用的,儘管直到現在我沒有注意到它們之間的區別。 :P – yuyichao 2013-09-23 18:02:58

+0

也可能值得一提的是,有些Linux系統要求你在''之前'定義_GNU_SOURCE',以便定義'struct ucred'。 – mormegil 2013-10-14 23:18:19

4

是 - 該操作與FD傳遞一起通過類型爲SCM_CREDENTIALS的輔助消息來支持。涉及的電話記錄在man 7 unix

+0

THX非常多。 = D – yuyichao 2012-03-28 00:14:28

+0

所以通過使用'SCM_CREDENTIALS'消息由內核檢查,但它仍然需要客戶端發送消息。有沒有辦法在服務器端做到這一點? – yuyichao 2012-03-28 00:41:21

+0

否;據我所知,如果沒有另一端發送證書,就無法獲得憑證。 – duskwuff 2012-03-28 03:55:23

相關問題