2 * Platform-independent bits of X11 forwarding.
14 #define GET_16BIT(endian, cp) \
15 (endian=='B' ? GET_16BIT_MSB_FIRST(cp) : GET_16BIT_LSB_FIRST(cp))
17 #define PUT_16BIT(endian, cp, val) \
18 (endian=='B' ? PUT_16BIT_MSB_FIRST(cp, val) : PUT_16BIT_LSB_FIRST(cp, val))
20 const char *const x11_authnames[] = {
21 "", "MIT-MAGIC-COOKIE-1", "XDM-AUTHORIZATION-1"
26 unsigned char clientid[6];
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 */
34 struct X11Display *disp;
36 unsigned char *auth_data;
37 int data_read, auth_plen, auth_psize, auth_dlen, auth_dsize;
39 int throttled, throttle_override;
40 int no_data_sent_to_x_client;
43 struct ssh_channel *c; /* channel structure held by ssh.c */
47 static int xdmseen_cmp(void *a, void *b)
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));
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)
64 static int dummy_plug_receive(Plug p, int urgent, char *data, int len)
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
73 struct X11FakeAuth *x11_invent_fake_auth(tree234 *authtree, int authtype)
75 struct X11FakeAuth *auth = snew(struct X11FakeAuth);
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.
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.)
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.
103 if (authtype == X11_MIT) {
104 auth->proto = X11_MIT;
106 /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */
108 auth->data = snewn(auth->datalen, unsigned char);
109 auth->xa1_firstblock = NULL;
112 for (i = 0; i < auth->datalen; i++)
113 auth->data[i] = random_byte();
114 if (add234(authtree, auth) == auth)
118 auth->xdmseen = NULL;
120 assert(authtype == X11_XDM);
121 auth->proto = X11_XDM;
123 /* XDM-AUTHORIZATION-1. Cookie size is 16 bytes; byte 8 is zero. */
125 auth->data = snewn(auth->datalen, unsigned char);
126 auth->xa1_firstblock = snewn(8, unsigned char);
127 memset(auth->xa1_firstblock, 0, 8);
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)
138 auth->xdmseen = newtree234(xdmseen_cmp);
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",
147 auth->share_cs = auth->share_chan = NULL;
152 void x11_free_fake_auth(struct X11FakeAuth *auth)
155 smemclr(auth->data, auth->datalen);
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)
164 freetree234(auth->xdmseen);
169 int x11_authcmp(void *av, void *bv)
171 struct X11FakeAuth *a = (struct X11FakeAuth *)av;
172 struct X11FakeAuth *b = (struct X11FakeAuth *)bv;
174 if (a->proto < b->proto)
176 else if (a->proto > b->proto)
179 if (a->proto == X11_MIT) {
180 if (a->datalen < b->datalen)
182 else if (a->datalen > b->datalen)
185 return memcmp(a->data, b->data, a->datalen);
187 assert(a->proto == X11_XDM);
189 return memcmp(a->xa1_firstblock, b->xa1_firstblock, 8);
193 struct X11Display *x11_setup_display(const char *display, Conf *conf)
195 struct X11Display *disp = snew(struct X11Display);
198 if (!display || !*display) {
199 localcopy = platform_get_x_display();
200 if (!localcopy || !*localcopy) {
202 localcopy = dupstr(":0"); /* plausible default for any platform */
205 localcopy = dupstr(display);
208 * Parse the display name.
210 * We expect this to have one of the following forms:
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!)
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 '/'.
222 if (localcopy[0] == '/') {
223 disp->unixsocketpath = localcopy;
224 disp->unixdomain = TRUE;
225 disp->hostname = NULL;
226 disp->displaynum = -1;
230 char *colon, *dot, *slash;
231 char *protocol, *hostname;
233 colon = host_strrchr(localcopy, ':');
237 return NULL; /* FIXME: report a specific error? */
241 dot = strchr(colon, '.');
245 disp->displaynum = atoi(colon);
247 disp->screennum = atoi(dot);
252 hostname = localcopy;
253 if (colon > localcopy) {
254 slash = strchr(localcopy, '/');
257 protocol = localcopy;
262 disp->hostname = *hostname ? dupstr(hostname) : NULL;
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;
270 disp->unixdomain = FALSE;
272 if (!disp->hostname && !disp->unixdomain)
273 disp->hostname = dupstr("localhost");
275 disp->unixsocketpath = NULL;
282 * Look up the display hostname, if we need to.
284 if (!disp->unixdomain) {
287 disp->port = 6000 + disp->displaynum;
288 disp->addr = name_lookup(disp->hostname, disp->port,
289 &disp->realhost, conf, ADDRTYPE_UNSPEC,
292 if ((err = sk_addr_error(disp->addr)) != NULL) {
293 sk_addr_free(disp->addr);
294 sfree(disp->hostname);
295 sfree(disp->unixsocketpath);
297 return NULL; /* FIXME: report an error */
302 * Try upgrading an IP-style localhost display to a Unix-socket
303 * display (as the standard X connection libraries do).
305 if (!disp->unixdomain && sk_address_is_local(disp->addr)) {
306 SockAddr ux = platform_get_x11_unix_address(NULL, disp->displaynum);
307 const char *err = sk_addr_error(ux);
309 /* Create trial connection to see if there is a useful Unix-domain
311 const struct plug_function_table *dummy = &dummy_plug;
312 Socket s = sk_new(sk_addr_dup(ux), 0, 0, 0, 0, 0, (Plug)&dummy);
313 err = sk_socket_error(s);
319 sk_addr_free(disp->addr);
320 disp->unixdomain = TRUE;
322 /* Fill in the rest in a moment */
326 if (disp->unixdomain) {
328 disp->addr = platform_get_x11_unix_address(disp->unixsocketpath,
330 if (disp->unixsocketpath)
331 disp->realhost = dupstr(disp->unixsocketpath);
333 disp->realhost = dupprintf("unix:%d", disp->displaynum);
338 * Fetch the local authorisation details.
340 disp->localauthproto = X11_NO_AUTH;
341 disp->localauthdata = NULL;
342 disp->localauthdatalen = 0;
343 platform_get_x11_auth(disp, conf);
348 void x11_free_display(struct X11Display *disp)
350 sfree(disp->hostname);
351 sfree(disp->unixsocketpath);
352 if (disp->localauthdata)
353 smemclr(disp->localauthdata, disp->localauthdatalen);
354 sfree(disp->localauthdata);
355 sk_addr_free(disp->addr);
359 #define XDM_MAXSKEW 20*60 /* 20 minute clock skew should be OK */
361 static const char *x11_verify(unsigned long peer_ip, int peer_port,
362 tree234 *authtree, char *proto,
363 unsigned char *data, int dlen,
364 struct X11FakeAuth **auth_ret)
366 struct X11FakeAuth match_dummy; /* for passing to find234 */
367 struct X11FakeAuth *auth;
370 * First, do a lookup in our tree to find the only authorisation
371 * record that _might_ match.
373 if (!strcmp(proto, x11_authnames[X11_MIT])) {
375 * Just look up the whole cookie that was presented to us,
376 * which x11_authcmp will compare against the cookies we
377 * currently believe in.
379 match_dummy.proto = X11_MIT;
380 match_dummy.datalen = dlen;
381 match_dummy.data = data;
382 } else if (!strcmp(proto, x11_authnames[X11_XDM])) {
384 * Look up the first cipher block, against the stored first
385 * cipher blocks for the XDM-AUTHORIZATION-1 cookies we
386 * currently know. (See comment in x11_invent_fake_auth.)
388 match_dummy.proto = X11_XDM;
389 match_dummy.xa1_firstblock = data;
391 return "Unsupported authorisation protocol";
394 if ((auth = find234(authtree, &match_dummy, 0)) == NULL)
395 return "Authorisation not recognised";
398 * If we're using MIT-MAGIC-COOKIE-1, that was all we needed. If
399 * we're doing XDM-AUTHORIZATION-1, though, we have to check the
400 * rest of the auth data.
402 if (auth->proto == X11_XDM) {
406 struct XDMSeen *seen, *ret;
409 return "XDM-AUTHORIZATION-1 data was wrong length";
411 return "cannot do XDM-AUTHORIZATION-1 without remote address data";
412 des_decrypt_xdmauth(auth->data+9, data, 24);
413 if (memcmp(auth->data, data, 8) != 0)
414 return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */
415 if (GET_32BIT_MSB_FIRST(data+8) != peer_ip)
416 return "XDM-AUTHORIZATION-1 data failed check"; /* IP wrong */
417 if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port)
418 return "XDM-AUTHORIZATION-1 data failed check"; /* port wrong */
419 t = GET_32BIT_MSB_FIRST(data+14);
420 for (i = 18; i < 24; i++)
421 if (data[i] != 0) /* zero padding wrong */
422 return "XDM-AUTHORIZATION-1 data failed check";
424 if (((unsigned long)t - (unsigned long)tim
425 + XDM_MAXSKEW) > 2*XDM_MAXSKEW)
426 return "XDM-AUTHORIZATION-1 time stamp was too far out";
427 seen = snew(struct XDMSeen);
429 memcpy(seen->clientid, data+8, 6);
430 assert(auth->xdmseen != NULL);
431 ret = add234(auth->xdmseen, seen);
434 return "XDM-AUTHORIZATION-1 data replayed";
436 /* While we're here, purge entries too old to be replayed. */
438 seen = index234(auth->xdmseen, 0);
439 assert(seen != NULL);
440 if (t - seen->time <= XDM_MAXSKEW)
442 sfree(delpos234(auth->xdmseen, 0));
445 /* implement other protocols here if ever required */
451 void x11_get_auth_from_authfile(struct X11Display *disp,
452 const char *authfilename)
455 char *buf, *ptr, *str[4];
457 int family, protocol;
458 int ideal_match = FALSE;
462 * Normally we should look for precisely the details specified in
463 * `disp'. However, there's an oddity when the display is local:
464 * displays like "localhost:0" usually have their details stored
465 * in a Unix-domain-socket record (even if there isn't actually a
466 * real Unix-domain socket available, as with OpenSSH's proxy X11
469 * This is apparently a fudge to get round the meaninglessness of
470 * "localhost" in a shared-home-directory context -- xauth entries
471 * for Unix-domain sockets already disambiguate this by storing
472 * the *local* hostname in the conveniently-blank hostname field,
473 * but IP "localhost" records couldn't do this. So, typically, an
474 * IP "localhost" entry in the auth database isn't present and if
475 * it were it would be ignored.
477 * However, we don't entirely trust that (say) Windows X servers
478 * won't rely on a straight "localhost" entry, bad idea though
479 * that is; so if we can't find a Unix-domain-socket entry we'll
480 * fall back to an IP-based entry if we can find one.
482 int localhost = !disp->unixdomain && sk_address_is_local(disp->addr);
484 authfp = fopen(authfilename, "rb");
488 ourhostname = get_hostname();
490 /* Records in .Xauthority contain four strings of up to 64K each */
491 buf = snewn(65537 * 4, char);
493 while (!ideal_match) {
494 int c, i, j, match = FALSE;
496 #define GET do { c = fgetc(authfp); if (c == EOF) goto done; c = (unsigned char)c; } while (0)
497 /* Expect a big-endian 2-byte number giving address family */
499 GET; family = (family << 8) | c;
500 /* Then expect four strings, each composed of a big-endian 2-byte
501 * length field followed by that many bytes of data */
503 for (i = 0; i < 4; i++) {
505 GET; len[i] = (len[i] << 8) | c;
507 for (j = 0; j < len[i]; j++) {
515 * Now we have a full X authority record in memory. See
516 * whether it matches the display we're trying to
519 * The details we've just read should be interpreted as
522 * - 'family' is the network address family used to
523 * connect to the display. 0 means IPv4; 6 means IPv6;
524 * 256 means Unix-domain sockets.
526 * - str[0] is the network address itself. For IPv4 and
527 * IPv6, this is a string of binary data of the
528 * appropriate length (respectively 4 and 16 bytes)
529 * representing the address in big-endian format, e.g.
530 * 7F 00 00 01 means IPv4 localhost. For Unix-domain
531 * sockets, this is the host name of the machine on
532 * which the Unix-domain display resides (so that an
533 * .Xauthority file on a shared file system can contain
534 * authority entries for Unix-domain displays on
535 * several machines without them clashing).
537 * - str[1] is the display number. I've no idea why
538 * .Xauthority stores this as a string when it has a
539 * perfectly good integer format, but there we go.
541 * - str[2] is the authorisation method, encoded as its
542 * canonical string name (i.e. "MIT-MAGIC-COOKIE-1",
543 * "XDM-AUTHORIZATION-1" or something we don't
546 * - str[3] is the actual authorisation data, stored in
550 if (disp->displaynum < 0 || disp->displaynum != atoi(str[1]))
551 continue; /* not the one */
553 for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
554 if (!strcmp(str[2], x11_authnames[protocol]))
556 if (protocol == lenof(x11_authnames))
557 continue; /* don't recognise this protocol, look for another */
561 if (!disp->unixdomain &&
562 sk_addrtype(disp->addr) == ADDRTYPE_IPV4) {
564 sk_addrcopy(disp->addr, buf);
565 if (len[0] == 4 && !memcmp(str[0], buf, 4)) {
567 /* If this is a "localhost" entry, note it down
568 * but carry on looking for a Unix-domain entry. */
569 ideal_match = !localhost;
574 if (!disp->unixdomain &&
575 sk_addrtype(disp->addr) == ADDRTYPE_IPV6) {
577 sk_addrcopy(disp->addr, buf);
578 if (len[0] == 16 && !memcmp(str[0], buf, 16)) {
580 ideal_match = !localhost;
584 case 256: /* Unix-domain / localhost */
585 if ((disp->unixdomain || localhost)
586 && ourhostname && !strcmp(ourhostname, str[0]))
587 /* A matching Unix-domain socket is always the best
589 match = ideal_match = TRUE;
594 /* Current best guess -- may be overridden if !ideal_match */
595 disp->localauthproto = protocol;
596 sfree(disp->localauthdata); /* free previous guess, if any */
597 disp->localauthdata = snewn(len[3], unsigned char);
598 memcpy(disp->localauthdata, str[3], len[3]);
599 disp->localauthdatalen = len[3];
605 smemclr(buf, 65537 * 4);
610 static void x11_log(Plug p, int type, SockAddr addr, int port,
611 const char *error_msg, int error_code)
613 /* We have no interface to the logging module here, so we drop these. */
616 static void x11_send_init_error(struct X11Connection *conn,
617 const char *err_message);
619 static int x11_closing(Plug plug, const char *error_msg, int error_code,
622 struct X11Connection *xconn = (struct X11Connection *) plug;
626 * Socket error. If we're still at the connection setup stage,
627 * construct an X11 error packet passing on the problem.
629 if (xconn->no_data_sent_to_x_client) {
630 char *err_message = dupprintf("unable to connect to forwarded "
631 "X server: %s", error_msg);
632 x11_send_init_error(xconn, err_message);
637 * Whether we did that or not, now we slam the connection
640 sshfwd_unclean_close(xconn->c, error_msg);
643 * Ordinary EOF received on socket. Send an EOF on the SSH
647 sshfwd_write_eof(xconn->c);
653 static int x11_receive(Plug plug, int urgent, char *data, int len)
655 struct X11Connection *xconn = (struct X11Connection *) plug;
657 if (sshfwd_write(xconn->c, data, len) > 0) {
658 xconn->throttled = 1;
659 xconn->no_data_sent_to_x_client = FALSE;
660 sk_set_frozen(xconn->s, 1);
666 static void x11_sent(Plug plug, int bufsize)
668 struct X11Connection *xconn = (struct X11Connection *) plug;
670 sshfwd_unthrottle(xconn->c, bufsize);
674 * When setting up X forwarding, we should send the screen number
675 * from the specified local display. This function extracts it from
676 * the display string.
678 int x11_get_screen_number(char *display)
682 n = host_strcspn(display, ":");
685 n = strcspn(display, ".");
688 return atoi(display + n + 1);
692 * Called to set up the X11Connection structure, though this does not
693 * yet connect to an actual server.
695 struct X11Connection *x11_init(tree234 *authtree, void *c,
696 const char *peeraddr, int peerport)
698 static const struct plug_function_table fn_table = {
706 struct X11Connection *xconn;
711 xconn = snew(struct X11Connection);
712 xconn->fn = &fn_table;
713 xconn->auth_protocol = NULL;
714 xconn->authtree = authtree;
716 xconn->data_read = 0;
717 xconn->throttled = xconn->throttle_override = 0;
718 xconn->no_data_sent_to_x_client = TRUE;
722 * We don't actually open a local socket to the X server just yet,
723 * because we don't know which one it is. Instead, we'll wait
724 * until we see the incoming authentication data, which may tell
725 * us what display to connect to, or whether we have to divert
726 * this X forwarding channel to a connection-sharing downstream
727 * rather than handling it ourself.
733 * Stash the peer address we were given in its original text form.
735 xconn->peer_addr = peeraddr ? dupstr(peeraddr) : NULL;
736 xconn->peer_port = peerport;
741 void x11_close(struct X11Connection *xconn)
746 if (xconn->auth_protocol) {
747 sfree(xconn->auth_protocol);
748 sfree(xconn->auth_data);
754 sfree(xconn->peer_addr);
758 void x11_unthrottle(struct X11Connection *xconn)
763 xconn->throttled = 0;
765 sk_set_frozen(xconn->s, xconn->throttled || xconn->throttle_override);
768 void x11_override_throttle(struct X11Connection *xconn, int enable)
773 xconn->throttle_override = enable;
775 sk_set_frozen(xconn->s, xconn->throttled || xconn->throttle_override);
778 static void x11_send_init_error(struct X11Connection *xconn,
779 const char *err_message)
783 unsigned char *reply;
785 full_message = dupprintf("%s X11 proxy: %s\n", appname, err_message);
787 msglen = strlen(full_message);
788 reply = snewn(8 + msglen+1 + 4, unsigned char); /* include zero */
789 msgsize = (msglen + 3) & ~3;
790 reply[0] = 0; /* failure */
791 reply[1] = msglen; /* length of reason string */
792 memcpy(reply + 2, xconn->firstpkt + 2, 4); /* major/minor proto vsn */
793 PUT_16BIT(xconn->firstpkt[0], reply + 6, msgsize >> 2);/* data len */
794 memset(reply + 8, 0, msgsize);
795 memcpy(reply + 8, full_message, msglen);
796 sshfwd_write(xconn->c, (char *)reply, 8 + msgsize);
797 sshfwd_write_eof(xconn->c);
798 xconn->no_data_sent_to_x_client = FALSE;
803 static int x11_parse_ip(const char *addr_string, unsigned long *ip)
807 * See if we can make sense of this string as an IPv4 address, for
808 * XDM-AUTHORIZATION-1 purposes.
812 4 == sscanf(addr_string, "%d.%d.%d.%d", i+0, i+1, i+2, i+3)) {
813 *ip = (i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3];
821 * Called to send data down the raw connection.
823 int x11_send(struct X11Connection *xconn, char *data, int len)
829 * Read the first packet.
831 while (len > 0 && xconn->data_read < 12)
832 xconn->firstpkt[xconn->data_read++] = (unsigned char) (len--, *data++);
833 if (xconn->data_read < 12)
837 * If we have not allocated the auth_protocol and auth_data
838 * strings, do so now.
840 if (!xconn->auth_protocol) {
841 xconn->auth_plen = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 6);
842 xconn->auth_dlen = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 8);
843 xconn->auth_psize = (xconn->auth_plen + 3) & ~3;
844 xconn->auth_dsize = (xconn->auth_dlen + 3) & ~3;
845 /* Leave room for a terminating zero, to make our lives easier. */
846 xconn->auth_protocol = snewn(xconn->auth_psize + 1, char);
847 xconn->auth_data = snewn(xconn->auth_dsize, unsigned char);
851 * Read the auth_protocol and auth_data strings.
854 xconn->data_read < 12 + xconn->auth_psize)
855 xconn->auth_protocol[xconn->data_read++ - 12] = (len--, *data++);
857 xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
858 xconn->auth_data[xconn->data_read++ - 12 -
859 xconn->auth_psize] = (unsigned char) (len--, *data++);
860 if (xconn->data_read < 12 + xconn->auth_psize + xconn->auth_dsize)
864 * If we haven't verified the authorisation, do so now.
866 if (!xconn->verified) {
868 struct X11FakeAuth *auth_matched = NULL;
869 unsigned long peer_ip;
871 int protomajor, protominor;
874 unsigned char *socketdata;
876 char new_peer_addr[32];
879 protomajor = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 2);
880 protominor = GET_16BIT(xconn->firstpkt[0], xconn->firstpkt + 4);
884 xconn->auth_protocol[xconn->auth_plen] = '\0'; /* ASCIZ */
886 peer_ip = 0; /* placate optimiser */
887 if (x11_parse_ip(xconn->peer_addr, &peer_ip))
888 peer_port = xconn->peer_port;
890 peer_port = -1; /* signal no peer address data available */
892 err = x11_verify(peer_ip, peer_port,
893 xconn->authtree, xconn->auth_protocol,
894 xconn->auth_data, xconn->auth_dlen, &auth_matched);
896 x11_send_init_error(xconn, err);
899 assert(auth_matched);
902 * If this auth points to a connection-sharing downstream
903 * rather than an X display we know how to connect to
904 * directly, pass it off to the sharing module now.
906 if (auth_matched->share_cs) {
907 sshfwd_x11_sharing_handover(xconn->c, auth_matched->share_cs,
908 auth_matched->share_chan,
909 xconn->peer_addr, xconn->peer_port,
911 protomajor, protominor, data, len);
916 * Now we know we're going to accept the connection, and what
917 * X display to connect to. Actually connect to it.
919 sshfwd_x11_is_local(xconn->c);
920 xconn->disp = auth_matched->disp;
921 xconn->s = new_connection(sk_addr_dup(xconn->disp->addr),
922 xconn->disp->realhost, xconn->disp->port,
923 0, 1, 0, 0, (Plug) xconn,
924 sshfwd_get_conf(xconn->c));
925 if ((err = sk_socket_error(xconn->s)) != NULL) {
926 char *err_message = dupprintf("unable to connect to"
927 " forwarded X server: %s", err);
928 x11_send_init_error(xconn, err_message);
934 * Write a new connection header containing our replacement
938 socketdata = sk_getxdmdata(xconn->s, &socketdatalen);
939 if (socketdata && socketdatalen==6) {
940 sprintf(new_peer_addr, "%d.%d.%d.%d", socketdata[0],
941 socketdata[1], socketdata[2], socketdata[3]);
942 new_peer_port = GET_16BIT_MSB_FIRST(socketdata + 4);
944 strcpy(new_peer_addr, "0.0.0.0");
948 greeting = x11_make_greeting(xconn->firstpkt[0],
949 protomajor, protominor,
950 xconn->disp->localauthproto,
951 xconn->disp->localauthdata,
952 xconn->disp->localauthdatalen,
953 new_peer_addr, new_peer_port,
956 sk_write(xconn->s, greeting, greeting_len);
958 smemclr(greeting, greeting_len);
968 * After initialisation, just copy data simply.
971 return sk_write(xconn->s, data, len);
974 void x11_send_eof(struct X11Connection *xconn)
977 sk_write_eof(xconn->s);
980 * If EOF is received from the X client before we've got to
981 * the point of actually connecting to an X server, then we
982 * should send an EOF back to the client so that the
983 * forwarded channel will be terminated.
986 sshfwd_write_eof(xconn->c);
991 * Utility functions used by connection sharing to convert textual
992 * representations of an X11 auth protocol name + hex cookie into our
993 * usual integer protocol id and binary auth data.
995 int x11_identify_auth_proto(const char *protoname)
999 for (protocol = 1; protocol < lenof(x11_authnames); protocol++)
1000 if (!strcmp(protoname, x11_authnames[protocol]))
1005 void *x11_dehexify(const char *hex, int *outlen)
1010 len = strlen(hex) / 2;
1011 ret = snewn(len, unsigned char);
1013 for (i = 0; i < len; i++) {
1016 bytestr[0] = hex[2*i];
1017 bytestr[1] = hex[2*i+1];
1019 sscanf(bytestr, "%x", &val);
1028 * Construct an X11 greeting packet, including making up the right
1029 * authorisation data.
1031 void *x11_make_greeting(int endian, int protomajor, int protominor,
1032 int auth_proto, const void *auth_data, int auth_len,
1033 const char *peer_addr, int peer_port,
1036 unsigned char *greeting;
1037 unsigned char realauthdata[64];
1038 const char *authname;
1039 const unsigned char *authdata;
1040 int authnamelen, authnamelen_pad;
1041 int authdatalen, authdatalen_pad;
1044 authname = x11_authnames[auth_proto];
1045 authnamelen = strlen(authname);
1046 authnamelen_pad = (authnamelen + 3) & ~3;
1048 if (auth_proto == X11_MIT) {
1049 authdata = auth_data;
1050 authdatalen = auth_len;
1051 } else if (auth_proto == X11_XDM && auth_len == 16) {
1053 unsigned long peer_ip = 0;
1055 x11_parse_ip(peer_addr, &peer_ip);
1057 authdata = realauthdata;
1059 memset(realauthdata, 0, authdatalen);
1060 memcpy(realauthdata, auth_data, 8);
1061 PUT_32BIT_MSB_FIRST(realauthdata+8, peer_ip);
1062 PUT_16BIT_MSB_FIRST(realauthdata+12, peer_port);
1064 PUT_32BIT_MSB_FIRST(realauthdata+14, t);
1066 des_encrypt_xdmauth((const unsigned char *)auth_data + 9,
1067 realauthdata, authdatalen);
1069 authdata = realauthdata;
1073 authdatalen_pad = (authdatalen + 3) & ~3;
1074 greeting_len = 12 + authnamelen_pad + authdatalen_pad;
1076 greeting = snewn(greeting_len, unsigned char);
1077 memset(greeting, 0, greeting_len);
1078 greeting[0] = endian;
1079 PUT_16BIT(endian, greeting+2, protomajor);
1080 PUT_16BIT(endian, greeting+4, protominor);
1081 PUT_16BIT(endian, greeting+6, authnamelen);
1082 PUT_16BIT(endian, greeting+8, authdatalen);
1083 memcpy(greeting+12, authname, authnamelen);
1084 memcpy(greeting+12+authnamelen_pad, authdata, authdatalen);
1086 smemclr(realauthdata, sizeof(realauthdata));
1088 *outlen = greeting_len;