xcb_auth.c revision 1c7386f4
1/* Copyright (C) 2001-2004 Bart Massey and Jamey Sharp.
2 *
3 * Permission is hereby granted, free of charge, to any person obtaining a
4 * copy of this software and associated documentation files (the "Software"),
5 * to deal in the Software without restriction, including without limitation
6 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 * and/or sell copies of the Software, and to permit persons to whom the
8 * Software is furnished to do so, subject to the following conditions:
9 *
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 * AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
17 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 *
20 * Except as contained in this notice, the names of the authors or their
21 * institutions shall not be used in advertising or otherwise to promote the
22 * sale, use or other dealings in this Software without prior written
23 * authorization from the authors.
24 */
25
26/* Authorization systems for the X protocol. */
27
28#ifdef HAVE_CONFIG_H
29#include "config.h"
30#endif
31
32#include <assert.h>
33#include <X11/Xauth.h>
34#include <sys/param.h>
35#include <unistd.h>
36#include <stdlib.h>
37
38#ifdef __INTERIX
39/* _don't_ ask. interix has INADDR_LOOPBACK in here. */
40#include <rpc/types.h>
41#endif
42
43#ifdef _WIN32
44#ifdef HASXDMAUTH
45/* We must include the wrapped windows.h before any system header which includes
46   it unwrapped, to avoid conflicts with types defined in X headers */
47#include <X11/Xwindows.h>
48#endif
49#include "xcb_windefs.h"
50#else
51#include <arpa/inet.h>
52#include <sys/socket.h>
53#include <netinet/in.h>
54#include <sys/un.h>
55#endif /* _WIN32 */
56
57#include "xcb.h"
58#include "xcbint.h"
59
60#ifdef HASXDMAUTH
61#include <X11/Xdmcp.h>
62#endif
63
64enum auth_protos {
65#ifdef HASXDMAUTH
66    AUTH_XA1,
67#endif
68    AUTH_MC1,
69    N_AUTH_PROTOS
70};
71
72#define AUTH_PROTO_XDM_AUTHORIZATION "XDM-AUTHORIZATION-1"
73#define AUTH_PROTO_MIT_MAGIC_COOKIE "MIT-MAGIC-COOKIE-1"
74
75static char *authnames[N_AUTH_PROTOS] = {
76#ifdef HASXDMAUTH
77    AUTH_PROTO_XDM_AUTHORIZATION,
78#endif
79    AUTH_PROTO_MIT_MAGIC_COOKIE,
80};
81
82static int authnameslen[N_AUTH_PROTOS] = {
83#ifdef HASXDMAUTH
84    sizeof(AUTH_PROTO_XDM_AUTHORIZATION) - 1,
85#endif
86    sizeof(AUTH_PROTO_MIT_MAGIC_COOKIE) - 1,
87};
88
89static size_t memdup(char **dst, void *src, size_t len)
90{
91    if(len)
92        *dst = malloc(len);
93    else
94        *dst = 0;
95    if(!*dst)
96        return 0;
97    memcpy(*dst, src, len);
98    return len;
99}
100
101static int authname_match(enum auth_protos kind, char *name, size_t namelen)
102{
103    if(authnameslen[kind] != namelen)
104        return 0;
105    if(memcmp(authnames[kind], name, namelen))
106        return 0;
107    return 1;
108}
109
110#define SIN6_ADDR(s) (&((struct sockaddr_in6 *)s)->sin6_addr)
111
112static Xauth *get_authptr(struct sockaddr *sockname, int display)
113{
114    char *addr = 0;
115    int addrlen = 0;
116    unsigned short family;
117    char hostnamebuf[256];   /* big enough for max hostname */
118    char dispbuf[40];   /* big enough to hold more than 2^64 base 10 */
119    int dispbuflen;
120
121    family = FamilyLocal; /* 256 */
122    switch(sockname->sa_family)
123    {
124#ifdef AF_INET6
125    case AF_INET6:
126        addr = (char *) SIN6_ADDR(sockname);
127        addrlen = sizeof(*SIN6_ADDR(sockname));
128        if(!IN6_IS_ADDR_V4MAPPED(SIN6_ADDR(sockname)))
129        {
130            if(!IN6_IS_ADDR_LOOPBACK(SIN6_ADDR(sockname)))
131                family = XCB_FAMILY_INTERNET_6;
132            break;
133        }
134        addr += 12;
135        /* if v4-mapped, fall through. */
136#endif
137    case AF_INET:
138        if(!addr)
139            addr = (char *) &((struct sockaddr_in *)sockname)->sin_addr;
140        addrlen = sizeof(((struct sockaddr_in *)sockname)->sin_addr);
141        if(*(in_addr_t *) addr != htonl(INADDR_LOOPBACK))
142            family = XCB_FAMILY_INTERNET;
143        break;
144    case AF_UNIX:
145        break;
146    default:
147        return 0;   /* cannot authenticate this family */
148    }
149
150    dispbuflen = snprintf(dispbuf, sizeof(dispbuf), "%d", display);
151    if(dispbuflen < 0)
152        return 0;
153    /* snprintf may have truncate our text */
154    dispbuflen = MIN(dispbuflen, sizeof(dispbuf) - 1);
155
156    if (family == FamilyLocal) {
157        if (gethostname(hostnamebuf, sizeof(hostnamebuf)) == -1)
158            return 0;   /* do not know own hostname */
159        addr = hostnamebuf;
160        addrlen = strlen(addr);
161    }
162
163    return XauGetBestAuthByAddr (family,
164                                 (unsigned short) addrlen, addr,
165                                 (unsigned short) dispbuflen, dispbuf,
166                                 N_AUTH_PROTOS, authnames, authnameslen);
167}
168
169#ifdef HASXDMAUTH
170static int next_nonce(void)
171{
172    static int nonce = 0;
173    static pthread_mutex_t nonce_mutex = PTHREAD_MUTEX_INITIALIZER;
174    int ret;
175    pthread_mutex_lock(&nonce_mutex);
176    ret = nonce++;
177    pthread_mutex_unlock(&nonce_mutex);
178    return ret;
179}
180
181static void do_append(char *buf, int *idxp, void *val, size_t valsize) {
182    memcpy(buf + *idxp, val, valsize);
183    *idxp += valsize;
184}
185#endif
186
187static int compute_auth(xcb_auth_info_t *info, Xauth *authptr, struct sockaddr *sockname)
188{
189    if (authname_match(AUTH_MC1, authptr->name, authptr->name_length)) {
190        info->datalen = memdup(&info->data, authptr->data, authptr->data_length);
191        if(!info->datalen)
192            return 0;
193        return 1;
194    }
195#ifdef HASXDMAUTH
196#define APPEND(buf,idx,val) do_append((buf),&(idx),&(val),sizeof(val))
197    if (authname_match(AUTH_XA1, authptr->name, authptr->name_length)) {
198        int j;
199
200        info->data = malloc(192 / 8);
201        if(!info->data)
202            return 0;
203
204        for (j = 0; j < 8; j++)
205            info->data[j] = authptr->data[j];
206        switch(sockname->sa_family) {
207        case AF_INET:
208            /*block*/ {
209            struct sockaddr_in *si = (struct sockaddr_in *) sockname;
210            APPEND(info->data, j, si->sin_addr.s_addr);
211            APPEND(info->data, j, si->sin_port);
212        }
213        break;
214#ifdef AF_INET6
215        case AF_INET6:
216            /*block*/ {
217            struct sockaddr_in6 *si6 = (struct sockaddr_in6 *) sockname;
218            if(IN6_IS_ADDR_V4MAPPED(SIN6_ADDR(sockname)))
219            {
220                do_append(info->data, &j, &si6->sin6_addr.s6_addr[12], 4);
221                APPEND(info->data, j, si6->sin6_port);
222            }
223            else
224            {
225                /* XDM-AUTHORIZATION-1 does not handle IPv6 correctly.  Do the
226                   same thing Xlib does: use all zeroes for the 4-byte address
227                   and 2-byte port number. */
228                uint32_t fakeaddr = 0;
229                uint16_t fakeport = 0;
230                APPEND(info->data, j, fakeaddr);
231                APPEND(info->data, j, fakeport);
232            }
233        }
234        break;
235#endif
236        case AF_UNIX:
237            /*block*/ {
238            uint32_t fakeaddr = htonl(0xffffffff - next_nonce());
239            uint16_t fakeport = htons(getpid());
240            APPEND(info->data, j, fakeaddr);
241            APPEND(info->data, j, fakeport);
242        }
243        break;
244        default:
245            free(info->data);
246            return 0;   /* do not know how to build this */
247        }
248        {
249            uint32_t now = htonl(time(0));
250            APPEND(info->data, j, now);
251        }
252        assert(j <= 192 / 8);
253        while (j < 192 / 8)
254            info->data[j++] = 0;
255        info->datalen = j;
256        XdmcpWrap ((unsigned char *) info->data, (unsigned char *) authptr->data + 8, (unsigned char *) info->data, info->datalen);
257        return 1;
258    }
259#undef APPEND
260#endif
261
262    return 0;   /* Unknown authorization type */
263}
264
265/* `sockaddr_un.sun_path' typical size usually ranges between 92 and 108 */
266#define INITIAL_SOCKNAME_SLACK 108
267
268/* Return a dynamically allocated socket address structure according
269   to the value returned by either getpeername() or getsockname()
270   (according to POSIX, applications should not assume a particular
271   length for `sockaddr_un.sun_path') */
272static struct sockaddr *get_peer_sock_name(int (*socket_func)(int,
273                                                              struct sockaddr *,
274                                                              socklen_t *),
275                                           int fd)
276{
277    socklen_t socknamelen = sizeof(struct sockaddr) + INITIAL_SOCKNAME_SLACK;
278    socklen_t actual_socknamelen = socknamelen;
279    struct sockaddr *sockname = malloc(socknamelen);
280
281    if (sockname == NULL)
282        return NULL;
283
284    /* Both getpeername() and getsockname() truncates sockname if
285       there is not enough space and set the required length in
286       actual_socknamelen */
287    if (socket_func(fd, sockname, &actual_socknamelen) == -1)
288        goto sock_or_realloc_error;
289
290    if (actual_socknamelen > socknamelen)
291    {
292        struct sockaddr *new_sockname = NULL;
293        socknamelen = actual_socknamelen;
294
295        if ((new_sockname = realloc(sockname, actual_socknamelen)) == NULL)
296            goto sock_or_realloc_error;
297
298        sockname = new_sockname;
299
300        if (socket_func(fd, sockname, &actual_socknamelen) == -1 ||
301            actual_socknamelen > socknamelen)
302            goto sock_or_realloc_error;
303    }
304
305    return sockname;
306
307 sock_or_realloc_error:
308    free(sockname);
309    return NULL;
310}
311
312int _xcb_get_auth_info(int fd, xcb_auth_info_t *info, int display)
313{
314    /* code adapted from Xlib/ConnDis.c, xtrans/Xtranssocket.c,
315       xtrans/Xtransutils.c */
316    struct sockaddr *sockname = NULL;
317    int gotsockname = 0;
318    Xauth *authptr = 0;
319    int ret = 1;
320
321    /* Some systems like hpux or Hurd do not expose peer names
322     * for UNIX Domain Sockets, but this is irrelevant,
323     * since compute_auth() ignores the peer name in this
324     * case anyway.*/
325    if ((sockname = get_peer_sock_name(getpeername, fd)) == NULL)
326    {
327        if ((sockname = get_peer_sock_name(getsockname, fd)) == NULL)
328            return 0;   /* can only authenticate sockets */
329        if (sockname->sa_family != AF_UNIX)
330        {
331            free(sockname);
332            return 0;   /* except for AF_UNIX, sockets should have peernames */
333        }
334        gotsockname = 1;
335    }
336
337    authptr = get_authptr(sockname, display);
338    if (authptr == 0)
339    {
340        free(sockname);
341        return 0;   /* cannot find good auth data */
342    }
343
344    info->namelen = memdup(&info->name, authptr->name, authptr->name_length);
345    if (!info->namelen)
346        goto no_auth;   /* out of memory */
347
348    if (!gotsockname)
349    {
350        free(sockname);
351
352        if ((sockname = get_peer_sock_name(getsockname, fd)) == NULL)
353        {
354            free(info->name);
355            goto no_auth;   /* can only authenticate sockets */
356        }
357    }
358
359    ret = compute_auth(info, authptr, sockname);
360    if(!ret)
361    {
362        free(info->name);
363        goto no_auth;   /* cannot build auth record */
364    }
365
366    free(sockname);
367    sockname = NULL;
368
369    XauDisposeAuth(authptr);
370    return ret;
371
372 no_auth:
373    free(sockname);
374
375    info->name = 0;
376    info->namelen = 0;
377    XauDisposeAuth(authptr);
378    return 0;
379}
380