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