1 /*
2  * Platform-independent bits of X11 forwarding.
3  */
4 
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8 #include <time.h>
9 
10 #include "putty.h"
11 #include "ssh.h"
12 #include "sshchan.h"
13 #include "tree234.h"
14 
GET_16BIT_X11(char endian,const void * p)15 static inline uint16_t GET_16BIT_X11(char endian, const void *p)
16 {
17     return endian == 'B' ? GET_16BIT_MSB_FIRST(p) : GET_16BIT_LSB_FIRST(p);
18 }
19 
PUT_16BIT_X11(char endian,void * p,uint16_t value)20 static inline void PUT_16BIT_X11(char endian, void *p, uint16_t value)
21 {
22     if (endian == 'B')
23         PUT_16BIT_MSB_FIRST(p, value);
24     else
25         PUT_16BIT_LSB_FIRST(p, value);
26 }
27 
28 const char *const x11_authnames[] = {
29     "", "MIT-MAGIC-COOKIE-1", "XDM-AUTHORIZATION-1"
30 };
31 
32 struct XDMSeen {
33     unsigned int time;
34     unsigned char clientid[6];
35 };
36 
37 typedef struct X11Connection {
38     unsigned char firstpkt[12];        /* first X data packet */
39     tree234 *authtree;
40     struct X11Display *disp;
41     char *auth_protocol;
42     unsigned char *auth_data;
43     int data_read, auth_plen, auth_psize, auth_dlen, auth_dsize;
44     bool verified;
45     bool input_wanted;
46     bool no_data_sent_to_x_client;
47     char *peer_addr;
48     int peer_port;
49     SshChannel *c;               /* channel structure held by SSH backend */
50     Socket *s;
51 
52     Plug plug;
53     Channel chan;
54 } X11Connection;
55 
xdmseen_cmp(void * a,void * b)56 static int xdmseen_cmp(void *a, void *b)
57 {
58     struct XDMSeen *sa = a, *sb = b;
59     return sa->time > sb->time ? 1 :
60            sa->time < sb->time ? -1 :
61            memcmp(sa->clientid, sb->clientid, sizeof(sa->clientid));
62 }
63 
x11_invent_fake_auth(tree234 * authtree,int authtype)64 struct X11FakeAuth *x11_invent_fake_auth(tree234 *authtree, int authtype)
65 {
66     struct X11FakeAuth *auth = snew(struct X11FakeAuth);
67     int i;
68 
69     /*
70      * This function has the job of inventing a set of X11 fake auth
71      * data, and adding it to 'authtree'. We must preserve the
72      * property that for any given actual authorisation attempt, _at
73      * most one_ thing in the tree can possibly match it.
74      *
75      * For MIT-MAGIC-COOKIE-1, that's not too difficult: the match
76      * criterion is simply that the entire cookie is correct, so we
77      * just have to make sure we don't make up two cookies the same.
78      * (Vanishingly unlikely, but we check anyway to be sure, and go
79      * round again inventing a new cookie if add234 tells us the one
80      * we thought of is already in use.)
81      *
82      * For XDM-AUTHORIZATION-1, it's a little more fiddly. The setup
83      * with XA1 is that half the cookie is used as a DES key with
84      * which to CBC-encrypt an assortment of stuff. Happily, the stuff
85      * encrypted _begins_ with the other half of the cookie, and the
86      * IV is always zero, which means that any valid XA1 authorisation
87      * attempt for a given cookie must begin with the same cipher
88      * block, consisting of the DES ECB encryption of the first half
89      * of the cookie using the second half as a key. So we compute
90      * that cipher block here and now, and use it as the sorting key
91      * for distinguishing XA1 entries in the tree.
92      */
93 
94     if (authtype == X11_MIT) {
95         auth->proto = X11_MIT;
96 
97         /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */
98         auth->datalen = 16;
99         auth->data = snewn(auth->datalen, unsigned char);
100         auth->xa1_firstblock = NULL;
101 
102         while (1) {
103             random_read(auth->data, auth->datalen);
104             if (add234(authtree, auth) == auth)
105                 break;
106         }
107 
108         auth->xdmseen = NULL;
109     } else {
110         assert(authtype == X11_XDM);
111         auth->proto = X11_XDM;
112 
113         /* XDM-AUTHORIZATION-1. Cookie size is 16 bytes; byte 8 is zero. */
114         auth->datalen = 16;
115         auth->data = snewn(auth->datalen, unsigned char);
116         auth->xa1_firstblock = snewn(8, unsigned char);
117         memset(auth->xa1_firstblock, 0, 8);
118 
119         while (1) {
120             random_read(auth->data, 15);
121             auth->data[15] = auth->data[8];
122             auth->data[8] = 0;
123 
124             memcpy(auth->xa1_firstblock, auth->data, 8);
125             des_encrypt_xdmauth(auth->data + 9, auth->xa1_firstblock, 8);
126             if (add234(authtree, auth) == auth)
127                 break;
128         }
129 
130         auth->xdmseen = newtree234(xdmseen_cmp);
131     }
132     auth->protoname = dupstr(x11_authnames[auth->proto]);
133     auth->datastring = snewn(auth->datalen * 2 + 1, char);
134     for (i = 0; i < auth->datalen; i++)
135         sprintf(auth->datastring + i*2, "%02x",
136                 auth->data[i]);
137 
138     auth->disp = NULL;
139     auth->share_cs = NULL;
140     auth->share_chan = NULL;
141 
142     return auth;
143 }
144 
x11_free_fake_auth(struct X11FakeAuth * auth)145 void x11_free_fake_auth(struct X11FakeAuth *auth)
146 {
147     if (auth->data)
148         smemclr(auth->data, auth->datalen);
149     sfree(auth->data);
150     sfree(auth->protoname);
151     sfree(auth->datastring);
152     sfree(auth->xa1_firstblock);
153     if (auth->xdmseen != NULL) {
154         struct XDMSeen *seen;
155         while ((seen = delpos234(auth->xdmseen, 0)) != NULL)
156             sfree(seen);
157         freetree234(auth->xdmseen);
158     }
159     sfree(auth);
160 }
161 
x11_authcmp(void * av,void * bv)162 int x11_authcmp(void *av, void *bv)
163 {
164     struct X11FakeAuth *a = (struct X11FakeAuth *)av;
165     struct X11FakeAuth *b = (struct X11FakeAuth *)bv;
166 
167     if (a->proto < b->proto)
168         return -1;
169     else if (a->proto > b->proto)
170         return +1;
171 
172     if (a->proto == X11_MIT) {
173         if (a->datalen < b->datalen)
174             return -1;
175         else if (a->datalen > b->datalen)
176             return +1;
177 
178         return memcmp(a->data, b->data, a->datalen);
179     } else {
180         assert(a->proto == X11_XDM);
181 
182         return memcmp(a->xa1_firstblock, b->xa1_firstblock, 8);
183     }
184 }
185 
x11_setup_display(const char * display,Conf * conf,char ** error_msg)186 struct X11Display *x11_setup_display(const char *display, Conf *conf,
187                                      char **error_msg)
188 {
189     struct X11Display *disp = snew(struct X11Display);
190     char *localcopy;
191 
192     *error_msg = NULL;
193 
194     if (!display || !*display) {
195         localcopy = platform_get_x_display();
196         if (!localcopy || !*localcopy) {
197             sfree(localcopy);
198             localcopy = dupstr(":0");  /* plausible default for any platform */
199         }
200     } else
201         localcopy = dupstr(display);
202 
203     /*
204      * Parse the display name.
205      *
206      * We expect this to have one of the following forms:
207      *
208      *  - the standard X format which looks like
209      *    [ [ protocol '/' ] host ] ':' displaynumber [ '.' screennumber ]
210      *    (X11 also permits a double colon to indicate DECnet, but
211      *    that's not our problem, thankfully!)
212      *
213      *  - only seen in the wild on MacOS (so far): a pathname to a
214      *    Unix-domain socket, which will typically and confusingly
215      *    end in ":0", and which I'm currently distinguishing from
216      *    the standard scheme by noting that it starts with '/'.
217      */
218     if (localcopy[0] == '/') {
219         disp->unixsocketpath = localcopy;
220         disp->unixdomain = true;
221         disp->hostname = NULL;
222         disp->displaynum = -1;
223         disp->screennum = 0;
224         disp->addr = NULL;
225     } else {
226         char *colon, *dot, *slash;
227         char *protocol, *hostname;
228 
229         colon = host_strrchr(localcopy, ':');
230         if (!colon) {
231             *error_msg = dupprintf("display name '%s' has no ':number'"
232                                    " suffix", localcopy);
233 
234             sfree(disp);
235             sfree(localcopy);
236             return NULL;
237         }
238 
239         *colon++ = '\0';
240         dot = strchr(colon, '.');
241         if (dot)
242             *dot++ = '\0';
243 
244         disp->displaynum = atoi(colon);
245         if (dot)
246             disp->screennum = atoi(dot);
247         else
248             disp->screennum = 0;
249 
250         protocol = NULL;
251         hostname = localcopy;
252         if (colon > localcopy) {
253             slash = strchr(localcopy, '/');
254             if (slash) {
255                 *slash++ = '\0';
256                 protocol = localcopy;
257                 hostname = slash;
258             }
259         }
260 
261         disp->hostname = *hostname ? dupstr(hostname) : NULL;
262 
263         if (protocol)
264             disp->unixdomain = (!strcmp(protocol, "local") ||
265                                 !strcmp(protocol, "unix"));
266         else if (!*hostname || !strcmp(hostname, "unix"))
267             disp->unixdomain = platform_uses_x11_unix_by_default;
268         else
269             disp->unixdomain = false;
270 
271         if (!disp->hostname && !disp->unixdomain)
272             disp->hostname = dupstr("localhost");
273 
274         disp->unixsocketpath = NULL;
275         disp->addr = NULL;
276 
277         sfree(localcopy);
278     }
279 
280     /*
281      * Look up the display hostname, if we need to.
282      */
283     if (!disp->unixdomain) {
284         const char *err;
285 
286         disp->port = 6000 + disp->displaynum;
287         disp->addr = name_lookup(disp->hostname, disp->port,
288                                  &disp->realhost, conf, ADDRTYPE_UNSPEC,
289                                  NULL, NULL);
290 
291         if ((err = sk_addr_error(disp->addr)) != NULL) {
292             *error_msg = dupprintf("unable to resolve host name '%s' in "
293                                    "display name", disp->hostname);
294 
295             sk_addr_free(disp->addr);
296             sfree(disp->hostname);
297             sfree(disp->unixsocketpath);
298             sfree(disp);
299             return NULL;
300         }
301     }
302 
303     /*
304      * Try upgrading an IP-style localhost display to a Unix-socket
305      * display (as the standard X connection libraries do).
306      */
307     if (!disp->unixdomain && sk_address_is_local(disp->addr)) {
308         SockAddr *ux = platform_get_x11_unix_address(NULL, disp->displaynum);
309         const char *err = sk_addr_error(ux);
310         if (!err) {
311             /* Create trial connection to see if there is a useful Unix-domain
312              * socket */
313             Socket *s = sk_new(sk_addr_dup(ux), 0, false, false,
314                                false, false, nullplug);
315             err = sk_socket_error(s);
316             sk_close(s);
317         }
318         if (err) {
319             sk_addr_free(ux);
320         } else {
321             sk_addr_free(disp->addr);
322             disp->unixdomain = true;
323             disp->addr = ux;
324             /* Fill in the rest in a moment */
325         }
326     }
327 
328     if (disp->unixdomain) {
329         if (!disp->addr)
330             disp->addr = platform_get_x11_unix_address(disp->unixsocketpath,
331                                                        disp->displaynum);
332         if (disp->unixsocketpath)
333             disp->realhost = dupstr(disp->unixsocketpath);
334         else
335             disp->realhost = dupprintf("unix:%d", disp->displaynum);
336         disp->port = 0;
337     }
338 
339     /*
340      * Fetch the local authorisation details.
341      */
342     disp->localauthproto = X11_NO_AUTH;
343     disp->localauthdata = NULL;
344     disp->localauthdatalen = 0;
345     platform_get_x11_auth(disp, conf);
346 
347     return disp;
348 }
349 
x11_free_display(struct X11Display * disp)350 void x11_free_display(struct X11Display *disp)
351 {
352     sfree(disp->hostname);
353     sfree(disp->unixsocketpath);
354     if (disp->localauthdata)
355         smemclr(disp->localauthdata, disp->localauthdatalen);
356     sfree(disp->localauthdata);
357     sk_addr_free(disp->addr);
358     sfree(disp);
359 }
360 
361 #define XDM_MAXSKEW 20*60      /* 20 minute clock skew should be OK */
362 
x11_verify(unsigned long peer_ip,int peer_port,tree234 * authtree,char * proto,unsigned char * data,int dlen,struct X11FakeAuth ** auth_ret)363 static const char *x11_verify(unsigned long peer_ip, int peer_port,
364                               tree234 *authtree, char *proto,
365                               unsigned char *data, int dlen,
366                               struct X11FakeAuth **auth_ret)
367 {
368     struct X11FakeAuth match_dummy;    /* for passing to find234 */
369     struct X11FakeAuth *auth;
370 
371     /*
372      * First, do a lookup in our tree to find the only authorisation
373      * record that _might_ match.
374      */
375     if (!strcmp(proto, x11_authnames[X11_MIT])) {
376         /*
377          * Just look up the whole cookie that was presented to us,
378          * which x11_authcmp will compare against the cookies we
379          * currently believe in.
380          */
381         match_dummy.proto = X11_MIT;
382         match_dummy.datalen = dlen;
383         match_dummy.data = data;
384     } else if (!strcmp(proto, x11_authnames[X11_XDM])) {
385         /*
386          * Look up the first cipher block, against the stored first
387          * cipher blocks for the XDM-AUTHORIZATION-1 cookies we
388          * currently know. (See comment in x11_invent_fake_auth.)
389          */
390         match_dummy.proto = X11_XDM;
391         match_dummy.xa1_firstblock = data;
392     } else {
393         return "Unsupported authorisation protocol";
394     }
395 
396     if ((auth = find234(authtree, &match_dummy, 0)) == NULL)
397         return "Authorisation not recognised";
398 
399     /*
400      * If we're using MIT-MAGIC-COOKIE-1, that was all we needed. If
401      * we're doing XDM-AUTHORIZATION-1, though, we have to check the
402      * rest of the auth data.
403      */
404     if (auth->proto == X11_XDM) {
405         unsigned long t;
406         time_t tim;
407         int i;
408         struct XDMSeen *seen, *ret;
409 
410         if (dlen != 24)
411             return "XDM-AUTHORIZATION-1 data was wrong length";
412         if (peer_port == -1)
413             return "cannot do XDM-AUTHORIZATION-1 without remote address data";
414         des_decrypt_xdmauth(auth->data+9, data, 24);
415         if (memcmp(auth->data, data, 8) != 0)
416             return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */
417         if (GET_32BIT_MSB_FIRST(data+8) != peer_ip)
418             return "XDM-AUTHORIZATION-1 data failed check";   /* IP wrong */
419         if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port)
420             return "XDM-AUTHORIZATION-1 data failed check";   /* port wrong */
421         t = GET_32BIT_MSB_FIRST(data+14);
422         for (i = 18; i < 24; i++)
423             if (data[i] != 0)          /* zero padding wrong */
424                 return "XDM-AUTHORIZATION-1 data failed check";
425         tim = time(NULL);
426         if (((unsigned long)t - (unsigned long)tim
427              + XDM_MAXSKEW) > 2*XDM_MAXSKEW)
428             return "XDM-AUTHORIZATION-1 time stamp was too far out";
429         seen = snew(struct XDMSeen);
430         seen->time = t;
431         memcpy(seen->clientid, data+8, 6);
432         assert(auth->xdmseen != NULL);
433         ret = add234(auth->xdmseen, seen);
434         if (ret != seen) {
435             sfree(seen);
436             return "XDM-AUTHORIZATION-1 data replayed";
437         }
438         /* While we're here, purge entries too old to be replayed. */
439         for (;;) {
440             seen = index234(auth->xdmseen, 0);
441             assert(seen != NULL);
442             if (t - seen->time <= XDM_MAXSKEW)
443                 break;
444             sfree(delpos234(auth->xdmseen, 0));
445         }
446     }
447     /* implement other protocols here if ever required */
448 
449     *auth_ret = auth;
450     return NULL;
451 }
452 
BinarySource_get_string_xauth(BinarySource * src)453 ptrlen BinarySource_get_string_xauth(BinarySource *src)
454 {
455     size_t len = get_uint16(src);
456     return get_data(src, len);
457 }
458 #define get_string_xauth(src) \
459     BinarySource_get_string_xauth(BinarySource_UPCAST(src))
460 
BinarySink_put_stringpl_xauth(BinarySink * bs,ptrlen pl)461 void BinarySink_put_stringpl_xauth(BinarySink *bs, ptrlen pl)
462 {
463     assert((pl.len >> 16) == 0);
464     put_uint16(bs, pl.len);
465     put_datapl(bs, pl);
466 }
467 #define put_stringpl_xauth(bs, ptrlen) \
468     BinarySink_put_stringpl_xauth(BinarySink_UPCAST(bs),ptrlen)
469 
x11_get_auth_from_authfile(struct X11Display * disp,const char * authfilename)470 void x11_get_auth_from_authfile(struct X11Display *disp,
471                                 const char *authfilename)
472 {
473     FILE *authfp;
474     char *buf;
475     int size;
476     BinarySource src[1];
477     int family, protocol;
478     ptrlen addr, protoname, data;
479     char *displaynum_string;
480     int displaynum;
481     bool ideal_match = false;
482     char *ourhostname;
483 
484     /* A maximally sized (wildly implausible) .Xauthority record
485      * consists of a 16-bit integer to start with, then four strings,
486      * each of which has a 16-bit length field followed by that many
487      * bytes of data (i.e. up to 0xFFFF bytes). */
488     const size_t MAX_RECORD_SIZE = 2 + 4 * (2+0xFFFF);
489 
490     /* We'll want a buffer of twice that size (see below). */
491     const size_t BUF_SIZE = 2 * MAX_RECORD_SIZE;
492 
493     /*
494      * Normally we should look for precisely the details specified in
495      * `disp'. However, there's an oddity when the display is local:
496      * displays like "localhost:0" usually have their details stored
497      * in a Unix-domain-socket record (even if there isn't actually a
498      * real Unix-domain socket available, as with OpenSSH's proxy X11
499      * server).
500      *
501      * This is apparently a fudge to get round the meaninglessness of
502      * "localhost" in a shared-home-directory context -- xauth entries
503      * for Unix-domain sockets already disambiguate this by storing
504      * the *local* hostname in the conveniently-blank hostname field,
505      * but IP "localhost" records couldn't do this. So, typically, an
506      * IP "localhost" entry in the auth database isn't present and if
507      * it were it would be ignored.
508      *
509      * However, we don't entirely trust that (say) Windows X servers
510      * won't rely on a straight "localhost" entry, bad idea though
511      * that is; so if we can't find a Unix-domain-socket entry we'll
512      * fall back to an IP-based entry if we can find one.
513      */
514     bool localhost = !disp->unixdomain && sk_address_is_local(disp->addr);
515 
516     authfp = fopen(authfilename, "rb");
517     if (!authfp)
518         return;
519 
520     ourhostname = get_hostname();
521 
522     /*
523      * Allocate enough space to hold two maximally sized records, so
524      * that a full record can start anywhere in the first half. That
525      * way we avoid the accidentally-quadratic algorithm that would
526      * arise if we moved everything to the front of the buffer after
527      * consuming each record; instead, we only move everything to the
528      * front after our current position gets past the half-way mark.
529      * Before then, there's no need to move anyway; so this guarantees
530      * linear time, in that every byte written into this buffer moves
531      * at most once (because every move is from the second half of the
532      * buffer to the first half).
533      */
534     buf = snewn(BUF_SIZE, char);
535     size = fread(buf, 1, BUF_SIZE, authfp);
536     BinarySource_BARE_INIT(src, buf, size);
537 
538     while (!ideal_match) {
539         bool match = false;
540 
541         if (src->pos >= MAX_RECORD_SIZE) {
542             size -= src->pos;
543             memcpy(buf, buf + src->pos, size);
544             size += fread(buf + size, 1, BUF_SIZE - size, authfp);
545             BinarySource_BARE_INIT(src, buf, size);
546         }
547 
548         family = get_uint16(src);
549         addr = get_string_xauth(src);
550         displaynum_string = mkstr(get_string_xauth(src));
551         displaynum = displaynum_string[0] ? atoi(displaynum_string) : -1;
552         sfree(displaynum_string);
553         protoname = get_string_xauth(src);
554         data = get_string_xauth(src);
555         if (get_err(src))
556             break;
557 
558         /*
559          * Now we have a full X authority record in memory. See
560          * whether it matches the display we're trying to
561          * authenticate to.
562          *
563          * The details we've just read should be interpreted as
564          * follows:
565          *
566          *  - 'family' is the network address family used to
567          *    connect to the display. 0 means IPv4; 6 means IPv6;
568          *    256 means Unix-domain sockets.
569          *
570          *  - 'addr' is the network address itself. For IPv4 and
571          *    IPv6, this is a string of binary data of the
572          *    appropriate length (respectively 4 and 16 bytes)
573          *    representing the address in big-endian format, e.g.
574          *    7F 00 00 01 means IPv4 localhost. For Unix-domain
575          *    sockets, this is the host name of the machine on
576          *    which the Unix-domain display resides (so that an
577          *    .Xauthority file on a shared file system can contain
578          *    authority entries for Unix-domain displays on
579          *    several machines without them clashing).
580          *
581          *  - 'displaynum' is the display number. An empty display
582          *    number is a wildcard for any display number.
583          *
584          *  - 'protoname' is the authorisation protocol, encoded as
585          *    its canonical string name (i.e. "MIT-MAGIC-COOKIE-1",
586          *    "XDM-AUTHORIZATION-1" or something we don't recognise).
587          *
588          *  - 'data' is the actual authorisation data, stored in
589          *    binary form.
590          */
591 
592         if (disp->displaynum < 0 ||
593             (displaynum >= 0 && disp->displaynum != displaynum))
594             continue;                  /* not the one */
595 
596         for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
597             if (ptrlen_eq_string(protoname, x11_authnames[protocol]))
598                 break;
599         if (protocol == lenof(x11_authnames))
600             continue;  /* don't recognise this protocol, look for another */
601 
602         switch (family) {
603           case 0:   /* IPv4 */
604             if (!disp->unixdomain &&
605                 sk_addrtype(disp->addr) == ADDRTYPE_IPV4) {
606                 char buf[4];
607                 sk_addrcopy(disp->addr, buf);
608                 if (addr.len == 4 && !memcmp(addr.ptr, buf, 4)) {
609                     match = true;
610                     /* If this is a "localhost" entry, note it down
611                      * but carry on looking for a Unix-domain entry. */
612                     ideal_match = !localhost;
613                 }
614             }
615             break;
616           case 6:   /* IPv6 */
617             if (!disp->unixdomain &&
618                 sk_addrtype(disp->addr) == ADDRTYPE_IPV6) {
619                 char buf[16];
620                 sk_addrcopy(disp->addr, buf);
621                 if (addr.len == 16 && !memcmp(addr.ptr, buf, 16)) {
622                     match = true;
623                     ideal_match = !localhost;
624                 }
625             }
626             break;
627           case 256: /* Unix-domain / localhost */
628             if ((disp->unixdomain || localhost)
629                 && ourhostname && ptrlen_eq_string(addr, ourhostname)) {
630                 /* A matching Unix-domain socket is always the best
631                  * match. */
632                 match = true;
633                 ideal_match = true;
634             }
635             break;
636         }
637 
638         if (match) {
639             /* Current best guess -- may be overridden if !ideal_match */
640             disp->localauthproto = protocol;
641             sfree(disp->localauthdata); /* free previous guess, if any */
642             disp->localauthdata = snewn(data.len, unsigned char);
643             memcpy(disp->localauthdata, data.ptr, data.len);
644             disp->localauthdatalen = data.len;
645         }
646     }
647 
648     fclose(authfp);
649     smemclr(buf, 2 * MAX_RECORD_SIZE);
650     sfree(buf);
651     sfree(ourhostname);
652 }
653 
x11_format_auth_for_authfile(BinarySink * bs,SockAddr * addr,int display_no,ptrlen authproto,ptrlen authdata)654 void x11_format_auth_for_authfile(
655     BinarySink *bs, SockAddr *addr, int display_no,
656     ptrlen authproto, ptrlen authdata)
657 {
658     if (sk_address_is_special_local(addr)) {
659         char *ourhostname = get_hostname();
660         put_uint16(bs, 256); /* indicates Unix-domain socket */
661         put_stringpl_xauth(bs, ptrlen_from_asciz(ourhostname));
662         sfree(ourhostname);
663     } else if (sk_addrtype(addr) == ADDRTYPE_IPV4) {
664         char ipv4buf[4];
665         sk_addrcopy(addr, ipv4buf);
666         put_uint16(bs, 0); /* indicates IPv4 */
667         put_stringpl_xauth(bs, make_ptrlen(ipv4buf, 4));
668     } else if (sk_addrtype(addr) == ADDRTYPE_IPV6) {
669         char ipv6buf[16];
670         sk_addrcopy(addr, ipv6buf);
671         put_uint16(bs, 6); /* indicates IPv6 */
672         put_stringpl_xauth(bs, make_ptrlen(ipv6buf, 16));
673     } else {
674         unreachable("Bad address type in x11_format_auth_for_authfile");
675     }
676 
677     {
678         char *numberbuf = dupprintf("%d", display_no);
679         put_stringpl_xauth(bs, ptrlen_from_asciz(numberbuf));
680         sfree(numberbuf);
681     }
682 
683     put_stringpl_xauth(bs, authproto);
684     put_stringpl_xauth(bs, authdata);
685 }
686 
x11_log(Plug * p,PlugLogType type,SockAddr * addr,int port,const char * error_msg,int error_code)687 static void x11_log(Plug *p, PlugLogType type, SockAddr *addr, int port,
688                     const char *error_msg, int error_code)
689 {
690     /* We have no interface to the logging module here, so we drop these. */
691 }
692 
693 static void x11_send_init_error(struct X11Connection *conn,
694                                 const char *err_message);
695 
x11_closing(Plug * plug,const char * error_msg,int error_code,bool calling_back)696 static void x11_closing(Plug *plug, const char *error_msg, int error_code,
697                         bool calling_back)
698 {
699     struct X11Connection *xconn = container_of(
700         plug, struct X11Connection, plug);
701 
702     if (error_msg) {
703         /*
704          * Socket error. If we're still at the connection setup stage,
705          * construct an X11 error packet passing on the problem.
706          */
707         if (xconn->no_data_sent_to_x_client) {
708             char *err_message = dupprintf("unable to connect to forwarded "
709                                           "X server: %s", error_msg);
710             x11_send_init_error(xconn, err_message);
711             sfree(err_message);
712         }
713 
714         /*
715          * Whether we did that or not, now we slam the connection
716          * shut.
717          */
718         sshfwd_initiate_close(xconn->c, error_msg);
719     } else {
720         /*
721          * Ordinary EOF received on socket. Send an EOF on the SSH
722          * channel.
723          */
724         if (xconn->c)
725             sshfwd_write_eof(xconn->c);
726     }
727 }
728 
x11_receive(Plug * plug,int urgent,const char * data,size_t len)729 static void x11_receive(Plug *plug, int urgent, const char *data, size_t len)
730 {
731     struct X11Connection *xconn = container_of(
732         plug, struct X11Connection, plug);
733 
734     xconn->no_data_sent_to_x_client = false;
735     sshfwd_write(xconn->c, data, len);
736 }
737 
x11_sent(Plug * plug,size_t bufsize)738 static void x11_sent(Plug *plug, size_t bufsize)
739 {
740     struct X11Connection *xconn = container_of(
741         plug, struct X11Connection, plug);
742 
743     sshfwd_unthrottle(xconn->c, bufsize);
744 }
745 
746 /*
747  * When setting up X forwarding, we should send the screen number
748  * from the specified local display. This function extracts it from
749  * the display string.
750  */
x11_get_screen_number(char * display)751 int x11_get_screen_number(char *display)
752 {
753     int n;
754 
755     n = host_strcspn(display, ":");
756     if (!display[n])
757         return 0;
758     n = strcspn(display, ".");
759     if (!display[n])
760         return 0;
761     return atoi(display + n + 1);
762 }
763 
764 static const PlugVtable X11Connection_plugvt = {
765     .log = x11_log,
766     .closing = x11_closing,
767     .receive = x11_receive,
768     .sent = x11_sent,
769 };
770 
771 static void x11_chan_free(Channel *chan);
772 static size_t x11_send(
773     Channel *chan, bool is_stderr, const void *vdata, size_t len);
774 static void x11_send_eof(Channel *chan);
775 static void x11_set_input_wanted(Channel *chan, bool wanted);
776 static char *x11_log_close_msg(Channel *chan);
777 
778 static const ChannelVtable X11Connection_channelvt = {
779     .free = x11_chan_free,
780     .open_confirmation = chan_remotely_opened_confirmation,
781     .open_failed = chan_remotely_opened_failure,
782     .send = x11_send,
783     .send_eof = x11_send_eof,
784     .set_input_wanted = x11_set_input_wanted,
785     .log_close_msg = x11_log_close_msg,
786     .want_close = chan_default_want_close,
787     .rcvd_exit_status = chan_no_exit_status,
788     .rcvd_exit_signal = chan_no_exit_signal,
789     .rcvd_exit_signal_numeric = chan_no_exit_signal_numeric,
790     .run_shell = chan_no_run_shell,
791     .run_command = chan_no_run_command,
792     .run_subsystem = chan_no_run_subsystem,
793     .enable_x11_forwarding = chan_no_enable_x11_forwarding,
794     .enable_agent_forwarding = chan_no_enable_agent_forwarding,
795     .allocate_pty = chan_no_allocate_pty,
796     .set_env = chan_no_set_env,
797     .send_break = chan_no_send_break,
798     .send_signal = chan_no_send_signal,
799     .change_window_size = chan_no_change_window_size,
800     .request_response = chan_no_request_response,
801 };
802 
803 /*
804  * Called to set up the X11Connection structure, though this does not
805  * yet connect to an actual server.
806  */
x11_new_channel(tree234 * authtree,SshChannel * c,const char * peeraddr,int peerport,bool connection_sharing_possible)807 Channel *x11_new_channel(tree234 *authtree, SshChannel *c,
808                          const char *peeraddr, int peerport,
809                          bool connection_sharing_possible)
810 {
811     struct X11Connection *xconn;
812 
813     /*
814      * Open socket.
815      */
816     xconn = snew(struct X11Connection);
817     xconn->plug.vt = &X11Connection_plugvt;
818     xconn->chan.vt = &X11Connection_channelvt;
819     xconn->chan.initial_fixed_window_size =
820         (connection_sharing_possible ? 128 : 0);
821     xconn->auth_protocol = NULL;
822     xconn->authtree = authtree;
823     xconn->verified = false;
824     xconn->data_read = 0;
825     xconn->input_wanted = true;
826     xconn->no_data_sent_to_x_client = true;
827     xconn->c = c;
828 
829     /*
830      * We don't actually open a local socket to the X server just yet,
831      * because we don't know which one it is. Instead, we'll wait
832      * until we see the incoming authentication data, which may tell
833      * us what display to connect to, or whether we have to divert
834      * this X forwarding channel to a connection-sharing downstream
835      * rather than handling it ourself.
836      */
837     xconn->disp = NULL;
838     xconn->s = NULL;
839 
840     /*
841      * Stash the peer address we were given in its original text form.
842      */
843     xconn->peer_addr = peeraddr ? dupstr(peeraddr) : NULL;
844     xconn->peer_port = peerport;
845 
846     return &xconn->chan;
847 }
848 
x11_chan_free(Channel * chan)849 static void x11_chan_free(Channel *chan)
850 {
851     assert(chan->vt == &X11Connection_channelvt);
852     X11Connection *xconn = container_of(chan, X11Connection, chan);
853 
854     if (xconn->auth_protocol) {
855         sfree(xconn->auth_protocol);
856         sfree(xconn->auth_data);
857     }
858 
859     if (xconn->s)
860         sk_close(xconn->s);
861 
862     sfree(xconn->peer_addr);
863     sfree(xconn);
864 }
865 
x11_set_input_wanted(Channel * chan,bool wanted)866 static void x11_set_input_wanted(Channel *chan, bool wanted)
867 {
868     assert(chan->vt == &X11Connection_channelvt);
869     X11Connection *xconn = container_of(chan, X11Connection, chan);
870 
871     xconn->input_wanted = wanted;
872     if (xconn->s)
873         sk_set_frozen(xconn->s, !xconn->input_wanted);
874 }
875 
x11_send_init_error(struct X11Connection * xconn,const char * err_message)876 static void x11_send_init_error(struct X11Connection *xconn,
877                                 const char *err_message)
878 {
879     char *full_message;
880     int msglen, msgsize;
881     unsigned char *reply;
882 
883     full_message = dupprintf("%s X11 proxy: %s\n", appname, err_message);
884 
885     msglen = strlen(full_message);
886     reply = snewn(8 + msglen+1 + 4, unsigned char); /* include zero */
887     msgsize = (msglen + 3) & ~3;
888     reply[0] = 0;              /* failure */
889     reply[1] = msglen;         /* length of reason string */
890     memcpy(reply + 2, xconn->firstpkt + 2, 4);  /* major/minor proto vsn */
891     PUT_16BIT_X11(xconn->firstpkt[0], reply + 6, msgsize >> 2);/* data len */
892     memset(reply + 8, 0, msgsize);
893     memcpy(reply + 8, full_message, msglen);
894     sshfwd_write(xconn->c, reply, 8 + msgsize);
895     sshfwd_write_eof(xconn->c);
896     xconn->no_data_sent_to_x_client = false;
897     sfree(reply);
898     sfree(full_message);
899 }
900 
x11_parse_ip(const char * addr_string,unsigned long * ip)901 static bool x11_parse_ip(const char *addr_string, unsigned long *ip)
902 {
903 
904     /*
905      * See if we can make sense of this string as an IPv4 address, for
906      * XDM-AUTHORIZATION-1 purposes.
907      */
908     int i[4];
909     if (addr_string &&
910         4 == sscanf(addr_string, "%d.%d.%d.%d", i+0, i+1, i+2, i+3)) {
911         *ip = (i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3];
912         return true;
913     } else {
914         return false;
915     }
916 }
917 
918 /*
919  * Called to send data down the raw connection.
920  */
x11_send(Channel * chan,bool is_stderr,const void * vdata,size_t len)921 static size_t x11_send(
922     Channel *chan, bool is_stderr, const void *vdata, size_t len)
923 {
924     assert(chan->vt == &X11Connection_channelvt);
925     X11Connection *xconn = container_of(chan, X11Connection, chan);
926     const char *data = (const char *)vdata;
927 
928     /*
929      * Read the first packet.
930      */
931     while (len > 0 && xconn->data_read < 12)
932         xconn->firstpkt[xconn->data_read++] = (unsigned char) (len--, *data++);
933     if (xconn->data_read < 12)
934         return 0;
935 
936     /*
937      * If we have not allocated the auth_protocol and auth_data
938      * strings, do so now.
939      */
940     if (!xconn->auth_protocol) {
941         char endian = xconn->firstpkt[0];
942         xconn->auth_plen = GET_16BIT_X11(endian, xconn->firstpkt + 6);
943         xconn->auth_dlen = GET_16BIT_X11(endian, xconn->firstpkt + 8);
944         xconn->auth_psize = (xconn->auth_plen + 3) & ~3;
945         xconn->auth_dsize = (xconn->auth_dlen + 3) & ~3;
946         /* Leave room for a terminating zero, to make our lives easier. */
947         xconn->auth_protocol = snewn(xconn->auth_psize + 1, char);
948         xconn->auth_data = snewn(xconn->auth_dsize, unsigned char);
949     }
950 
951     /*
952      * Read the auth_protocol and auth_data strings.
953      */
954     while (len > 0 &&
955            xconn->data_read < 12 + xconn->auth_psize)
956         xconn->auth_protocol[xconn->data_read++ - 12] = (len--, *data++);
957     while (len > 0 &&
958            xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
959         xconn->auth_data[xconn->data_read++ - 12 -
960                       xconn->auth_psize] = (unsigned char) (len--, *data++);
961     if (xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
962         return 0;
963 
964     /*
965      * If we haven't verified the authorisation, do so now.
966      */
967     if (!xconn->verified) {
968         const char *err;
969         struct X11FakeAuth *auth_matched = NULL;
970         unsigned long peer_ip;
971         int peer_port;
972         int protomajor, protominor;
973         void *greeting;
974         int greeting_len;
975         unsigned char *socketdata;
976         int socketdatalen;
977         char new_peer_addr[32];
978         int new_peer_port;
979         char endian = xconn->firstpkt[0];
980 
981         protomajor = GET_16BIT_X11(endian, xconn->firstpkt + 2);
982         protominor = GET_16BIT_X11(endian, xconn->firstpkt + 4);
983 
984         assert(!xconn->s);
985 
986         xconn->auth_protocol[xconn->auth_plen] = '\0';  /* ASCIZ */
987 
988         peer_ip = 0;                   /* placate optimiser */
989         if (x11_parse_ip(xconn->peer_addr, &peer_ip))
990             peer_port = xconn->peer_port;
991         else
992             peer_port = -1; /* signal no peer address data available */
993 
994         err = x11_verify(peer_ip, peer_port,
995                          xconn->authtree, xconn->auth_protocol,
996                          xconn->auth_data, xconn->auth_dlen, &auth_matched);
997         if (err) {
998             x11_send_init_error(xconn, err);
999             return 0;
1000         }
1001         assert(auth_matched);
1002 
1003         /*
1004          * If this auth points to a connection-sharing downstream
1005          * rather than an X display we know how to connect to
1006          * directly, pass it off to the sharing module now. (This will
1007          * have the side effect of freeing xconn.)
1008          */
1009         if (auth_matched->share_cs) {
1010             sshfwd_x11_sharing_handover(xconn->c, auth_matched->share_cs,
1011                                         auth_matched->share_chan,
1012                                         xconn->peer_addr, xconn->peer_port,
1013                                         xconn->firstpkt[0],
1014                                         protomajor, protominor, data, len);
1015             return 0;
1016         }
1017 
1018         /*
1019          * Now we know we're going to accept the connection, and what
1020          * X display to connect to. Actually connect to it.
1021          */
1022         xconn->chan.initial_fixed_window_size = 0;
1023         sshfwd_window_override_removed(xconn->c);
1024         xconn->disp = auth_matched->disp;
1025         xconn->s = new_connection(sk_addr_dup(xconn->disp->addr),
1026                                   xconn->disp->realhost, xconn->disp->port,
1027                                   false, true, false, false, &xconn->plug,
1028                                   sshfwd_get_conf(xconn->c));
1029         if ((err = sk_socket_error(xconn->s)) != NULL) {
1030             char *err_message = dupprintf("unable to connect to"
1031                                           " forwarded X server: %s", err);
1032             x11_send_init_error(xconn, err_message);
1033             sfree(err_message);
1034             return 0;
1035         }
1036 
1037         /*
1038          * Write a new connection header containing our replacement
1039          * auth data.
1040          */
1041         socketdatalen = 0;             /* placate compiler warning */
1042         socketdata = sk_getxdmdata(xconn->s, &socketdatalen);
1043         if (socketdata && socketdatalen==6) {
1044             sprintf(new_peer_addr, "%d.%d.%d.%d", socketdata[0],
1045                     socketdata[1], socketdata[2], socketdata[3]);
1046             new_peer_port = GET_16BIT_MSB_FIRST(socketdata + 4);
1047         } else {
1048             strcpy(new_peer_addr, "0.0.0.0");
1049             new_peer_port = 0;
1050         }
1051 
1052         greeting = x11_make_greeting(xconn->firstpkt[0],
1053                                      protomajor, protominor,
1054                                      xconn->disp->localauthproto,
1055                                      xconn->disp->localauthdata,
1056                                      xconn->disp->localauthdatalen,
1057                                      new_peer_addr, new_peer_port,
1058                                      &greeting_len);
1059 
1060         sk_write(xconn->s, greeting, greeting_len);
1061 
1062         smemclr(greeting, greeting_len);
1063         sfree(greeting);
1064 
1065         /*
1066          * Now we're done.
1067          */
1068         xconn->verified = true;
1069     }
1070 
1071     /*
1072      * After initialisation, just copy data simply.
1073      */
1074 
1075     return sk_write(xconn->s, data, len);
1076 }
1077 
x11_send_eof(Channel * chan)1078 static void x11_send_eof(Channel *chan)
1079 {
1080     assert(chan->vt == &X11Connection_channelvt);
1081     X11Connection *xconn = container_of(chan, X11Connection, chan);
1082 
1083     if (xconn->s) {
1084         sk_write_eof(xconn->s);
1085     } else {
1086         /*
1087          * If EOF is received from the X client before we've got to
1088          * the point of actually connecting to an X server, then we
1089          * should send an EOF back to the client so that the
1090          * forwarded channel will be terminated.
1091          */
1092         if (xconn->c)
1093             sshfwd_write_eof(xconn->c);
1094     }
1095 }
1096 
x11_log_close_msg(Channel * chan)1097 static char *x11_log_close_msg(Channel *chan)
1098 {
1099     return dupstr("Forwarded X11 connection terminated");
1100 }
1101 
1102 /*
1103  * Utility functions used by connection sharing to convert textual
1104  * representations of an X11 auth protocol name + hex cookie into our
1105  * usual integer protocol id and binary auth data.
1106  */
x11_identify_auth_proto(ptrlen protoname)1107 int x11_identify_auth_proto(ptrlen protoname)
1108 {
1109     int protocol;
1110 
1111     for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
1112         if (ptrlen_eq_string(protoname, x11_authnames[protocol]))
1113             return protocol;
1114     return -1;
1115 }
1116 
x11_dehexify(ptrlen hexpl,int * outlen)1117 void *x11_dehexify(ptrlen hexpl, int *outlen)
1118 {
1119     int len, i;
1120     unsigned char *ret;
1121 
1122     len = hexpl.len / 2;
1123     ret = snewn(len, unsigned char);
1124 
1125     for (i = 0; i < len; i++) {
1126         char bytestr[3];
1127         unsigned val = 0;
1128         bytestr[0] = ((const char *)hexpl.ptr)[2*i];
1129         bytestr[1] = ((const char *)hexpl.ptr)[2*i+1];
1130         bytestr[2] = '\0';
1131         sscanf(bytestr, "%x", &val);
1132         ret[i] = val;
1133     }
1134 
1135     *outlen = len;
1136     return ret;
1137 }
1138 
1139 /*
1140  * Construct an X11 greeting packet, including making up the right
1141  * authorisation data.
1142  */
x11_make_greeting(int endian,int protomajor,int protominor,int auth_proto,const void * auth_data,int auth_len,const char * peer_addr,int peer_port,int * outlen)1143 void *x11_make_greeting(int endian, int protomajor, int protominor,
1144                         int auth_proto, const void *auth_data, int auth_len,
1145                         const char *peer_addr, int peer_port,
1146                         int *outlen)
1147 {
1148     unsigned char *greeting;
1149     unsigned char realauthdata[64];
1150     const char *authname;
1151     const unsigned char *authdata;
1152     int authnamelen, authnamelen_pad;
1153     int authdatalen, authdatalen_pad;
1154     int greeting_len;
1155 
1156     authname = x11_authnames[auth_proto];
1157     authnamelen = strlen(authname);
1158     authnamelen_pad = (authnamelen + 3) & ~3;
1159 
1160     if (auth_proto == X11_MIT) {
1161         authdata = auth_data;
1162         authdatalen = auth_len;
1163     } else if (auth_proto == X11_XDM && auth_len == 16) {
1164         time_t t;
1165         unsigned long peer_ip = 0;
1166 
1167         x11_parse_ip(peer_addr, &peer_ip);
1168 
1169         authdata = realauthdata;
1170         authdatalen = 24;
1171         memset(realauthdata, 0, authdatalen);
1172         memcpy(realauthdata, auth_data, 8);
1173         PUT_32BIT_MSB_FIRST(realauthdata+8, peer_ip);
1174         PUT_16BIT_MSB_FIRST(realauthdata+12, peer_port);
1175         t = time(NULL);
1176         PUT_32BIT_MSB_FIRST(realauthdata+14, t);
1177 
1178         des_encrypt_xdmauth((char *)auth_data + 9, realauthdata, authdatalen);
1179     } else {
1180         authdata = realauthdata;
1181         authdatalen = 0;
1182     }
1183 
1184     authdatalen_pad = (authdatalen + 3) & ~3;
1185     greeting_len = 12 + authnamelen_pad + authdatalen_pad;
1186 
1187     greeting = snewn(greeting_len, unsigned char);
1188     memset(greeting, 0, greeting_len);
1189     greeting[0] = endian;
1190     PUT_16BIT_X11(endian, greeting+2, protomajor);
1191     PUT_16BIT_X11(endian, greeting+4, protominor);
1192     PUT_16BIT_X11(endian, greeting+6, authnamelen);
1193     PUT_16BIT_X11(endian, greeting+8, authdatalen);
1194     memcpy(greeting+12, authname, authnamelen);
1195     memcpy(greeting+12+authnamelen_pad, authdata, authdatalen);
1196 
1197     smemclr(realauthdata, sizeof(realauthdata));
1198 
1199     *outlen = greeting_len;
1200     return greeting;
1201 }
1202