]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - portfwd.c
Unify GET_32BIT()/PUT_32BIT() et al from numerous source files into misc.h.
[PuTTY.git] / portfwd.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #include "putty.h"
5 #include "ssh.h"
6
7 #ifndef FALSE
8 #define FALSE 0
9 #endif
10 #ifndef TRUE
11 #define TRUE 1
12 #endif
13
14 struct PFwdPrivate {
15     const struct plug_function_table *fn;
16     /* the above variable absolutely *must* be the first in this structure */
17     void *c;                           /* (channel) data used by ssh.c */
18     void *backhandle;                  /* instance of SSH backend itself */
19     /* Note that backhandle need not be filled in if c is non-NULL */
20     Socket s;
21     int throttled, throttle_override;
22     int ready;
23     /*
24      * `dynamic' does double duty. It's set to 0 for an ordinary
25      * forwarded port, and nonzero for SOCKS-style dynamic port
26      * forwarding; but it also represents the state of the SOCKS
27      * exchange.
28      */
29     int dynamic;
30     /*
31      * `hostname' and `port' are the real hostname and port, once
32      * we know what we're connecting to; they're unused for this
33      * purpose while conducting a local SOCKS exchange, which means
34      * we can also use them as a buffer and pointer for reading
35      * data from the SOCKS client.
36      */
37     char hostname[256+8];
38     int port;
39     /*
40      * When doing dynamic port forwarding, we can receive
41      * connection data before we are actually able to send it; so
42      * we may have to temporarily hold some in a dynamically
43      * allocated buffer here.
44      */
45     void *buffer;
46     int buflen;
47 };
48
49 static void pfd_log(Plug plug, int type, SockAddr addr, int port,
50                     const char *error_msg, int error_code)
51 {
52     /* we have to dump these since we have no interface to logging.c */
53 }
54
55 static int pfd_closing(Plug plug, const char *error_msg, int error_code,
56                        int calling_back)
57 {
58     struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
59
60     /*
61      * We have no way to communicate down the forwarded connection,
62      * so if an error occurred on the socket, we just ignore it
63      * and treat it like a proper close.
64      */
65     if (pr->c)
66         sshfwd_close(pr->c);
67     pfd_close(pr->s);
68     return 1;
69 }
70
71 static int pfd_receive(Plug plug, int urgent, char *data, int len)
72 {
73     struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
74     if (pr->dynamic) {
75         while (len--) {
76             /*
77              * Throughout SOCKS negotiation, "hostname" is re-used as a
78              * random protocol buffer with "port" storing the length.
79              */ 
80             if (pr->port >= lenof(pr->hostname)) {
81                 /* Request too long. */
82                 if ((pr->dynamic >> 12) == 4) {
83                     /* Send back a SOCKS 4 error before closing. */
84                     char data[8];
85                     memset(data, 0, sizeof(data));
86                     data[1] = 91;      /* generic `request rejected' */
87                     sk_write(pr->s, data, 8);
88                 }
89                 pfd_close(pr->s);
90                 return 1;
91             }
92             pr->hostname[pr->port++] = *data++;
93
94             /*
95              * Now check what's in the buffer to see if it's a
96              * valid and complete message in the SOCKS exchange.
97              */
98             if ((pr->dynamic == 1 || (pr->dynamic >> 12) == 4) &&
99                 pr->hostname[0] == 4) {
100                 /*
101                  * SOCKS 4.
102                  */
103                 if (pr->dynamic == 1)
104                     pr->dynamic = 0x4000;
105                 if (pr->port < 2) continue;/* don't have command code yet */
106                 if (pr->hostname[1] != 1) {
107                     /* Not CONNECT. */
108                     /* Send back a SOCKS 4 error before closing. */
109                     char data[8];
110                     memset(data, 0, sizeof(data));
111                     data[1] = 91;      /* generic `request rejected' */
112                     sk_write(pr->s, data, 8);
113                     pfd_close(pr->s);
114                     return 1;
115                 }
116                 if (pr->port <= 8) continue; /* haven't started user/hostname */
117                 if (pr->hostname[pr->port-1] != 0)
118                     continue;          /* haven't _finished_ user/hostname */
119                 /*
120                  * Now we have a full SOCKS 4 request. Check it to
121                  * see if it's a SOCKS 4A request.
122                  */
123                 if (pr->hostname[4] == 0 && pr->hostname[5] == 0 &&
124                     pr->hostname[6] == 0 && pr->hostname[7] != 0) {
125                     /*
126                      * It's SOCKS 4A. So if we haven't yet
127                      * collected the host name, we should continue
128                      * waiting for data in order to do so; if we
129                      * have, we can go ahead.
130                      */
131                     int len;
132                     if (pr->dynamic == 0x4000) {
133                         pr->dynamic = 0x4001;
134                         pr->port = 8;      /* reset buffer to overwrite name */
135                         continue;
136                     }
137                     pr->hostname[0] = 0;   /* reply version code */
138                     pr->hostname[1] = 90;   /* request granted */
139                     sk_write(pr->s, pr->hostname, 8);
140                     len= pr->port - 8;
141                     pr->port = GET_16BIT_MSB_FIRST(pr->hostname+2);
142                     memmove(pr->hostname, pr->hostname + 8, len);
143                     goto connect;
144                 } else {
145                     /*
146                      * It's SOCKS 4, which means we should format
147                      * the IP address into the hostname string and
148                      * then just go.
149                      */
150                     pr->hostname[0] = 0;   /* reply version code */
151                     pr->hostname[1] = 90;   /* request granted */
152                     sk_write(pr->s, pr->hostname, 8);
153                     pr->port = GET_16BIT_MSB_FIRST(pr->hostname+2);
154                     sprintf(pr->hostname, "%d.%d.%d.%d",
155                             (unsigned char)pr->hostname[4],
156                             (unsigned char)pr->hostname[5],
157                             (unsigned char)pr->hostname[6],
158                             (unsigned char)pr->hostname[7]);
159                     goto connect;
160                 }
161             }
162
163             if ((pr->dynamic == 1 || (pr->dynamic >> 12) == 5) &&
164                 pr->hostname[0] == 5) {
165                 /*
166                  * SOCKS 5.
167                  */
168                 if (pr->dynamic == 1)
169                     pr->dynamic = 0x5000;
170
171                 if (pr->dynamic == 0x5000) {
172                     int i, method;
173                     char data[2];
174                     /*
175                      * We're receiving a set of method identifiers.
176                      */
177                     if (pr->port < 2) continue;/* no method count yet */
178                     if (pr->port < 2 + (unsigned char)pr->hostname[1])
179                         continue;      /* no methods yet */
180                     method = 0xFF;     /* invalid */
181                     for (i = 0; i < (unsigned char)pr->hostname[1]; i++)
182                         if (pr->hostname[2+i] == 0) {
183                             method = 0;/* no auth */
184                             break;
185                         }
186                     data[0] = 5;
187                     data[1] = method;
188                     sk_write(pr->s, data, 2);
189                     pr->dynamic = 0x5001;
190                     pr->port = 0;      /* re-empty the buffer */
191                     continue;
192                 }
193
194                 if (pr->dynamic == 0x5001) {
195                     /*
196                      * We're receiving a SOCKS request.
197                      */
198                     unsigned char reply[10]; /* SOCKS5 atyp=1 reply */
199                     int atype, alen = 0;
200
201                     /*
202                      * Pre-fill reply packet.
203                      * In all cases, we set BND.{HOST,ADDR} to 0.0.0.0:0
204                      * (atyp=1) in the reply; if we succeed, we don't know
205                      * the right answers, and if we fail, they should be
206                      * ignored.
207                      */
208                     memset(reply, 0, lenof(reply));
209                     reply[0] = 5; /* VER */
210                     reply[3] = 1; /* ATYP = 1 (IPv4, 0.0.0.0:0) */
211
212                     if (pr->port < 6) continue;
213                     atype = (unsigned char)pr->hostname[3];
214                     if (atype == 1)    /* IPv4 address */
215                         alen = 4;
216                     if (atype == 4)    /* IPv6 address */
217                         alen = 16;
218                     if (atype == 3)    /* domain name has leading length */
219                         alen = 1 + (unsigned char)pr->hostname[4];
220                     if (pr->port < 6 + alen) continue;
221                     if (pr->hostname[1] != 1 || pr->hostname[2] != 0) {
222                         /* Not CONNECT or reserved field nonzero - error */
223                         reply[1] = 1;   /* generic failure */
224                         sk_write(pr->s, (char *) reply, lenof(reply));
225                         pfd_close(pr->s);
226                         return 1;
227                     }
228                     /*
229                      * Now we have a viable connect request. Switch
230                      * on atype.
231                      */
232                     pr->port = GET_16BIT_MSB_FIRST(pr->hostname+4+alen);
233                     if (atype == 1) {
234                         /* REP=0 (success) already */
235                         sk_write(pr->s, (char *) reply, lenof(reply));
236                         sprintf(pr->hostname, "%d.%d.%d.%d",
237                                 (unsigned char)pr->hostname[4],
238                                 (unsigned char)pr->hostname[5],
239                                 (unsigned char)pr->hostname[6],
240                                 (unsigned char)pr->hostname[7]);
241                         goto connect;
242                     } else if (atype == 3) {
243                         /* REP=0 (success) already */
244                         sk_write(pr->s, (char *) reply, lenof(reply));
245                         memmove(pr->hostname, pr->hostname + 5, alen-1);
246                         pr->hostname[alen-1] = '\0';
247                         goto connect;
248                     } else {
249                         /*
250                          * Unknown address type. (FIXME: support IPv6!)
251                          */
252                         reply[1] = 8;   /* atype not supported */
253                         sk_write(pr->s, (char *) reply, lenof(reply));
254                         pfd_close(pr->s);
255                         return 1;
256                     }
257                 }
258             }
259
260             /*
261              * If we get here without either having done `continue'
262              * or `goto connect', it must be because there is no
263              * sensible interpretation of what's in our buffer. So
264              * close the connection rudely.
265              */
266             pfd_close(pr->s);
267             return 1;
268         }
269         return 1;
270
271         /*
272          * We come here when we're ready to make an actual
273          * connection.
274          */
275         connect:
276
277         pr->c = new_sock_channel(pr->backhandle, pr->s);
278         if (pr->c == NULL) {
279             pfd_close(pr->s);
280             return 1;
281         } else {
282             /* asks to forward to the specified host/port for this */
283             ssh_send_port_open(pr->c, pr->hostname, pr->port, "forwarding");
284         }
285         pr->dynamic = 0;
286
287         /*
288          * Now freeze the socket until the SSH server confirms the
289          * connection.
290          */
291         sk_set_frozen(pr->s, 1);
292         /*
293          * If there's any data remaining in our current buffer,
294          * save it to be sent on pfd_confirm().
295          */
296         if (len > 0) {
297             pr->buffer = snewn(len, char);
298             memcpy(pr->buffer, data, len);
299             pr->buflen = len;
300         }
301     }
302     if (pr->ready) {
303         if (sshfwd_write(pr->c, data, len) > 0) {
304             pr->throttled = 1;
305             sk_set_frozen(pr->s, 1);
306         }
307     }
308     return 1;
309 }
310
311 static void pfd_sent(Plug plug, int bufsize)
312 {
313     struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
314
315     if (pr->c)
316         sshfwd_unthrottle(pr->c, bufsize);
317 }
318
319 /*
320  * Called when receiving a PORT OPEN from the server
321  */
322 const char *pfd_newconnect(Socket *s, char *hostname, int port,
323                            void *c, const Config *cfg, int addressfamily)
324 {
325     static const struct plug_function_table fn_table = {
326         pfd_log,
327         pfd_closing,
328         pfd_receive,
329         pfd_sent,
330         NULL
331     };
332
333     SockAddr addr;
334     const char *err;
335     char *dummy_realhost;
336     struct PFwdPrivate *pr;
337
338     /*
339      * Try to find host.
340      */
341     addr = name_lookup(hostname, port, &dummy_realhost, cfg, addressfamily);
342     if ((err = sk_addr_error(addr)) != NULL) {
343         sk_addr_free(addr);
344         return err;
345     }
346
347     /*
348      * Open socket.
349      */
350     pr = snew(struct PFwdPrivate);
351     pr->buffer = NULL;
352     pr->fn = &fn_table;
353     pr->throttled = pr->throttle_override = 0;
354     pr->ready = 1;
355     pr->c = c;
356     pr->backhandle = NULL;             /* we shouldn't need this */
357     pr->dynamic = 0;
358
359     pr->s = *s = new_connection(addr, dummy_realhost, port,
360                                 0, 1, 0, 0, (Plug) pr, cfg);
361     if ((err = sk_socket_error(*s)) != NULL) {
362         sfree(pr);
363         return err;
364     }
365
366     sk_set_private_ptr(*s, pr);
367     return NULL;
368 }
369
370 /*
371  called when someone connects to the local port
372  */
373
374 static int pfd_accepting(Plug p, OSSocket sock)
375 {
376     static const struct plug_function_table fn_table = {
377         pfd_log,
378         pfd_closing,
379         pfd_receive,
380         pfd_sent,
381         NULL
382     };
383     struct PFwdPrivate *pr, *org;
384     Socket s;
385     const char *err;
386
387     org = (struct PFwdPrivate *)p;
388     pr = snew(struct PFwdPrivate);
389     pr->buffer = NULL;
390     pr->fn = &fn_table;
391
392     pr->c = NULL;
393     pr->backhandle = org->backhandle;
394
395     pr->s = s = sk_register(sock, (Plug) pr);
396     if ((err = sk_socket_error(s)) != NULL) {
397         sfree(pr);
398         return err != NULL;
399     }
400
401     sk_set_private_ptr(s, pr);
402
403     pr->throttled = pr->throttle_override = 0;
404     pr->ready = 0;
405
406     if (org->dynamic) {
407         pr->dynamic = 1;
408         pr->port = 0;                  /* "hostname" buffer is so far empty */
409         sk_set_frozen(s, 0);           /* we want to receive SOCKS _now_! */
410     } else {
411         pr->dynamic = 0;
412         strcpy(pr->hostname, org->hostname);
413         pr->port = org->port;   
414         pr->c = new_sock_channel(org->backhandle, s);
415
416         if (pr->c == NULL) {
417             sfree(pr);
418             return 1;
419         } else {
420             /* asks to forward to the specified host/port for this */
421             ssh_send_port_open(pr->c, pr->hostname, pr->port, "forwarding");
422         }
423     }
424
425     return 0;
426 }
427
428
429 /* Add a new forwarding from port -> desthost:destport
430  sets up a listener on the local machine on (srcaddr:)port
431  */
432 const char *pfd_addforward(char *desthost, int destport, char *srcaddr,
433                            int port, void *backhandle, const Config *cfg,
434                            void **sockdata, int address_family)
435 {
436     static const struct plug_function_table fn_table = {
437         pfd_log,
438         pfd_closing,
439         pfd_receive,                   /* should not happen... */
440         pfd_sent,                      /* also should not happen */
441         pfd_accepting
442     };
443
444     const char *err;
445     struct PFwdPrivate *pr;
446     Socket s;
447
448     /*
449      * Open socket.
450      */
451     pr = snew(struct PFwdPrivate);
452     pr->buffer = NULL;
453     pr->fn = &fn_table;
454     pr->c = NULL;
455     if (desthost) {
456         strcpy(pr->hostname, desthost);
457         pr->port = destport;
458         pr->dynamic = 0;
459     } else
460         pr->dynamic = 1;
461     pr->throttled = pr->throttle_override = 0;
462     pr->ready = 0;
463     pr->backhandle = backhandle;
464
465     pr->s = s = new_listener(srcaddr, port, (Plug) pr,
466                              !cfg->lport_acceptall, cfg, address_family);
467     if ((err = sk_socket_error(s)) != NULL) {
468         sfree(pr);
469         return err;
470     }
471
472     sk_set_private_ptr(s, pr);
473
474     *sockdata = (void *)s;
475
476     return NULL;
477 }
478
479 void pfd_close(Socket s)
480 {
481     struct PFwdPrivate *pr;
482
483     if (!s)
484         return;
485
486     pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
487
488     sfree(pr->buffer);
489     sfree(pr);
490
491     sk_close(s);
492 }
493
494 /*
495  * Terminate a listener.
496  */
497 void pfd_terminate(void *sv)
498 {
499     pfd_close((Socket)sv);
500 }
501
502 void pfd_unthrottle(Socket s)
503 {
504     struct PFwdPrivate *pr;
505     if (!s)
506         return;
507     pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
508
509     pr->throttled = 0;
510     sk_set_frozen(s, pr->throttled || pr->throttle_override);
511 }
512
513 void pfd_override_throttle(Socket s, int enable)
514 {
515     struct PFwdPrivate *pr;
516     if (!s)
517         return;
518     pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
519
520     pr->throttle_override = enable;
521     sk_set_frozen(s, pr->throttled || pr->throttle_override);
522 }
523
524 /*
525  * Called to send data down the raw connection.
526  */
527 int pfd_send(Socket s, char *data, int len)
528 {
529     if (s == NULL)
530         return 0;
531     return sk_write(s, data, len);
532 }
533
534
535 void pfd_confirm(Socket s)
536 {
537     struct PFwdPrivate *pr;
538
539     if (s == NULL)
540         return;
541
542     pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
543     pr->ready = 1;
544     sk_set_frozen(s, 0);
545     sk_write(s, NULL, 0);
546     if (pr->buffer) {
547         sshfwd_write(pr->c, pr->buffer, pr->buflen);
548         sfree(pr->buffer);
549         pr->buffer = NULL;
550     }
551 }