]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - x11fwd.c
Integrate unfix.org's IPv6 patches up to level 10, with rather a lot
[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
13 #define GET_32BIT_LSB_FIRST(cp) \
14   (((unsigned long)(unsigned char)(cp)[0]) | \
15   ((unsigned long)(unsigned char)(cp)[1] << 8) | \
16   ((unsigned long)(unsigned char)(cp)[2] << 16) | \
17   ((unsigned long)(unsigned char)(cp)[3] << 24))
18
19 #define PUT_32BIT_LSB_FIRST(cp, value) ( \
20   (cp)[0] = (char)(value), \
21   (cp)[1] = (char)((value) >> 8), \
22   (cp)[2] = (char)((value) >> 16), \
23   (cp)[3] = (char)((value) >> 24) )
24
25 #define GET_16BIT_LSB_FIRST(cp) \
26   (((unsigned long)(unsigned char)(cp)[0]) | \
27   ((unsigned long)(unsigned char)(cp)[1] << 8))
28
29 #define PUT_16BIT_LSB_FIRST(cp, value) ( \
30   (cp)[0] = (char)(value), \
31   (cp)[1] = (char)((value) >> 8) )
32
33 #define GET_32BIT_MSB_FIRST(cp) \
34   (((unsigned long)(unsigned char)(cp)[0] << 24) | \
35   ((unsigned long)(unsigned char)(cp)[1] << 16) | \
36   ((unsigned long)(unsigned char)(cp)[2] << 8) | \
37   ((unsigned long)(unsigned char)(cp)[3]))
38
39 #define PUT_32BIT_MSB_FIRST(cp, value) ( \
40   (cp)[0] = (char)((value) >> 24), \
41   (cp)[1] = (char)((value) >> 16), \
42   (cp)[2] = (char)((value) >> 8), \
43   (cp)[3] = (char)(value) )
44
45 #define GET_16BIT_MSB_FIRST(cp) \
46   (((unsigned long)(unsigned char)(cp)[0] << 8) | \
47   ((unsigned long)(unsigned char)(cp)[1]))
48
49 #define PUT_16BIT_MSB_FIRST(cp, value) ( \
50   (cp)[0] = (char)((value) >> 8), \
51   (cp)[1] = (char)(value) )
52
53 #define GET_16BIT(endian, cp) \
54   (endian=='B' ? GET_16BIT_MSB_FIRST(cp) : GET_16BIT_LSB_FIRST(cp))
55
56 #define PUT_16BIT(endian, cp, val) \
57   (endian=='B' ? PUT_16BIT_MSB_FIRST(cp, val) : PUT_16BIT_LSB_FIRST(cp, val))
58
59 const char *const x11_authnames[] = {
60     "", "MIT-MAGIC-COOKIE-1", "XDM-AUTHORIZATION-1"
61 };
62
63 struct X11Auth {
64     unsigned char fakedata[64], realdata[64];
65     int fakeproto, realproto;
66     int fakelen, reallen;
67 };
68
69 struct X11Private {
70     const struct plug_function_table *fn;
71     /* the above variable absolutely *must* be the first in this structure */
72     unsigned char firstpkt[12];        /* first X data packet */
73     struct X11Auth *auth;
74     char *auth_protocol;
75     unsigned char *auth_data;
76     int data_read, auth_plen, auth_psize, auth_dlen, auth_dsize;
77     int verified;
78     int throttled, throttle_override;
79     unsigned long peer_ip;
80     int peer_port;
81     void *c;                           /* data used by ssh.c */
82     Socket s;
83 };
84
85 void *x11_invent_auth(char *proto, int protomaxlen,
86                       char *data, int datamaxlen, int proto_id)
87 {
88     struct X11Auth *auth = snew(struct X11Auth);
89     char ourdata[64];
90     int i;
91
92     if (proto_id == X11_MIT) {
93         auth->fakeproto = X11_MIT;
94
95         /* MIT-MAGIC-COOKIE-1. Cookie size is 128 bits (16 bytes). */
96         auth->fakelen = 16;
97         for (i = 0; i < 16; i++)
98             auth->fakedata[i] = random_byte();
99     } else {
100         assert(proto_id == X11_XDM);
101         auth->fakeproto = X11_XDM;
102
103         /* XDM-AUTHORIZATION-1. Cookie size is 16 bytes; byte 8 is zero. */
104         auth->fakelen = 16;
105         for (i = 0; i < 16; i++)
106             auth->fakedata[i] = (i == 8 ? 0 : random_byte());
107     }
108
109     /* Now format for the recipient. */
110     strncpy(proto, x11_authnames[auth->fakeproto], protomaxlen);
111     ourdata[0] = '\0';
112     for (i = 0; i < auth->fakelen; i++)
113         sprintf(ourdata + strlen(ourdata), "%02x", auth->fakedata[i]);
114     strncpy(data, ourdata, datamaxlen);
115
116     return auth;
117 }
118
119 void x11_free_auth(void *auth)
120 {
121
122     sfree(auth);
123 }
124
125 /*
126  * Fetch the real auth data for a given display string, and store
127  * it in an X11Auth structure. Returns NULL on success, or an error
128  * string.
129  */
130 void x11_get_real_auth(void *authv, char *display)
131 {
132     struct X11Auth *auth = (struct X11Auth *)authv;
133
134     auth->realproto = X11_NO_AUTH;     /* in case next call does nothing */
135
136     auth->reallen = sizeof(auth->realdata);
137     platform_get_x11_auth(display, &auth->realproto,
138                           auth->realdata, &auth->reallen);
139 }
140
141 static char *x11_verify(unsigned long peer_ip, int peer_port,
142                         struct X11Auth *auth, char *proto,
143                         unsigned char *data, int dlen)
144 {
145     if (strcmp(proto, x11_authnames[auth->fakeproto]) != 0)
146         return "wrong authentication protocol attempted";
147     if (auth->fakeproto == X11_MIT) {
148         if (dlen != auth->fakelen)
149             return "MIT-MAGIC-COOKIE-1 data was wrong length";
150         if (memcmp(auth->fakedata, data, dlen) != 0)
151             return "MIT-MAGIC-COOKIE-1 data did not match";
152     }
153     if (auth->fakeproto == X11_XDM) {
154         unsigned long t;
155         time_t tim;
156         int i;
157
158         if (dlen != 24)
159             return "XDM-AUTHORIZATION-1 data was wrong length";
160         if (peer_port == -1)
161             return "cannot do XDM-AUTHORIZATION-1 without remote address data";
162         des_decrypt_xdmauth(auth->fakedata+9, data, 24);
163         if (memcmp(auth->fakedata, data, 8) != 0)
164             return "XDM-AUTHORIZATION-1 data failed check"; /* cookie wrong */
165         if (GET_32BIT_MSB_FIRST(data+8) != peer_ip)
166             return "XDM-AUTHORIZATION-1 data failed check";   /* IP wrong */
167         if ((int)GET_16BIT_MSB_FIRST(data+12) != peer_port)
168             return "XDM-AUTHORIZATION-1 data failed check";   /* port wrong */
169         t = GET_32BIT_MSB_FIRST(data+14);
170         for (i = 18; i < 24; i++)
171             if (data[i] != 0)          /* zero padding wrong */
172                 return "XDM-AUTHORIZATION-1 data failed check";
173         tim = time(NULL);
174         if (abs(t - tim) > 20*60)      /* 20 minute clock skew should be OK */
175             return "XDM-AUTHORIZATION-1 time stamp was too far out";
176     }
177     /* implement other protocols here if ever required */
178     return NULL;
179 }
180
181 static int x11_closing(Plug plug, const char *error_msg, int error_code,
182                        int calling_back)
183 {
184     struct X11Private *pr = (struct X11Private *) plug;
185
186     /*
187      * We have no way to communicate down the forwarded connection,
188      * so if an error occurred on the socket, we just ignore it
189      * and treat it like a proper close.
190      */
191     sshfwd_close(pr->c);
192     x11_close(pr->s);
193     return 1;
194 }
195
196 static int x11_receive(Plug plug, int urgent, char *data, int len)
197 {
198     struct X11Private *pr = (struct X11Private *) plug;
199
200     if (sshfwd_write(pr->c, data, len) > 0) {
201         pr->throttled = 1;
202         sk_set_frozen(pr->s, 1);
203     }
204
205     return 1;
206 }
207
208 static void x11_sent(Plug plug, int bufsize)
209 {
210     struct X11Private *pr = (struct X11Private *) plug;
211
212     sshfwd_unthrottle(pr->c, bufsize);
213 }
214
215 /*
216  * When setting up X forwarding, we should send the screen number
217  * from the specified local display. This function extracts it from
218  * the display string.
219  */
220 int x11_get_screen_number(char *display)
221 {
222     int n;
223
224     n = strcspn(display, ":");
225     if (!display[n])
226         return 0;
227     n = strcspn(display, ".");
228     if (!display[n])
229         return 0;
230     return atoi(display + n + 1);
231 }
232
233 /* Find the right display, returns an allocated string */
234 char *x11_display(const char *display) {
235     char *ret;
236     if(!display || !*display) {
237         /* try to find platform-specific local display */
238         if(!(ret = platform_get_x_display()))
239             /* plausible default for all platforms */
240             ret = dupstr(":0");
241     } else
242         ret = dupstr(display);
243     if(ret[0] == ':') {
244         /* no transport specified, use whatever we think is best */
245         char *s = dupcat(platform_x11_best_transport, ret, (char *)0);
246         sfree(ret);
247         return s;
248     } else
249         return ret;
250 }
251
252 /*
253  * Called to set up the raw connection.
254  * 
255  * Returns an error message, or NULL on success.
256  * also, fills the SocketsStructure
257  */
258 const char *x11_init(Socket * s, char *display, void *c, void *auth,
259                      const char *peeraddr, int peerport, const Config *cfg)
260 {
261     static const struct plug_function_table fn_table = {
262         x11_closing,
263         x11_receive,
264         x11_sent,
265         NULL
266     };
267
268     SockAddr addr;
269     int port;
270     const char *err;
271     char *dummy_realhost;
272     char host[128];
273     int n, displaynum;
274     struct X11Private *pr;
275
276     /* default display */
277     display = x11_display(display);
278     /*
279      * Split up display name into host and display-number parts.
280      */
281     n = strcspn(display, ":");
282     assert(n != 0);             /* x11_display() promises this */
283     if (display[n])
284         displaynum = atoi(display + n + 1);
285     else
286         displaynum = 0;                /* sensible default */
287     if (n > sizeof(host) - 1)
288         n = sizeof(host) - 1;
289     strncpy(host, display, n);
290     host[n] = '\0';
291     sfree(display);
292     
293     if(!strcmp(host, "unix")) {
294         /* use AF_UNIX sockets (doesn't make sense on all platforms) */
295         addr = platform_get_x11_unix_address(displaynum,
296                                              &dummy_realhost);
297         port = 0;               /* to show we are not confused */
298     } else {
299         port = 6000 + displaynum;
300         
301         /*
302          * Try to find host.
303          */
304         addr = name_lookup(host, port, &dummy_realhost, cfg, ADDRTYPE_UNSPEC);
305         if ((err = sk_addr_error(addr)) != NULL) {
306             sk_addr_free(addr);
307             return err;
308         }
309     }
310
311     /*
312      * Open socket.
313      */
314     pr = snew(struct X11Private);
315     pr->fn = &fn_table;
316     pr->auth_protocol = NULL;
317     pr->auth = (struct X11Auth *)auth;
318     pr->verified = 0;
319     pr->data_read = 0;
320     pr->throttled = pr->throttle_override = 0;
321     pr->c = c;
322
323     pr->s = *s = new_connection(addr, dummy_realhost, port,
324                                 0, 1, 0, 0, (Plug) pr, cfg);
325     if ((err = sk_socket_error(*s)) != NULL) {
326         sfree(pr);
327         return err;
328     }
329
330     /*
331      * See if we can make sense of the peer address we were given.
332      */
333     {
334         int i[4];
335         if (peeraddr &&
336             4 == sscanf(peeraddr, "%d.%d.%d.%d", i+0, i+1, i+2, i+3)) {
337             pr->peer_ip = (i[0] << 24) | (i[1] << 16) | (i[2] << 8) | i[3];
338             pr->peer_port = peerport;
339         } else {
340             pr->peer_ip = 0;
341             pr->peer_port = -1;
342         }
343     }
344
345     sk_set_private_ptr(*s, pr);
346     return NULL;
347 }
348
349 void x11_close(Socket s)
350 {
351     struct X11Private *pr;
352     if (!s)
353         return;
354     pr = (struct X11Private *) sk_get_private_ptr(s);
355     if (pr->auth_protocol) {
356         sfree(pr->auth_protocol);
357         sfree(pr->auth_data);
358     }
359
360     sfree(pr);
361
362     sk_close(s);
363 }
364
365 void x11_unthrottle(Socket s)
366 {
367     struct X11Private *pr;
368     if (!s)
369         return;
370     pr = (struct X11Private *) sk_get_private_ptr(s);
371
372     pr->throttled = 0;
373     sk_set_frozen(s, pr->throttled || pr->throttle_override);
374 }
375
376 void x11_override_throttle(Socket s, int enable)
377 {
378     struct X11Private *pr;
379     if (!s)
380         return;
381     pr = (struct X11Private *) sk_get_private_ptr(s);
382
383     pr->throttle_override = enable;
384     sk_set_frozen(s, pr->throttled || pr->throttle_override);
385 }
386
387 /*
388  * Called to send data down the raw connection.
389  */
390 int x11_send(Socket s, char *data, int len)
391 {
392     struct X11Private *pr;
393     if (!s)
394         return 0;
395     pr = (struct X11Private *) sk_get_private_ptr(s);
396
397     /*
398      * Read the first packet.
399      */
400     while (len > 0 && pr->data_read < 12)
401         pr->firstpkt[pr->data_read++] = (unsigned char) (len--, *data++);
402     if (pr->data_read < 12)
403         return 0;
404
405     /*
406      * If we have not allocated the auth_protocol and auth_data
407      * strings, do so now.
408      */
409     if (!pr->auth_protocol) {
410         pr->auth_plen = GET_16BIT(pr->firstpkt[0], pr->firstpkt + 6);
411         pr->auth_dlen = GET_16BIT(pr->firstpkt[0], pr->firstpkt + 8);
412         pr->auth_psize = (pr->auth_plen + 3) & ~3;
413         pr->auth_dsize = (pr->auth_dlen + 3) & ~3;
414         /* Leave room for a terminating zero, to make our lives easier. */
415         pr->auth_protocol = snewn(pr->auth_psize + 1, char);
416         pr->auth_data = snewn(pr->auth_dsize, unsigned char);
417     }
418
419     /*
420      * Read the auth_protocol and auth_data strings.
421      */
422     while (len > 0 && pr->data_read < 12 + pr->auth_psize)
423         pr->auth_protocol[pr->data_read++ - 12] = (len--, *data++);
424     while (len > 0 && pr->data_read < 12 + pr->auth_psize + pr->auth_dsize)
425         pr->auth_data[pr->data_read++ - 12 -
426                       pr->auth_psize] = (unsigned char) (len--, *data++);
427     if (pr->data_read < 12 + pr->auth_psize + pr->auth_dsize)
428         return 0;
429
430     /*
431      * If we haven't verified the authentication, do so now.
432      */
433     if (!pr->verified) {
434         char *err;
435
436         pr->auth_protocol[pr->auth_plen] = '\0';        /* ASCIZ */
437         err = x11_verify(pr->peer_ip, pr->peer_port,
438                          pr->auth, pr->auth_protocol,
439                          pr->auth_data, pr->auth_dlen);
440
441         /*
442          * If authentication failed, construct and send an error
443          * packet, then terminate the connection.
444          */
445         if (err) {
446             char *message;
447             int msglen, msgsize;
448             unsigned char *reply;
449
450             message = dupprintf("PuTTY X11 proxy: %s", err);
451             msglen = strlen(message);
452             reply = snewn(8 + msglen+1 + 4, unsigned char); /* include zero */
453             msgsize = (msglen + 3) & ~3;
454             reply[0] = 0;              /* failure */
455             reply[1] = msglen;         /* length of reason string */
456             memcpy(reply + 2, pr->firstpkt + 2, 4);     /* major/minor proto vsn */
457             PUT_16BIT(pr->firstpkt[0], reply + 6, msgsize >> 2);/* data len */
458             memset(reply + 8, 0, msgsize);
459             memcpy(reply + 8, message, msglen);
460             sshfwd_write(pr->c, (char *)reply, 8 + msgsize);
461             sshfwd_close(pr->c);
462             x11_close(s);
463             sfree(reply);
464             sfree(message);
465             return 0;
466         }
467
468         /*
469          * Now we know we're going to accept the connection. Strip
470          * the fake auth data, and optionally put real auth data in
471          * instead.
472          */
473         {
474             char realauthdata[64];
475             int realauthlen = 0;
476             int authstrlen = strlen(x11_authnames[pr->auth->realproto]);
477             unsigned long ip;
478             int port;
479             static const char zeroes[4] = { 0,0,0,0 };
480
481             if (pr->auth->realproto == X11_MIT) {
482                 assert(pr->auth->reallen <= lenof(realauthdata));
483                 realauthlen = pr->auth->reallen;
484                 memcpy(realauthdata, pr->auth->realdata, realauthlen);
485             } else if (pr->auth->realproto == X11_XDM &&
486                        pr->auth->reallen == 16 &&
487                        sk_getxdmdata(s, &ip, &port)) {
488                 time_t t;
489                 realauthlen = 24;
490                 memset(realauthdata, 0, 24);
491                 memcpy(realauthdata, pr->auth->realdata, 8);
492                 PUT_32BIT_MSB_FIRST(realauthdata+8, ip);
493                 PUT_16BIT_MSB_FIRST(realauthdata+12, port);
494                 t = time(NULL);
495                 PUT_32BIT_MSB_FIRST(realauthdata+14, t);
496                 des_encrypt_xdmauth(pr->auth->realdata+9,
497                                     (unsigned char *)realauthdata, 24);
498             }
499             /* implement other auth methods here if required */
500
501             PUT_16BIT(pr->firstpkt[0], pr->firstpkt + 6, authstrlen);
502             PUT_16BIT(pr->firstpkt[0], pr->firstpkt + 8, realauthlen);
503         
504             sk_write(s, (char *)pr->firstpkt, 12);
505
506             if (authstrlen) {
507                 sk_write(s, x11_authnames[pr->auth->realproto], authstrlen);
508                 sk_write(s, zeroes, 3 & (-authstrlen));
509             }
510             if (realauthlen) {
511                 sk_write(s, realauthdata, realauthlen);
512                 sk_write(s, zeroes, 3 & (-realauthlen));
513             }
514         }
515         pr->verified = 1;
516     }
517
518     /*
519      * After initialisation, just copy data simply.
520      */
521
522     return sk_write(s, data, len);
523 }