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