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