]> andersk Git - gssapi-openssh.git/blob - openssh/channels.c
openssh-4.3p2-hpn12.diff
[gssapi-openssh.git] / openssh / channels.c
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * This file contains functions for generic socket connection forwarding.
6  * There is also code for initiating connection forwarding for X11 connections,
7  * arbitrary tcp/ip connections, and the authentication agent connection.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  * SSH2 support added by Markus Friedl.
16  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
17  * Copyright (c) 1999 Dug Song.  All rights reserved.
18  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39  */
40
41 #include "includes.h"
42 RCSID("$OpenBSD: channels.c,v 1.232 2006/01/30 12:22:22 reyk Exp $");
43
44 #include "ssh.h"
45 #include "ssh1.h"
46 #include "ssh2.h"
47 #include "packet.h"
48 #include "xmalloc.h"
49 #include "log.h"
50 #include "misc.h"
51 #include "channels.h"
52 #include "compat.h"
53 #include "canohost.h"
54 #include "key.h"
55 #include "authfd.h"
56 #include "pathnames.h"
57 #include "bufaux.h"
58
59
60 /* -- channel core */
61
62 /*
63  * Pointer to an array containing all allocated channels.  The array is
64  * dynamically extended as needed.
65  */
66 static Channel **channels = NULL;
67
68 /*
69  * Size of the channel array.  All slots of the array must always be
70  * initialized (at least the type field); unused slots set to NULL
71  */
72 static u_int channels_alloc = 0;
73
74 /*
75  * Maximum file descriptor value used in any of the channels.  This is
76  * updated in channel_new.
77  */
78 static int channel_max_fd = 0;
79
80
81 /* -- tcp forwarding */
82
83 /*
84  * Data structure for storing which hosts are permitted for forward requests.
85  * The local sides of any remote forwards are stored in this array to prevent
86  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
87  * network (which might be behind a firewall).
88  */
89 typedef struct {
90         char *host_to_connect;          /* Connect to 'host'. */
91         u_short port_to_connect;        /* Connect to 'port'. */
92         u_short listen_port;            /* Remote side should listen port number. */
93 } ForwardPermission;
94
95 /* List of all permitted host/port pairs to connect. */
96 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
97
98 /* Number of permitted host/port pairs in the array. */
99 static int num_permitted_opens = 0;
100 /*
101  * If this is true, all opens are permitted.  This is the case on the server
102  * on which we have to trust the client anyway, and the user could do
103  * anything after logging in anyway.
104  */
105 static int all_opens_permitted = 0;
106
107
108 /* -- X11 forwarding */
109
110 /* Maximum number of fake X11 displays to try. */
111 #define MAX_DISPLAYS  1000
112
113 /* Saved X11 local (client) display. */
114 static char *x11_saved_display = NULL;
115
116 /* Saved X11 authentication protocol name. */
117 static char *x11_saved_proto = NULL;
118
119 /* Saved X11 authentication data.  This is the real data. */
120 static char *x11_saved_data = NULL;
121 static u_int x11_saved_data_len = 0;
122
123 /*
124  * Fake X11 authentication data.  This is what the server will be sending us;
125  * we should replace any occurrences of this by the real data.
126  */
127 static char *x11_fake_data = NULL;
128 static u_int x11_fake_data_len;
129
130
131 /* -- agent forwarding */
132
133 #define NUM_SOCKS       10
134
135 /* AF_UNSPEC or AF_INET or AF_INET6 */
136 static int IPv4or6 = AF_UNSPEC;
137
138 /* helper */
139 static void port_open_helper(Channel *c, char *rtype);
140
141 /* -- channel core */
142
143 Channel *
144 channel_by_id(int id)
145 {
146         Channel *c;
147
148         if (id < 0 || (u_int)id >= channels_alloc) {
149                 logit("channel_by_id: %d: bad id", id);
150                 return NULL;
151         }
152         c = channels[id];
153         if (c == NULL) {
154                 logit("channel_by_id: %d: bad id: channel free", id);
155                 return NULL;
156         }
157         return c;
158 }
159
160 /*
161  * Returns the channel if it is allowed to receive protocol messages.
162  * Private channels, like listening sockets, may not receive messages.
163  */
164 Channel *
165 channel_lookup(int id)
166 {
167         Channel *c;
168
169         if ((c = channel_by_id(id)) == NULL)
170                 return (NULL);
171
172         switch(c->type) {
173         case SSH_CHANNEL_X11_OPEN:
174         case SSH_CHANNEL_LARVAL:
175         case SSH_CHANNEL_CONNECTING:
176         case SSH_CHANNEL_DYNAMIC:
177         case SSH_CHANNEL_OPENING:
178         case SSH_CHANNEL_OPEN:
179         case SSH_CHANNEL_INPUT_DRAINING:
180         case SSH_CHANNEL_OUTPUT_DRAINING:
181                 return (c);
182                 break;
183         }
184         logit("Non-public channel %d, type %d.", id, c->type);
185         return (NULL);
186 }
187
188 /*
189  * Register filedescriptors for a channel, used when allocating a channel or
190  * when the channel consumer/producer is ready, e.g. shell exec'd
191  */
192
193 static void
194 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
195     int extusage, int nonblock)
196 {
197         /* Update the maximum file descriptor value. */
198         channel_max_fd = MAX(channel_max_fd, rfd);
199         channel_max_fd = MAX(channel_max_fd, wfd);
200         channel_max_fd = MAX(channel_max_fd, efd);
201
202         /* XXX set close-on-exec -markus */
203
204         c->rfd = rfd;
205         c->wfd = wfd;
206         c->sock = (rfd == wfd) ? rfd : -1;
207         c->ctl_fd = -1; /* XXX: set elsewhere */
208         c->efd = efd;
209         c->extended_usage = extusage;
210
211         /* XXX ugly hack: nonblock is only set by the server */
212         if (nonblock && isatty(c->rfd)) {
213                 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
214                 c->isatty = 1;
215                 if (!isatty(c->wfd)) {
216                         error("channel %d: wfd %d is not a tty?",
217                             c->self, c->wfd);
218                 }
219         } else {
220                 c->isatty = 0;
221         }
222         c->wfd_isatty = isatty(c->wfd);
223
224         /* enable nonblocking mode */
225         if (nonblock) {
226                 if (rfd != -1)
227                         set_nonblock(rfd);
228                 if (wfd != -1)
229                         set_nonblock(wfd);
230                 if (efd != -1)
231                         set_nonblock(efd);
232         }
233 }
234
235 /*
236  * Allocate a new channel object and set its type and socket. This will cause
237  * remote_name to be freed.
238  */
239
240 Channel *
241 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
242     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
243 {
244         int found;
245         u_int i;
246         Channel *c;
247
248         /* Do initial allocation if this is the first call. */
249         if (channels_alloc == 0) {
250                 channels_alloc = 10;
251                 channels = xmalloc(channels_alloc * sizeof(Channel *));
252                 for (i = 0; i < channels_alloc; i++)
253                         channels[i] = NULL;
254         }
255         /* Try to find a free slot where to put the new channel. */
256         for (found = -1, i = 0; i < channels_alloc; i++)
257                 if (channels[i] == NULL) {
258                         /* Found a free slot. */
259                         found = (int)i;
260                         break;
261                 }
262         if (found < 0) {
263                 /* There are no free slots.  Take last+1 slot and expand the array.  */
264                 found = channels_alloc;
265                 if (channels_alloc > 10000)
266                         fatal("channel_new: internal error: channels_alloc %d "
267                             "too big.", channels_alloc);
268                 channels = xrealloc(channels,
269                     (channels_alloc + 10) * sizeof(Channel *));
270                 channels_alloc += 10;
271                 debug2("channel: expanding %d", channels_alloc);
272                 for (i = found; i < channels_alloc; i++)
273                         channels[i] = NULL;
274         }
275         /* Initialize and return new channel. */
276         c = channels[found] = xmalloc(sizeof(Channel));
277         memset(c, 0, sizeof(Channel));
278         buffer_init(&c->input);
279         buffer_init(&c->output);
280         buffer_init(&c->extended);
281         c->ostate = CHAN_OUTPUT_OPEN;
282         c->istate = CHAN_INPUT_OPEN;
283         c->flags = 0;
284         channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
285         c->self = found;
286         c->type = type;
287         c->ctype = ctype;
288         c->local_window = window;
289         c->local_window_max = window;
290         c->local_consumed = 0;
291         c->local_maxpacket = maxpack;
292         c->dynamic_window = 0;
293         c->remote_id = -1;
294         c->remote_name = xstrdup(remote_name);
295         c->remote_window = 0;
296         c->remote_maxpacket = 0;
297         c->force_drain = 0;
298         c->single_connection = 0;
299         c->detach_user = NULL;
300         c->detach_close = 0;
301         c->confirm = NULL;
302         c->confirm_ctx = NULL;
303         c->input_filter = NULL;
304         c->output_filter = NULL;
305         debug("channel %d: new [%s]", found, remote_name);
306         return c;
307 }
308
309 static int
310 channel_find_maxfd(void)
311 {
312         u_int i;
313         int max = 0;
314         Channel *c;
315
316         for (i = 0; i < channels_alloc; i++) {
317                 c = channels[i];
318                 if (c != NULL) {
319                         max = MAX(max, c->rfd);
320                         max = MAX(max, c->wfd);
321                         max = MAX(max, c->efd);
322                 }
323         }
324         return max;
325 }
326
327 int
328 channel_close_fd(int *fdp)
329 {
330         int ret = 0, fd = *fdp;
331
332         if (fd != -1) {
333                 ret = close(fd);
334                 *fdp = -1;
335                 if (fd == channel_max_fd)
336                         channel_max_fd = channel_find_maxfd();
337         }
338         return ret;
339 }
340
341 /* Close all channel fd/socket. */
342
343 static void
344 channel_close_fds(Channel *c)
345 {
346         debug3("channel %d: close_fds r %d w %d e %d c %d",
347             c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
348
349         channel_close_fd(&c->sock);
350         channel_close_fd(&c->ctl_fd);
351         channel_close_fd(&c->rfd);
352         channel_close_fd(&c->wfd);
353         channel_close_fd(&c->efd);
354 }
355
356 /* Free the channel and close its fd/socket. */
357
358 void
359 channel_free(Channel *c)
360 {
361         char *s;
362         u_int i, n;
363
364         for (n = 0, i = 0; i < channels_alloc; i++)
365                 if (channels[i])
366                         n++;
367         debug("channel %d: free: %s, nchannels %u", c->self,
368             c->remote_name ? c->remote_name : "???", n);
369
370         s = channel_open_message();
371         debug3("channel %d: status: %s", c->self, s);
372         xfree(s);
373
374         if (c->sock != -1)
375                 shutdown(c->sock, SHUT_RDWR);
376         if (c->ctl_fd != -1)
377                 shutdown(c->ctl_fd, SHUT_RDWR);
378         channel_close_fds(c);
379         buffer_free(&c->input);
380         buffer_free(&c->output);
381         buffer_free(&c->extended);
382         if (c->remote_name) {
383                 xfree(c->remote_name);
384                 c->remote_name = NULL;
385         }
386         channels[c->self] = NULL;
387         xfree(c);
388 }
389
390 void
391 channel_free_all(void)
392 {
393         u_int i;
394
395         for (i = 0; i < channels_alloc; i++)
396                 if (channels[i] != NULL)
397                         channel_free(channels[i]);
398 }
399
400 /*
401  * Closes the sockets/fds of all channels.  This is used to close extra file
402  * descriptors after a fork.
403  */
404
405 void
406 channel_close_all(void)
407 {
408         u_int i;
409
410         for (i = 0; i < channels_alloc; i++)
411                 if (channels[i] != NULL)
412                         channel_close_fds(channels[i]);
413 }
414
415 /*
416  * Stop listening to channels.
417  */
418
419 void
420 channel_stop_listening(void)
421 {
422         u_int i;
423         Channel *c;
424
425         for (i = 0; i < channels_alloc; i++) {
426                 c = channels[i];
427                 if (c != NULL) {
428                         switch (c->type) {
429                         case SSH_CHANNEL_AUTH_SOCKET:
430                         case SSH_CHANNEL_PORT_LISTENER:
431                         case SSH_CHANNEL_RPORT_LISTENER:
432                         case SSH_CHANNEL_X11_LISTENER:
433                                 channel_close_fd(&c->sock);
434                                 channel_free(c);
435                                 break;
436                         }
437                 }
438         }
439 }
440
441 /*
442  * Returns true if no channel has too much buffered data, and false if one or
443  * more channel is overfull.
444  */
445
446 int
447 channel_not_very_much_buffered_data(void)
448 {
449         u_int i;
450         Channel *c;
451
452         for (i = 0; i < channels_alloc; i++) {
453                 c = channels[i];
454                 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
455 #if 0
456                         if (!compat20 &&
457                             buffer_len(&c->input) > packet_get_maxsize()) {
458                                 debug2("channel %d: big input buffer %d",
459                                     c->self, buffer_len(&c->input));
460                                 return 0;
461                         }
462 #endif
463                         if (buffer_len(&c->output) > packet_get_maxsize()) {
464                                 debug2("channel %d: big output buffer %u > %u",
465                                     c->self, buffer_len(&c->output),
466                                     packet_get_maxsize());
467                                 return 0;
468                         }
469                 }
470         }
471         return 1;
472 }
473
474 /* Returns true if any channel is still open. */
475
476 int
477 channel_still_open(void)
478 {
479         u_int i;
480         Channel *c;
481
482         for (i = 0; i < channels_alloc; i++) {
483                 c = channels[i];
484                 if (c == NULL)
485                         continue;
486                 switch (c->type) {
487                 case SSH_CHANNEL_X11_LISTENER:
488                 case SSH_CHANNEL_PORT_LISTENER:
489                 case SSH_CHANNEL_RPORT_LISTENER:
490                 case SSH_CHANNEL_CLOSED:
491                 case SSH_CHANNEL_AUTH_SOCKET:
492                 case SSH_CHANNEL_DYNAMIC:
493                 case SSH_CHANNEL_CONNECTING:
494                 case SSH_CHANNEL_ZOMBIE:
495                         continue;
496                 case SSH_CHANNEL_LARVAL:
497                         if (!compat20)
498                                 fatal("cannot happen: SSH_CHANNEL_LARVAL");
499                         continue;
500                 case SSH_CHANNEL_OPENING:
501                 case SSH_CHANNEL_OPEN:
502                 case SSH_CHANNEL_X11_OPEN:
503                         return 1;
504                 case SSH_CHANNEL_INPUT_DRAINING:
505                 case SSH_CHANNEL_OUTPUT_DRAINING:
506                         if (!compat13)
507                                 fatal("cannot happen: OUT_DRAIN");
508                         return 1;
509                 default:
510                         fatal("channel_still_open: bad channel type %d", c->type);
511                         /* NOTREACHED */
512                 }
513         }
514         return 0;
515 }
516
517 /* Returns the id of an open channel suitable for keepaliving */
518
519 int
520 channel_find_open(void)
521 {
522         u_int i;
523         Channel *c;
524
525         for (i = 0; i < channels_alloc; i++) {
526                 c = channels[i];
527                 if (c == NULL || c->remote_id < 0)
528                         continue;
529                 switch (c->type) {
530                 case SSH_CHANNEL_CLOSED:
531                 case SSH_CHANNEL_DYNAMIC:
532                 case SSH_CHANNEL_X11_LISTENER:
533                 case SSH_CHANNEL_PORT_LISTENER:
534                 case SSH_CHANNEL_RPORT_LISTENER:
535                 case SSH_CHANNEL_OPENING:
536                 case SSH_CHANNEL_CONNECTING:
537                 case SSH_CHANNEL_ZOMBIE:
538                         continue;
539                 case SSH_CHANNEL_LARVAL:
540                 case SSH_CHANNEL_AUTH_SOCKET:
541                 case SSH_CHANNEL_OPEN:
542                 case SSH_CHANNEL_X11_OPEN:
543                         return i;
544                 case SSH_CHANNEL_INPUT_DRAINING:
545                 case SSH_CHANNEL_OUTPUT_DRAINING:
546                         if (!compat13)
547                                 fatal("cannot happen: OUT_DRAIN");
548                         return i;
549                 default:
550                         fatal("channel_find_open: bad channel type %d", c->type);
551                         /* NOTREACHED */
552                 }
553         }
554         return -1;
555 }
556
557
558 /*
559  * Returns a message describing the currently open forwarded connections,
560  * suitable for sending to the client.  The message contains crlf pairs for
561  * newlines.
562  */
563
564 char *
565 channel_open_message(void)
566 {
567         Buffer buffer;
568         Channel *c;
569         char buf[1024], *cp;
570         u_int i;
571
572         buffer_init(&buffer);
573         snprintf(buf, sizeof buf, "The following connections are open:\r\n");
574         buffer_append(&buffer, buf, strlen(buf));
575         for (i = 0; i < channels_alloc; i++) {
576                 c = channels[i];
577                 if (c == NULL)
578                         continue;
579                 switch (c->type) {
580                 case SSH_CHANNEL_X11_LISTENER:
581                 case SSH_CHANNEL_PORT_LISTENER:
582                 case SSH_CHANNEL_RPORT_LISTENER:
583                 case SSH_CHANNEL_CLOSED:
584                 case SSH_CHANNEL_AUTH_SOCKET:
585                 case SSH_CHANNEL_ZOMBIE:
586                         continue;
587                 case SSH_CHANNEL_LARVAL:
588                 case SSH_CHANNEL_OPENING:
589                 case SSH_CHANNEL_CONNECTING:
590                 case SSH_CHANNEL_DYNAMIC:
591                 case SSH_CHANNEL_OPEN:
592                 case SSH_CHANNEL_X11_OPEN:
593                 case SSH_CHANNEL_INPUT_DRAINING:
594                 case SSH_CHANNEL_OUTPUT_DRAINING:
595                         snprintf(buf, sizeof buf,
596                             "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
597                             c->self, c->remote_name,
598                             c->type, c->remote_id,
599                             c->istate, buffer_len(&c->input),
600                             c->ostate, buffer_len(&c->output),
601                             c->rfd, c->wfd, c->ctl_fd);
602                         buffer_append(&buffer, buf, strlen(buf));
603                         continue;
604                 default:
605                         fatal("channel_open_message: bad channel type %d", c->type);
606                         /* NOTREACHED */
607                 }
608         }
609         buffer_append(&buffer, "\0", 1);
610         cp = xstrdup(buffer_ptr(&buffer));
611         buffer_free(&buffer);
612         return cp;
613 }
614
615 void
616 channel_send_open(int id)
617 {
618         Channel *c = channel_lookup(id);
619
620         if (c == NULL) {
621                 logit("channel_send_open: %d: bad id", id);
622                 return;
623         }
624         debug2("channel %d: send open", id);
625         packet_start(SSH2_MSG_CHANNEL_OPEN);
626         packet_put_cstring(c->ctype);
627         packet_put_int(c->self);
628         packet_put_int(c->local_window);
629         packet_put_int(c->local_maxpacket);
630         packet_send();
631 }
632
633 void
634 channel_request_start(int id, char *service, int wantconfirm)
635 {
636         Channel *c = channel_lookup(id);
637
638         if (c == NULL) {
639                 logit("channel_request_start: %d: unknown channel id", id);
640                 return;
641         }
642         debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
643         packet_start(SSH2_MSG_CHANNEL_REQUEST);
644         packet_put_int(c->remote_id);
645         packet_put_cstring(service);
646         packet_put_char(wantconfirm);
647 }
648 void
649 channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
650 {
651         Channel *c = channel_lookup(id);
652
653         if (c == NULL) {
654                 logit("channel_register_comfirm: %d: bad id", id);
655                 return;
656         }
657         c->confirm = fn;
658         c->confirm_ctx = ctx;
659 }
660 void
661 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
662 {
663         Channel *c = channel_by_id(id);
664
665         if (c == NULL) {
666                 logit("channel_register_cleanup: %d: bad id", id);
667                 return;
668         }
669         c->detach_user = fn;
670         c->detach_close = do_close;
671 }
672 void
673 channel_cancel_cleanup(int id)
674 {
675         Channel *c = channel_by_id(id);
676
677         if (c == NULL) {
678                 logit("channel_cancel_cleanup: %d: bad id", id);
679                 return;
680         }
681         c->detach_user = NULL;
682         c->detach_close = 0;
683 }
684 void
685 channel_register_filter(int id, channel_infilter_fn *ifn,
686     channel_outfilter_fn *ofn)
687 {
688         Channel *c = channel_lookup(id);
689
690         if (c == NULL) {
691                 logit("channel_register_filter: %d: bad id", id);
692                 return;
693         }
694         c->input_filter = ifn;
695         c->output_filter = ofn;
696 }
697
698 void
699 channel_set_fds(int id, int rfd, int wfd, int efd,
700     int extusage, int nonblock, u_int window_max)
701 {
702         Channel *c = channel_lookup(id);
703
704         if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
705                 fatal("channel_activate for non-larval channel %d.", id);
706         channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
707         c->type = SSH_CHANNEL_OPEN;
708         c->local_window = c->local_window_max = window_max;
709         packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
710         packet_put_int(c->remote_id);
711         packet_put_int(c->local_window);
712         packet_send();
713 }
714
715 /*
716  * 'channel_pre*' are called just before select() to add any bits relevant to
717  * channels in the select bitmasks.
718  */
719 /*
720  * 'channel_post*': perform any appropriate operations for channels which
721  * have events pending.
722  */
723 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
724 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
725 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
726
727 static void
728 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
729 {
730         FD_SET(c->sock, readset);
731 }
732
733 static void
734 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
735 {
736         debug3("channel %d: waiting for connection", c->self);
737         FD_SET(c->sock, writeset);
738 }
739
740 static void
741 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
742 {
743         if (buffer_len(&c->input) < packet_get_maxsize())
744                 FD_SET(c->sock, readset);
745         if (buffer_len(&c->output) > 0)
746                 FD_SET(c->sock, writeset);
747 }
748
749 int channel_tcpwinsz () {
750         u_int32_t tcpwinsz = 0;
751         socklen_t optsz = sizeof(tcpwinsz);
752         int ret = -1;
753         if(!packet_connection_is_on_socket()) 
754                 return(131072);
755         ret = getsockopt(packet_get_connection_in(),
756                         SOL_SOCKET, SO_RCVBUF, &tcpwinsz, &optsz);
757         if ((ret == 0) && tcpwinsz > BUFFER_MAX_HPN_LEN)
758                           tcpwinsz = BUFFER_MAX_HPN_LEN;
759         debug2("tcpwinsz: %d for connection: %d", tcpwinsz, packet_get_connection_in());
760         return(tcpwinsz);
761 }
762
763 static void
764 channel_pre_open(Channel *c, fd_set * readset, fd_set * writeset)
765 {
766         u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
767
768         /* check buffer limits */
769         if (!c->tcpwinsz) 
770                 c->tcpwinsz = channel_tcpwinsz();
771         if (c->dynamic_window > 0)
772                 c->tcpwinsz = channel_tcpwinsz();
773
774         limit = MIN(limit, 2 * c->tcpwinsz);
775
776         if (c->istate == CHAN_INPUT_OPEN &&
777             limit > 0 &&
778             buffer_len(&c->input) < limit)
779                 FD_SET(c->rfd, readset);
780         if (c->ostate == CHAN_OUTPUT_OPEN ||
781             c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
782                 if (buffer_len(&c->output) > 0) {
783                         FD_SET(c->wfd, writeset);
784                 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
785                         if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
786                                 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
787                                     c->self, c->efd, buffer_len(&c->extended));
788                         else
789                                 chan_obuf_empty(c);
790                 }
791         }
792         /** XXX check close conditions, too */
793         if (compat20 && c->efd != -1) {
794                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
795                     buffer_len(&c->extended) > 0)
796                         FD_SET(c->efd, writeset);
797                 else if (!(c->flags & CHAN_EOF_SENT) &&
798                     c->extended_usage == CHAN_EXTENDED_READ &&
799                     buffer_len(&c->extended) < c->remote_window)
800                         FD_SET(c->efd, readset);
801         }
802         /* XXX: What about efd? races? */
803         if (compat20 && c->ctl_fd != -1 &&
804             c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
805                 FD_SET(c->ctl_fd, readset);
806 }
807
808 static void
809 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
810 {
811         if (buffer_len(&c->input) == 0) {
812                 packet_start(SSH_MSG_CHANNEL_CLOSE);
813                 packet_put_int(c->remote_id);
814                 packet_send();
815                 c->type = SSH_CHANNEL_CLOSED;
816                 debug2("channel %d: closing after input drain.", c->self);
817         }
818 }
819
820 static void
821 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
822 {
823         if (buffer_len(&c->output) == 0)
824                 chan_mark_dead(c);
825         else
826                 FD_SET(c->sock, writeset);
827 }
828
829 /*
830  * This is a special state for X11 authentication spoofing.  An opened X11
831  * connection (when authentication spoofing is being done) remains in this
832  * state until the first packet has been completely read.  The authentication
833  * data in that packet is then substituted by the real data if it matches the
834  * fake data, and the channel is put into normal mode.
835  * XXX All this happens at the client side.
836  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
837  */
838 static int
839 x11_open_helper(Buffer *b)
840 {
841         u_char *ucp;
842         u_int proto_len, data_len;
843
844         /* Check if the fixed size part of the packet is in buffer. */
845         if (buffer_len(b) < 12)
846                 return 0;
847
848         /* Parse the lengths of variable-length fields. */
849         ucp = buffer_ptr(b);
850         if (ucp[0] == 0x42) {   /* Byte order MSB first. */
851                 proto_len = 256 * ucp[6] + ucp[7];
852                 data_len = 256 * ucp[8] + ucp[9];
853         } else if (ucp[0] == 0x6c) {    /* Byte order LSB first. */
854                 proto_len = ucp[6] + 256 * ucp[7];
855                 data_len = ucp[8] + 256 * ucp[9];
856         } else {
857                 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
858                     ucp[0]);
859                 return -1;
860         }
861
862         /* Check if the whole packet is in buffer. */
863         if (buffer_len(b) <
864             12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
865                 return 0;
866
867         /* Check if authentication protocol matches. */
868         if (proto_len != strlen(x11_saved_proto) ||
869             memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
870                 debug2("X11 connection uses different authentication protocol.");
871                 return -1;
872         }
873         /* Check if authentication data matches our fake data. */
874         if (data_len != x11_fake_data_len ||
875             memcmp(ucp + 12 + ((proto_len + 3) & ~3),
876                 x11_fake_data, x11_fake_data_len) != 0) {
877                 debug2("X11 auth data does not match fake data.");
878                 return -1;
879         }
880         /* Check fake data length */
881         if (x11_fake_data_len != x11_saved_data_len) {
882                 error("X11 fake_data_len %d != saved_data_len %d",
883                     x11_fake_data_len, x11_saved_data_len);
884                 return -1;
885         }
886         /*
887          * Received authentication protocol and data match
888          * our fake data. Substitute the fake data with real
889          * data.
890          */
891         memcpy(ucp + 12 + ((proto_len + 3) & ~3),
892             x11_saved_data, x11_saved_data_len);
893         return 1;
894 }
895
896 static void
897 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
898 {
899         int ret = x11_open_helper(&c->output);
900
901         if (ret == 1) {
902                 /* Start normal processing for the channel. */
903                 c->type = SSH_CHANNEL_OPEN;
904                 channel_pre_open_13(c, readset, writeset);
905         } else if (ret == -1) {
906                 /*
907                  * We have received an X11 connection that has bad
908                  * authentication information.
909                  */
910                 logit("X11 connection rejected because of wrong authentication.");
911                 buffer_clear(&c->input);
912                 buffer_clear(&c->output);
913                 channel_close_fd(&c->sock);
914                 c->sock = -1;
915                 c->type = SSH_CHANNEL_CLOSED;
916                 packet_start(SSH_MSG_CHANNEL_CLOSE);
917                 packet_put_int(c->remote_id);
918                 packet_send();
919         }
920 }
921
922 static void
923 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
924 {
925         int ret = x11_open_helper(&c->output);
926
927         /* c->force_drain = 1; */
928
929         if (ret == 1) {
930                 c->type = SSH_CHANNEL_OPEN;
931                 channel_pre_open(c, readset, writeset);
932         } else if (ret == -1) {
933                 logit("X11 connection rejected because of wrong authentication.");
934                 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
935                 chan_read_failed(c);
936                 buffer_clear(&c->input);
937                 chan_ibuf_empty(c);
938                 buffer_clear(&c->output);
939                 /* for proto v1, the peer will send an IEOF */
940                 if (compat20)
941                         chan_write_failed(c);
942                 else
943                         c->type = SSH_CHANNEL_OPEN;
944                 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
945         }
946 }
947
948 /* try to decode a socks4 header */
949 static int
950 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
951 {
952         char *p, *host;
953         u_int len, have, i, found;
954         char username[256];
955         struct {
956                 u_int8_t version;
957                 u_int8_t command;
958                 u_int16_t dest_port;
959                 struct in_addr dest_addr;
960         } s4_req, s4_rsp;
961
962         debug2("channel %d: decode socks4", c->self);
963
964         have = buffer_len(&c->input);
965         len = sizeof(s4_req);
966         if (have < len)
967                 return 0;
968         p = buffer_ptr(&c->input);
969         for (found = 0, i = len; i < have; i++) {
970                 if (p[i] == '\0') {
971                         found = 1;
972                         break;
973                 }
974                 if (i > 1024) {
975                         /* the peer is probably sending garbage */
976                         debug("channel %d: decode socks4: too long",
977                             c->self);
978                         return -1;
979                 }
980         }
981         if (!found)
982                 return 0;
983         buffer_get(&c->input, (char *)&s4_req.version, 1);
984         buffer_get(&c->input, (char *)&s4_req.command, 1);
985         buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
986         buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
987         have = buffer_len(&c->input);
988         p = buffer_ptr(&c->input);
989         len = strlen(p);
990         debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
991         if (len > have)
992                 fatal("channel %d: decode socks4: len %d > have %d",
993                     c->self, len, have);
994         strlcpy(username, p, sizeof(username));
995         buffer_consume(&c->input, len);
996         buffer_consume(&c->input, 1);           /* trailing '\0' */
997
998         host = inet_ntoa(s4_req.dest_addr);
999         strlcpy(c->path, host, sizeof(c->path));
1000         c->host_port = ntohs(s4_req.dest_port);
1001
1002         debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1003             c->self, host, c->host_port, s4_req.command);
1004
1005         if (s4_req.command != 1) {
1006                 debug("channel %d: cannot handle: socks4 cn %d",
1007                     c->self, s4_req.command);
1008                 return -1;
1009         }
1010         s4_rsp.version = 0;                     /* vn: 0 for reply */
1011         s4_rsp.command = 90;                    /* cd: req granted */
1012         s4_rsp.dest_port = 0;                   /* ignored */
1013         s4_rsp.dest_addr.s_addr = INADDR_ANY;   /* ignored */
1014         buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
1015         return 1;
1016 }
1017
1018 /* try to decode a socks5 header */
1019 #define SSH_SOCKS5_AUTHDONE     0x1000
1020 #define SSH_SOCKS5_NOAUTH       0x00
1021 #define SSH_SOCKS5_IPV4         0x01
1022 #define SSH_SOCKS5_DOMAIN       0x03
1023 #define SSH_SOCKS5_IPV6         0x04
1024 #define SSH_SOCKS5_CONNECT      0x01
1025 #define SSH_SOCKS5_SUCCESS      0x00
1026
1027 static int
1028 channel_decode_socks5(Channel *c, fd_set * readset, fd_set * writeset)
1029 {
1030         struct {
1031                 u_int8_t version;
1032                 u_int8_t command;
1033                 u_int8_t reserved;
1034                 u_int8_t atyp;
1035         } s5_req, s5_rsp;
1036         u_int16_t dest_port;
1037         u_char *p, dest_addr[255+1];
1038         u_int have, i, found, nmethods, addrlen, af;
1039
1040         debug2("channel %d: decode socks5", c->self);
1041         p = buffer_ptr(&c->input);
1042         if (p[0] != 0x05)
1043                 return -1;
1044         have = buffer_len(&c->input);
1045         if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1046                 /* format: ver | nmethods | methods */
1047                 if (have < 2)
1048                         return 0;
1049                 nmethods = p[1];
1050                 if (have < nmethods + 2)
1051                         return 0;
1052                 /* look for method: "NO AUTHENTICATION REQUIRED" */
1053                 for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1054                         if (p[i] == SSH_SOCKS5_NOAUTH ) {
1055                                 found = 1;
1056                                 break;
1057                         }
1058                 }
1059                 if (!found) {
1060                         debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1061                             c->self);
1062                         return -1;
1063                 }
1064                 buffer_consume(&c->input, nmethods + 2);
1065                 buffer_put_char(&c->output, 0x05);              /* version */
1066                 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1067                 FD_SET(c->sock, writeset);
1068                 c->flags |= SSH_SOCKS5_AUTHDONE;
1069                 debug2("channel %d: socks5 auth done", c->self);
1070                 return 0;                               /* need more */
1071         }
1072         debug2("channel %d: socks5 post auth", c->self);
1073         if (have < sizeof(s5_req)+1)
1074                 return 0;                       /* need more */
1075         memcpy((char *)&s5_req, p, sizeof(s5_req));
1076         if (s5_req.version != 0x05 ||
1077             s5_req.command != SSH_SOCKS5_CONNECT ||
1078             s5_req.reserved != 0x00) {
1079                 debug2("channel %d: only socks5 connect supported", c->self);
1080                 return -1;
1081         }
1082         switch (s5_req.atyp){
1083         case SSH_SOCKS5_IPV4:
1084                 addrlen = 4;
1085                 af = AF_INET;
1086                 break;
1087         case SSH_SOCKS5_DOMAIN:
1088                 addrlen = p[sizeof(s5_req)];
1089                 af = -1;
1090                 break;
1091         case SSH_SOCKS5_IPV6:
1092                 addrlen = 16;
1093                 af = AF_INET6;
1094                 break;
1095         default:
1096                 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1097                 return -1;
1098         }
1099         if (have < 4 + addrlen + 2)
1100                 return 0;
1101         buffer_consume(&c->input, sizeof(s5_req));
1102         if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1103                 buffer_consume(&c->input, 1);    /* host string length */
1104         buffer_get(&c->input, (char *)&dest_addr, addrlen);
1105         buffer_get(&c->input, (char *)&dest_port, 2);
1106         dest_addr[addrlen] = '\0';
1107         if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1108                 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1109         else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1110                 return -1;
1111         c->host_port = ntohs(dest_port);
1112
1113         debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1114             c->self, c->path, c->host_port, s5_req.command);
1115
1116         s5_rsp.version = 0x05;
1117         s5_rsp.command = SSH_SOCKS5_SUCCESS;
1118         s5_rsp.reserved = 0;                    /* ignored */
1119         s5_rsp.atyp = SSH_SOCKS5_IPV4;
1120         ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1121         dest_port = 0;                          /* ignored */
1122
1123         buffer_append(&c->output, (char *)&s5_rsp, sizeof(s5_rsp));
1124         buffer_append(&c->output, (char *)&dest_addr, sizeof(struct in_addr));
1125         buffer_append(&c->output, (char *)&dest_port, sizeof(dest_port));
1126         return 1;
1127 }
1128
1129 /* dynamic port forwarding */
1130 static void
1131 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
1132 {
1133         u_char *p;
1134         u_int have;
1135         int ret;
1136
1137         have = buffer_len(&c->input);
1138         c->delayed = 0;
1139         debug2("channel %d: pre_dynamic: have %d", c->self, have);
1140         /* buffer_dump(&c->input); */
1141         /* check if the fixed size part of the packet is in buffer. */
1142         if (have < 3) {
1143                 /* need more */
1144                 FD_SET(c->sock, readset);
1145                 return;
1146         }
1147         /* try to guess the protocol */
1148         p = buffer_ptr(&c->input);
1149         switch (p[0]) {
1150         case 0x04:
1151                 ret = channel_decode_socks4(c, readset, writeset);
1152                 break;
1153         case 0x05:
1154                 ret = channel_decode_socks5(c, readset, writeset);
1155                 break;
1156         default:
1157                 ret = -1;
1158                 break;
1159         }
1160         if (ret < 0) {
1161                 chan_mark_dead(c);
1162         } else if (ret == 0) {
1163                 debug2("channel %d: pre_dynamic: need more", c->self);
1164                 /* need more */
1165                 FD_SET(c->sock, readset);
1166         } else {
1167                 /* switch to the next state */
1168                 c->type = SSH_CHANNEL_OPENING;
1169                 port_open_helper(c, "direct-tcpip");
1170         }
1171 }
1172
1173 /* This is our fake X11 server socket. */
1174 static void
1175 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
1176 {
1177         Channel *nc;
1178         struct sockaddr addr;
1179         int newsock;
1180         socklen_t addrlen;
1181         char buf[16384], *remote_ipaddr;
1182         int remote_port;
1183
1184         if (FD_ISSET(c->sock, readset)) {
1185                 debug("X11 connection requested.");
1186                 addrlen = sizeof(addr);
1187                 newsock = accept(c->sock, &addr, &addrlen);
1188                 if (c->single_connection) {
1189                         debug2("single_connection: closing X11 listener.");
1190                         channel_close_fd(&c->sock);
1191                         chan_mark_dead(c);
1192                 }
1193                 if (newsock < 0) {
1194                         error("accept: %.100s", strerror(errno));
1195                         return;
1196                 }
1197                 set_nodelay(newsock);
1198                 remote_ipaddr = get_peer_ipaddr(newsock);
1199                 remote_port = get_peer_port(newsock);
1200                 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1201                     remote_ipaddr, remote_port);
1202
1203                 nc = channel_new("accepted x11 socket",
1204                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
1205                     c->local_window_max, c->local_maxpacket, 0, buf, 1);
1206                 if (compat20) {
1207                         packet_start(SSH2_MSG_CHANNEL_OPEN);
1208                         packet_put_cstring("x11");
1209                         packet_put_int(nc->self);
1210                         packet_put_int(nc->local_window_max);
1211                         packet_put_int(nc->local_maxpacket);
1212                         /* originator ipaddr and port */
1213                         packet_put_cstring(remote_ipaddr);
1214                         if (datafellows & SSH_BUG_X11FWD) {
1215                                 debug2("ssh2 x11 bug compat mode");
1216                         } else {
1217                                 packet_put_int(remote_port);
1218                         }
1219                         packet_send();
1220                 } else {
1221                         packet_start(SSH_SMSG_X11_OPEN);
1222                         packet_put_int(nc->self);
1223                         if (packet_get_protocol_flags() &
1224                             SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1225                                 packet_put_cstring(buf);
1226                         packet_send();
1227                 }
1228                 xfree(remote_ipaddr);
1229         }
1230 }
1231
1232 static void
1233 port_open_helper(Channel *c, char *rtype)
1234 {
1235         int direct;
1236         char buf[1024];
1237         char *remote_ipaddr = get_peer_ipaddr(c->sock);
1238         int remote_port = get_peer_port(c->sock);
1239
1240         direct = (strcmp(rtype, "direct-tcpip") == 0);
1241
1242         snprintf(buf, sizeof buf,
1243             "%s: listening port %d for %.100s port %d, "
1244             "connect from %.200s port %d",
1245             rtype, c->listening_port, c->path, c->host_port,
1246             remote_ipaddr, remote_port);
1247
1248         xfree(c->remote_name);
1249         c->remote_name = xstrdup(buf);
1250
1251         if (compat20) {
1252                 packet_start(SSH2_MSG_CHANNEL_OPEN);
1253                 packet_put_cstring(rtype);
1254                 packet_put_int(c->self);
1255                 packet_put_int(c->local_window_max);
1256                 packet_put_int(c->local_maxpacket);
1257                 if (direct) {
1258                         /* target host, port */
1259                         packet_put_cstring(c->path);
1260                         packet_put_int(c->host_port);
1261                 } else {
1262                         /* listen address, port */
1263                         packet_put_cstring(c->path);
1264                         packet_put_int(c->listening_port);
1265                 }
1266                 /* originator host and port */
1267                 packet_put_cstring(remote_ipaddr);
1268                 packet_put_int((u_int)remote_port);
1269                 packet_send();
1270         } else {
1271                 packet_start(SSH_MSG_PORT_OPEN);
1272                 packet_put_int(c->self);
1273                 packet_put_cstring(c->path);
1274                 packet_put_int(c->host_port);
1275                 if (packet_get_protocol_flags() &
1276                     SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1277                         packet_put_cstring(c->remote_name);
1278                 packet_send();
1279         }
1280         xfree(remote_ipaddr);
1281 }
1282
1283 static void
1284 channel_set_reuseaddr(int fd)
1285 {
1286         int on = 1;
1287
1288         /*
1289          * Set socket options.
1290          * Allow local port reuse in TIME_WAIT.
1291          */
1292         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1293                 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1294 }
1295
1296 /*
1297  * This socket is listening for connections to a forwarded TCP/IP port.
1298  */
1299 static void
1300 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
1301 {
1302         Channel *nc;
1303         struct sockaddr addr;
1304         int newsock, nextstate;
1305         socklen_t addrlen;
1306         char *rtype;
1307
1308         if (FD_ISSET(c->sock, readset)) {
1309                 debug("Connection to port %d forwarding "
1310                     "to %.100s port %d requested.",
1311                     c->listening_port, c->path, c->host_port);
1312
1313                 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1314                         nextstate = SSH_CHANNEL_OPENING;
1315                         rtype = "forwarded-tcpip";
1316                 } else {
1317                         if (c->host_port == 0) {
1318                                 nextstate = SSH_CHANNEL_DYNAMIC;
1319                                 rtype = "dynamic-tcpip";
1320                         } else {
1321                                 nextstate = SSH_CHANNEL_OPENING;
1322                                 rtype = "direct-tcpip";
1323                         }
1324                 }
1325
1326                 addrlen = sizeof(addr);
1327                 newsock = accept(c->sock, &addr, &addrlen);
1328                 if (newsock < 0) {
1329                         error("accept: %.100s", strerror(errno));
1330                         return;
1331                 }
1332                 set_nodelay(newsock);
1333                 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1334                     c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1335                 nc->listening_port = c->listening_port;
1336                 nc->host_port = c->host_port;
1337                 strlcpy(nc->path, c->path, sizeof(nc->path));
1338
1339                 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1340                         /*
1341                          * do not call the channel_post handler until
1342                          * this flag has been reset by a pre-handler.
1343                          * otherwise the FD_ISSET calls might overflow
1344                          */
1345                         nc->delayed = 1;
1346                 } else {
1347                         port_open_helper(nc, rtype);
1348                 }
1349         }
1350 }
1351
1352 /*
1353  * This is the authentication agent socket listening for connections from
1354  * clients.
1355  */
1356 static void
1357 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
1358 {
1359         Channel *nc;
1360         int newsock;
1361         struct sockaddr addr;
1362         socklen_t addrlen;
1363
1364         if (FD_ISSET(c->sock, readset)) {
1365                 addrlen = sizeof(addr);
1366                 newsock = accept(c->sock, &addr, &addrlen);
1367                 if (newsock < 0) {
1368                         error("accept from auth socket: %.100s", strerror(errno));
1369                         return;
1370                 }
1371                 nc = channel_new("accepted auth socket",
1372                     SSH_CHANNEL_OPENING, newsock, newsock, -1,
1373                     c->local_window_max, c->local_maxpacket,
1374                     0, "accepted auth socket", 1);
1375                 if (compat20) {
1376                         packet_start(SSH2_MSG_CHANNEL_OPEN);
1377                         packet_put_cstring("auth-agent@openssh.com");
1378                         packet_put_int(nc->self);
1379                         packet_put_int(c->local_window_max);
1380                         packet_put_int(c->local_maxpacket);
1381                 } else {
1382                         packet_start(SSH_SMSG_AGENT_OPEN);
1383                         packet_put_int(nc->self);
1384                 }
1385                 packet_send();
1386         }
1387 }
1388
1389 static void
1390 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
1391 {
1392         int err = 0;
1393         socklen_t sz = sizeof(err);
1394
1395         if (FD_ISSET(c->sock, writeset)) {
1396                 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1397                         err = errno;
1398                         error("getsockopt SO_ERROR failed");
1399                 }
1400                 if (err == 0) {
1401                         debug("channel %d: connected", c->self);
1402                         c->type = SSH_CHANNEL_OPEN;
1403                         if (compat20) {
1404                                 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1405                                 packet_put_int(c->remote_id);
1406                                 packet_put_int(c->self);
1407                                 packet_put_int(c->local_window);
1408                                 packet_put_int(c->local_maxpacket);
1409                         } else {
1410                                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1411                                 packet_put_int(c->remote_id);
1412                                 packet_put_int(c->self);
1413                         }
1414                 } else {
1415                         debug("channel %d: not connected: %s",
1416                             c->self, strerror(err));
1417                         if (compat20) {
1418                                 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1419                                 packet_put_int(c->remote_id);
1420                                 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1421                                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1422                                         packet_put_cstring(strerror(err));
1423                                         packet_put_cstring("");
1424                                 }
1425                         } else {
1426                                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1427                                 packet_put_int(c->remote_id);
1428                         }
1429                         chan_mark_dead(c);
1430                 }
1431                 packet_send();
1432         }
1433 }
1434
1435 static int
1436 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
1437 {
1438         char buf[CHAN_RBUF];
1439         int len;
1440
1441         if (c->rfd != -1 &&
1442             FD_ISSET(c->rfd, readset)) {
1443                 len = read(c->rfd, buf, sizeof(buf));
1444                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1445                         return 1;
1446                 if (len <= 0) {
1447                         debug2("channel %d: read<=0 rfd %d len %d",
1448                             c->self, c->rfd, len);
1449                         if (c->type != SSH_CHANNEL_OPEN) {
1450                                 debug2("channel %d: not open", c->self);
1451                                 chan_mark_dead(c);
1452                                 return -1;
1453                         } else if (compat13) {
1454                                 buffer_clear(&c->output);
1455                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
1456                                 debug2("channel %d: input draining.", c->self);
1457                         } else {
1458                                 chan_read_failed(c);
1459                         }
1460                         return -1;
1461                 }
1462                 if (c->input_filter != NULL) {
1463                         if (c->input_filter(c, buf, len) == -1) {
1464                                 debug2("channel %d: filter stops", c->self);
1465                                 chan_read_failed(c);
1466                         }
1467                 } else if (c->datagram) {
1468                         buffer_put_string(&c->input, buf, len);
1469                 } else {
1470                         buffer_append(&c->input, buf, len);
1471                 }
1472         }
1473         return 1;
1474 }
1475 static int
1476 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
1477 {
1478         struct termios tio;
1479         u_char *data = NULL, *buf;
1480         u_int dlen;
1481         int len;
1482
1483         /* Send buffered output data to the socket. */
1484         if (c->wfd != -1 &&
1485             FD_ISSET(c->wfd, writeset) &&
1486             buffer_len(&c->output) > 0) {
1487                 if (c->output_filter != NULL) {
1488                         if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1489                                 debug2("channel %d: filter stops", c->self);
1490                                 if (c->type != SSH_CHANNEL_OPEN)
1491                                         chan_mark_dead(c);
1492                                 else
1493                                         chan_write_failed(c);
1494                                 return -1;
1495                         }
1496                 } else if (c->datagram) {
1497                         buf = data = buffer_get_string(&c->output, &dlen);
1498                 } else {
1499                         buf = data = buffer_ptr(&c->output);
1500                         dlen = buffer_len(&c->output);
1501                 }
1502
1503                 if (c->datagram) {
1504                         /* ignore truncated writes, datagrams might get lost */
1505                         c->local_consumed += dlen + 4;
1506                         len = write(c->wfd, buf, dlen);
1507                         xfree(data);
1508                         if (len < 0 && (errno == EINTR || errno == EAGAIN))
1509                                 return 1;
1510                         if (len <= 0) {
1511                                 if (c->type != SSH_CHANNEL_OPEN)
1512                                         chan_mark_dead(c);
1513                                 else
1514                                         chan_write_failed(c);
1515                                 return -1;
1516                         }
1517                         return 1;
1518                 }
1519 #ifdef _AIX
1520                 /* XXX: Later AIX versions can't push as much data to tty */
1521                 if (compat20 && c->wfd_isatty)
1522                         dlen = MIN(dlen, 8*1024);
1523 #endif
1524
1525                 len = write(c->wfd, buf, dlen);
1526                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1527                         return 1;
1528                 if (len <= 0) {
1529                         if (c->type != SSH_CHANNEL_OPEN) {
1530                                 debug2("channel %d: not open", c->self);
1531                                 chan_mark_dead(c);
1532                                 return -1;
1533                         } else if (compat13) {
1534                                 buffer_clear(&c->output);
1535                                 debug2("channel %d: input draining.", c->self);
1536                                 c->type = SSH_CHANNEL_INPUT_DRAINING;
1537                         } else {
1538                                 chan_write_failed(c);
1539                         }
1540                         return -1;
1541                 }
1542                 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1543                         if (tcgetattr(c->wfd, &tio) == 0 &&
1544                             !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1545                                 /*
1546                                  * Simulate echo to reduce the impact of
1547                                  * traffic analysis. We need to match the
1548                                  * size of a SSH2_MSG_CHANNEL_DATA message
1549                                  * (4 byte channel id + buf)
1550                                  */
1551                                 packet_send_ignore(4 + len);
1552                                 packet_send();
1553                         }
1554                 }
1555                 buffer_consume(&c->output, len);
1556                 if (compat20 && len > 0) {
1557                         c->local_consumed += len;
1558                 }
1559         }
1560         return 1;
1561 }
1562 static int
1563 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
1564 {
1565         char buf[CHAN_RBUF];
1566         int len;
1567
1568 /** XXX handle drain efd, too */
1569         if (c->efd != -1) {
1570                 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1571                     FD_ISSET(c->efd, writeset) &&
1572                     buffer_len(&c->extended) > 0) {
1573                         len = write(c->efd, buffer_ptr(&c->extended),
1574                             buffer_len(&c->extended));
1575                         debug2("channel %d: written %d to efd %d",
1576                             c->self, len, c->efd);
1577                         if (len < 0 && (errno == EINTR || errno == EAGAIN))
1578                                 return 1;
1579                         if (len <= 0) {
1580                                 debug2("channel %d: closing write-efd %d",
1581                                     c->self, c->efd);
1582                                 channel_close_fd(&c->efd);
1583                         } else {
1584                                 buffer_consume(&c->extended, len);
1585                                 c->local_consumed += len;
1586                         }
1587                 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1588                     FD_ISSET(c->efd, readset)) {
1589                         len = read(c->efd, buf, sizeof(buf));
1590                         debug2("channel %d: read %d from efd %d",
1591                             c->self, len, c->efd);
1592                         if (len < 0 && (errno == EINTR || errno == EAGAIN))
1593                                 return 1;
1594                         if (len <= 0) {
1595                                 debug2("channel %d: closing read-efd %d",
1596                                     c->self, c->efd);
1597                                 channel_close_fd(&c->efd);
1598                         } else {
1599                                 buffer_append(&c->extended, buf, len);
1600                         }
1601                 }
1602         }
1603         return 1;
1604 }
1605 static int
1606 channel_handle_ctl(Channel *c, fd_set * readset, fd_set * writeset)
1607 {
1608         char buf[16];
1609         int len;
1610
1611         /* Monitor control fd to detect if the slave client exits */
1612         if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1613                 len = read(c->ctl_fd, buf, sizeof(buf));
1614                 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1615                         return 1;
1616                 if (len <= 0) {
1617                         debug2("channel %d: ctl read<=0", c->self);
1618                         if (c->type != SSH_CHANNEL_OPEN) {
1619                                 debug2("channel %d: not open", c->self);
1620                                 chan_mark_dead(c);
1621                                 return -1;
1622                         } else {
1623                                 chan_read_failed(c);
1624                                 chan_write_failed(c);
1625                         }
1626                         return -1;
1627                 } else
1628                         fatal("%s: unexpected data on ctl fd", __func__);
1629         }
1630         return 1;
1631 }
1632 static int
1633 channel_check_window(Channel *c)
1634 {
1635         if (c->type == SSH_CHANNEL_OPEN &&
1636             !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1637             c->local_window < c->local_window_max/2 &&
1638             c->local_consumed > 0) {
1639                 u_int addition = 0;
1640                 /* adjust max window size if we are in a dynamic environment */
1641                 if (c->dynamic_window && (c->tcpwinsz > c->local_window_max)) {
1642                         addition = c->tcpwinsz - c->local_window_max;
1643                         c->local_window_max += addition;
1644                 }
1645                 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1646                 packet_put_int(c->remote_id);
1647                 packet_put_int(c->local_consumed + addition);
1648                 packet_send();
1649                 debug2("channel %d: window %d sent adjust %d",
1650                     c->self, c->local_window,
1651                     c->local_consumed);
1652                 c->local_window += c->local_consumed + addition;
1653                 c->local_consumed = 0;
1654         }
1655         return 1;
1656 }
1657
1658 static void
1659 channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1660 {
1661         if (c->delayed)
1662                 return;
1663         channel_handle_rfd(c, readset, writeset);
1664         channel_handle_wfd(c, readset, writeset);
1665         if (!compat20)
1666                 return;
1667         channel_handle_efd(c, readset, writeset);
1668         channel_handle_ctl(c, readset, writeset);
1669         channel_check_window(c);
1670 }
1671
1672 static void
1673 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1674 {
1675         int len;
1676
1677         /* Send buffered output data to the socket. */
1678         if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1679                 len = write(c->sock, buffer_ptr(&c->output),
1680                             buffer_len(&c->output));
1681                 if (len <= 0)
1682                         buffer_clear(&c->output);
1683                 else
1684                         buffer_consume(&c->output, len);
1685         }
1686 }
1687
1688 static void
1689 channel_handler_init_20(void)
1690 {
1691         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1692         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1693         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1694         channel_pre[SSH_CHANNEL_RPORT_LISTENER] =       &channel_pre_listener;
1695         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1696         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1697         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1698         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1699
1700         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1701         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1702         channel_post[SSH_CHANNEL_RPORT_LISTENER] =      &channel_post_port_listener;
1703         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1704         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1705         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1706         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1707 }
1708
1709 static void
1710 channel_handler_init_13(void)
1711 {
1712         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open_13;
1713         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open_13;
1714         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1715         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1716         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1717         channel_pre[SSH_CHANNEL_INPUT_DRAINING] =       &channel_pre_input_draining;
1718         channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =      &channel_pre_output_draining;
1719         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1720         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1721
1722         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1723         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1724         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1725         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1726         channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =     &channel_post_output_drain_13;
1727         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1728         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1729 }
1730
1731 static void
1732 channel_handler_init_15(void)
1733 {
1734         channel_pre[SSH_CHANNEL_OPEN] =                 &channel_pre_open;
1735         channel_pre[SSH_CHANNEL_X11_OPEN] =             &channel_pre_x11_open;
1736         channel_pre[SSH_CHANNEL_X11_LISTENER] =         &channel_pre_listener;
1737         channel_pre[SSH_CHANNEL_PORT_LISTENER] =        &channel_pre_listener;
1738         channel_pre[SSH_CHANNEL_AUTH_SOCKET] =          &channel_pre_listener;
1739         channel_pre[SSH_CHANNEL_CONNECTING] =           &channel_pre_connecting;
1740         channel_pre[SSH_CHANNEL_DYNAMIC] =              &channel_pre_dynamic;
1741
1742         channel_post[SSH_CHANNEL_X11_LISTENER] =        &channel_post_x11_listener;
1743         channel_post[SSH_CHANNEL_PORT_LISTENER] =       &channel_post_port_listener;
1744         channel_post[SSH_CHANNEL_AUTH_SOCKET] =         &channel_post_auth_listener;
1745         channel_post[SSH_CHANNEL_OPEN] =                &channel_post_open;
1746         channel_post[SSH_CHANNEL_CONNECTING] =          &channel_post_connecting;
1747         channel_post[SSH_CHANNEL_DYNAMIC] =             &channel_post_open;
1748 }
1749
1750 static void
1751 channel_handler_init(void)
1752 {
1753         int i;
1754
1755         for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1756                 channel_pre[i] = NULL;
1757                 channel_post[i] = NULL;
1758         }
1759         if (compat20)
1760                 channel_handler_init_20();
1761         else if (compat13)
1762                 channel_handler_init_13();
1763         else
1764                 channel_handler_init_15();
1765 }
1766
1767 /* gc dead channels */
1768 static void
1769 channel_garbage_collect(Channel *c)
1770 {
1771         if (c == NULL)
1772                 return;
1773         if (c->detach_user != NULL) {
1774                 if (!chan_is_dead(c, c->detach_close))
1775                         return;
1776                 debug2("channel %d: gc: notify user", c->self);
1777                 c->detach_user(c->self, NULL);
1778                 /* if we still have a callback */
1779                 if (c->detach_user != NULL)
1780                         return;
1781                 debug2("channel %d: gc: user detached", c->self);
1782         }
1783         if (!chan_is_dead(c, 1))
1784                 return;
1785         debug2("channel %d: garbage collecting", c->self);
1786         channel_free(c);
1787 }
1788
1789 static void
1790 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1791 {
1792         static int did_init = 0;
1793         u_int i;
1794         Channel *c;
1795
1796         if (!did_init) {
1797                 channel_handler_init();
1798                 did_init = 1;
1799         }
1800         for (i = 0; i < channels_alloc; i++) {
1801                 c = channels[i];
1802                 if (c == NULL)
1803                         continue;
1804                 if (ftab[c->type] != NULL)
1805                         (*ftab[c->type])(c, readset, writeset);
1806                 channel_garbage_collect(c);
1807         }
1808 }
1809
1810 /*
1811  * Allocate/update select bitmasks and add any bits relevant to channels in
1812  * select bitmasks.
1813  */
1814 void
1815 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1816     u_int *nallocp, int rekeying)
1817 {
1818         u_int n, sz;
1819
1820         n = MAX(*maxfdp, channel_max_fd);
1821
1822         sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1823         /* perhaps check sz < nalloc/2 and shrink? */
1824         if (*readsetp == NULL || sz > *nallocp) {
1825                 *readsetp = xrealloc(*readsetp, sz);
1826                 *writesetp = xrealloc(*writesetp, sz);
1827                 *nallocp = sz;
1828         }
1829         *maxfdp = n;
1830         memset(*readsetp, 0, sz);
1831         memset(*writesetp, 0, sz);
1832
1833         if (!rekeying)
1834                 channel_handler(channel_pre, *readsetp, *writesetp);
1835 }
1836
1837 /*
1838  * After select, perform any appropriate operations for channels which have
1839  * events pending.
1840  */
1841 void
1842 channel_after_select(fd_set * readset, fd_set * writeset)
1843 {
1844         channel_handler(channel_post, readset, writeset);
1845 }
1846
1847
1848 /* If there is data to send to the connection, enqueue some of it now. */
1849
1850 void
1851 channel_output_poll(void)
1852 {
1853         Channel *c;
1854         u_int i, len;
1855
1856         for (i = 0; i < channels_alloc; i++) {
1857                 c = channels[i];
1858                 if (c == NULL)
1859                         continue;
1860
1861                 /*
1862                  * We are only interested in channels that can have buffered
1863                  * incoming data.
1864                  */
1865                 if (compat13) {
1866                         if (c->type != SSH_CHANNEL_OPEN &&
1867                             c->type != SSH_CHANNEL_INPUT_DRAINING)
1868                                 continue;
1869                 } else {
1870                         if (c->type != SSH_CHANNEL_OPEN)
1871                                 continue;
1872                 }
1873                 if (compat20 &&
1874                     (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1875                         /* XXX is this true? */
1876                         debug3("channel %d: will not send data after close", c->self);
1877                         continue;
1878                 }
1879
1880                 /* Get the amount of buffered data for this channel. */
1881                 if ((c->istate == CHAN_INPUT_OPEN ||
1882                     c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1883                     (len = buffer_len(&c->input)) > 0) {
1884                         if (c->datagram) {
1885                                 if (len > 0) {
1886                                         u_char *data;
1887                                         u_int dlen;
1888
1889                                         data = buffer_get_string(&c->input,
1890                                             &dlen);
1891                                         packet_start(SSH2_MSG_CHANNEL_DATA);
1892                                         packet_put_int(c->remote_id);
1893                                         packet_put_string(data, dlen);
1894                                         packet_send();
1895                                         c->remote_window -= dlen + 4;
1896                                         xfree(data);
1897                                 }
1898                                 continue;
1899                         }
1900                         /*
1901                          * Send some data for the other side over the secure
1902                          * connection.
1903                          */
1904                         if (compat20) {
1905                                 if (len > c->remote_window)
1906                                         len = c->remote_window;
1907                                 if (len > c->remote_maxpacket)
1908                                         len = c->remote_maxpacket;
1909                         } else {
1910                                 if (packet_is_interactive()) {
1911                                         if (len > 1024)
1912                                                 len = 512;
1913                                 } else {
1914                                         /* Keep the packets at reasonable size. */
1915                                         if (len > packet_get_maxsize()/2)
1916                                                 len = packet_get_maxsize()/2;
1917                                 }
1918                         }
1919                         if (len > 0) {
1920                                 packet_start(compat20 ?
1921                                     SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1922                                 packet_put_int(c->remote_id);
1923                                 packet_put_string(buffer_ptr(&c->input), len);
1924                                 packet_send();
1925                                 buffer_consume(&c->input, len);
1926                                 c->remote_window -= len;
1927                         }
1928                 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1929                         if (compat13)
1930                                 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1931                         /*
1932                          * input-buffer is empty and read-socket shutdown:
1933                          * tell peer, that we will not send more data: send IEOF.
1934                          * hack for extended data: delay EOF if EFD still in use.
1935                          */
1936                         if (CHANNEL_EFD_INPUT_ACTIVE(c))
1937                                 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1938                                     c->self, c->efd, buffer_len(&c->extended));
1939                         else
1940                                 chan_ibuf_empty(c);
1941                 }
1942                 /* Send extended data, i.e. stderr */
1943                 if (compat20 &&
1944                     !(c->flags & CHAN_EOF_SENT) &&
1945                     c->remote_window > 0 &&
1946                     (len = buffer_len(&c->extended)) > 0 &&
1947                     c->extended_usage == CHAN_EXTENDED_READ) {
1948                         debug2("channel %d: rwin %u elen %u euse %d",
1949                             c->self, c->remote_window, buffer_len(&c->extended),
1950                             c->extended_usage);
1951                         if (len > c->remote_window)
1952                                 len = c->remote_window;
1953                         if (len > c->remote_maxpacket)
1954                                 len = c->remote_maxpacket;
1955                         packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1956                         packet_put_int(c->remote_id);
1957                         packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1958                         packet_put_string(buffer_ptr(&c->extended), len);
1959                         packet_send();
1960                         buffer_consume(&c->extended, len);
1961                         c->remote_window -= len;
1962                         debug2("channel %d: sent ext data %d", c->self, len);
1963                 }
1964         }
1965 }
1966
1967
1968 /* -- protocol input */
1969
1970 void
1971 channel_input_data(int type, u_int32_t seq, void *ctxt)
1972 {
1973         int id;
1974         char *data;
1975         u_int data_len;
1976         Channel *c;
1977
1978         /* Get the channel number and verify it. */
1979         id = packet_get_int();
1980         c = channel_lookup(id);
1981         if (c == NULL)
1982                 packet_disconnect("Received data for nonexistent channel %d.", id);
1983
1984         /* Ignore any data for non-open channels (might happen on close) */
1985         if (c->type != SSH_CHANNEL_OPEN &&
1986             c->type != SSH_CHANNEL_X11_OPEN)
1987                 return;
1988
1989         /* Get the data. */
1990         data = packet_get_string(&data_len);
1991
1992         /*
1993          * Ignore data for protocol > 1.3 if output end is no longer open.
1994          * For protocol 2 the sending side is reducing its window as it sends
1995          * data, so we must 'fake' consumption of the data in order to ensure
1996          * that window updates are sent back.  Otherwise the connection might
1997          * deadlock.
1998          */
1999         if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2000                 if (compat20) {
2001                         c->local_window -= data_len;
2002                         c->local_consumed += data_len;
2003                 }
2004                 xfree(data);
2005                 return;
2006         }
2007
2008         if (compat20) {
2009                 if (data_len > c->local_maxpacket) {
2010                         logit("channel %d: rcvd big packet %d, maxpack %d",
2011                             c->self, data_len, c->local_maxpacket);
2012                 }
2013                 if (data_len > c->local_window) {
2014                         logit("channel %d: rcvd too much data %d, win %d",
2015                             c->self, data_len, c->local_window);
2016                         xfree(data);
2017                         return;
2018                 }
2019                 c->local_window -= data_len;
2020         }
2021         packet_check_eom();
2022         if (c->datagram)
2023                 buffer_put_string(&c->output, data, data_len);
2024         else
2025                 buffer_append(&c->output, data, data_len);
2026         xfree(data);
2027 }
2028
2029 void
2030 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2031 {
2032         int id;
2033         char *data;
2034         u_int data_len, tcode;
2035         Channel *c;
2036
2037         /* Get the channel number and verify it. */
2038         id = packet_get_int();
2039         c = channel_lookup(id);
2040
2041         if (c == NULL)
2042                 packet_disconnect("Received extended_data for bad channel %d.", id);
2043         if (c->type != SSH_CHANNEL_OPEN) {
2044                 logit("channel %d: ext data for non open", id);
2045                 return;
2046         }
2047         if (c->flags & CHAN_EOF_RCVD) {
2048                 if (datafellows & SSH_BUG_EXTEOF)
2049                         debug("channel %d: accepting ext data after eof", id);
2050                 else
2051                         packet_disconnect("Received extended_data after EOF "
2052                             "on channel %d.", id);
2053         }
2054         tcode = packet_get_int();
2055         if (c->efd == -1 ||
2056             c->extended_usage != CHAN_EXTENDED_WRITE ||
2057             tcode != SSH2_EXTENDED_DATA_STDERR) {
2058                 logit("channel %d: bad ext data", c->self);
2059                 return;
2060         }
2061         data = packet_get_string(&data_len);
2062         packet_check_eom();
2063         if (data_len > c->local_window) {
2064                 logit("channel %d: rcvd too much extended_data %d, win %d",
2065                     c->self, data_len, c->local_window);
2066                 xfree(data);
2067                 return;
2068         }
2069         debug2("channel %d: rcvd ext data %d", c->self, data_len);
2070         c->local_window -= data_len;
2071         buffer_append(&c->extended, data, data_len);
2072         xfree(data);
2073 }
2074
2075 void
2076 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2077 {
2078         int id;
2079         Channel *c;
2080
2081         id = packet_get_int();
2082         packet_check_eom();
2083         c = channel_lookup(id);
2084         if (c == NULL)
2085                 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2086         chan_rcvd_ieof(c);
2087
2088         /* XXX force input close */
2089         if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2090                 debug("channel %d: FORCE input drain", c->self);
2091                 c->istate = CHAN_INPUT_WAIT_DRAIN;
2092                 if (buffer_len(&c->input) == 0)
2093                         chan_ibuf_empty(c);
2094         }
2095
2096 }
2097
2098 void
2099 channel_input_close(int type, u_int32_t seq, void *ctxt)
2100 {
2101         int id;
2102         Channel *c;
2103
2104         id = packet_get_int();
2105         packet_check_eom();
2106         c = channel_lookup(id);
2107         if (c == NULL)
2108                 packet_disconnect("Received close for nonexistent channel %d.", id);
2109
2110         /*
2111          * Send a confirmation that we have closed the channel and no more
2112          * data is coming for it.
2113          */
2114         packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2115         packet_put_int(c->remote_id);
2116         packet_send();
2117
2118         /*
2119          * If the channel is in closed state, we have sent a close request,
2120          * and the other side will eventually respond with a confirmation.
2121          * Thus, we cannot free the channel here, because then there would be
2122          * no-one to receive the confirmation.  The channel gets freed when
2123          * the confirmation arrives.
2124          */
2125         if (c->type != SSH_CHANNEL_CLOSED) {
2126                 /*
2127                  * Not a closed channel - mark it as draining, which will
2128                  * cause it to be freed later.
2129                  */
2130                 buffer_clear(&c->input);
2131                 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2132         }
2133 }
2134
2135 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2136 void
2137 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2138 {
2139         int id = packet_get_int();
2140         Channel *c = channel_lookup(id);
2141
2142         packet_check_eom();
2143         if (c == NULL)
2144                 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2145         chan_rcvd_oclose(c);
2146 }
2147
2148 void
2149 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2150 {
2151         int id = packet_get_int();
2152         Channel *c = channel_lookup(id);
2153
2154         packet_check_eom();
2155         if (c == NULL)
2156                 packet_disconnect("Received close confirmation for "
2157                     "out-of-range channel %d.", id);
2158         if (c->type != SSH_CHANNEL_CLOSED)
2159                 packet_disconnect("Received close confirmation for "
2160                     "non-closed channel %d (type %d).", id, c->type);
2161         channel_free(c);
2162 }
2163
2164 void
2165 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2166 {
2167         int id, remote_id;
2168         Channel *c;
2169
2170         id = packet_get_int();
2171         c = channel_lookup(id);
2172
2173         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2174                 packet_disconnect("Received open confirmation for "
2175                     "non-opening channel %d.", id);
2176         remote_id = packet_get_int();
2177         /* Record the remote channel number and mark that the channel is now open. */
2178         c->remote_id = remote_id;
2179         c->type = SSH_CHANNEL_OPEN;
2180
2181         if (compat20) {
2182                 c->remote_window = packet_get_int();
2183                 c->remote_maxpacket = packet_get_int();
2184                 if (c->confirm) {
2185                         debug2("callback start");
2186                         c->confirm(c->self, c->confirm_ctx);
2187                         debug2("callback done");
2188                 }
2189                 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2190                     c->remote_window, c->remote_maxpacket);
2191         }
2192         packet_check_eom();
2193 }
2194
2195 static char *
2196 reason2txt(int reason)
2197 {
2198         switch (reason) {
2199         case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2200                 return "administratively prohibited";
2201         case SSH2_OPEN_CONNECT_FAILED:
2202                 return "connect failed";
2203         case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2204                 return "unknown channel type";
2205         case SSH2_OPEN_RESOURCE_SHORTAGE:
2206                 return "resource shortage";
2207         }
2208         return "unknown reason";
2209 }
2210
2211 void
2212 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2213 {
2214         int id, reason;
2215         char *msg = NULL, *lang = NULL;
2216         Channel *c;
2217
2218         id = packet_get_int();
2219         c = channel_lookup(id);
2220
2221         if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2222                 packet_disconnect("Received open failure for "
2223                     "non-opening channel %d.", id);
2224         if (compat20) {
2225                 reason = packet_get_int();
2226                 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2227                         msg  = packet_get_string(NULL);
2228                         lang = packet_get_string(NULL);
2229                 }
2230                 logit("channel %d: open failed: %s%s%s", id,
2231                     reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2232                 if (msg != NULL)
2233                         xfree(msg);
2234                 if (lang != NULL)
2235                         xfree(lang);
2236         }
2237         packet_check_eom();
2238         /* Free the channel.  This will also close the socket. */
2239         channel_free(c);
2240 }
2241
2242 void
2243 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2244 {
2245         Channel *c;
2246         int id;
2247         u_int adjust;
2248
2249         if (!compat20)
2250                 return;
2251
2252         /* Get the channel number and verify it. */
2253         id = packet_get_int();
2254         c = channel_lookup(id);
2255
2256         if (c == NULL) {
2257                 logit("Received window adjust for non-open channel %d.", id);
2258                 return;
2259         }
2260         adjust = packet_get_int();
2261         packet_check_eom();
2262         debug2("channel %d: rcvd adjust %u", id, adjust);
2263         c->remote_window += adjust;
2264 }
2265
2266 void
2267 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2268 {
2269         Channel *c = NULL;
2270         u_short host_port;
2271         char *host, *originator_string;
2272         int remote_id, sock = -1;
2273
2274         remote_id = packet_get_int();
2275         host = packet_get_string(NULL);
2276         host_port = packet_get_int();
2277
2278         if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2279                 originator_string = packet_get_string(NULL);
2280         } else {
2281                 originator_string = xstrdup("unknown (remote did not supply name)");
2282         }
2283         packet_check_eom();
2284         sock = channel_connect_to(host, host_port);
2285         if (sock != -1) {
2286                 c = channel_new("connected socket",
2287                     SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2288                     originator_string, 1);
2289                 c->remote_id = remote_id;
2290         }
2291         xfree(originator_string);
2292         if (c == NULL) {
2293                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2294                 packet_put_int(remote_id);
2295                 packet_send();
2296         }
2297         xfree(host);
2298 }
2299
2300
2301 /* -- tcp forwarding */
2302
2303 void
2304 channel_set_af(int af)
2305 {
2306         IPv4or6 = af;
2307 }
2308
2309 static int
2310 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2311     const char *host_to_connect, u_short port_to_connect, int gateway_ports, 
2312     int hpn_disabled, int hpn_buffer_size)
2313 {
2314         Channel *c;
2315         int sock, r, success = 0, wildcard = 0, is_client;
2316         struct addrinfo hints, *ai, *aitop;
2317         const char *host, *addr;
2318         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2319
2320         host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2321             listen_addr : host_to_connect;
2322         is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2323
2324         if (host == NULL) {
2325                 error("No forward host name.");
2326                 return 0;
2327         }
2328         if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2329                 error("Forward host name too long.");
2330                 return 0;
2331         }
2332
2333         /*
2334          * Determine whether or not a port forward listens to loopback,
2335          * specified address or wildcard. On the client, a specified bind
2336          * address will always override gateway_ports. On the server, a
2337          * gateway_ports of 1 (``yes'') will override the client's
2338          * specification and force a wildcard bind, whereas a value of 2
2339          * (``clientspecified'') will bind to whatever address the client
2340          * asked for.
2341          *
2342          * Special-case listen_addrs are:
2343          *
2344          * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2345          * "" (empty string), "*"  -> wildcard v4/v6
2346          * "localhost"             -> loopback v4/v6
2347          */
2348         addr = NULL;
2349         if (listen_addr == NULL) {
2350                 /* No address specified: default to gateway_ports setting */
2351                 if (gateway_ports)
2352                         wildcard = 1;
2353         } else if (gateway_ports || is_client) {
2354                 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2355                     strcmp(listen_addr, "0.0.0.0") == 0) ||
2356                     *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2357                     (!is_client && gateway_ports == 1))
2358                         wildcard = 1;
2359                 else if (strcmp(listen_addr, "localhost") != 0)
2360                         addr = listen_addr;
2361         }
2362
2363         debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2364             type, wildcard, (addr == NULL) ? "NULL" : addr);
2365
2366         /*
2367          * getaddrinfo returns a loopback address if the hostname is
2368          * set to NULL and hints.ai_flags is not AI_PASSIVE
2369          */
2370         memset(&hints, 0, sizeof(hints));
2371         hints.ai_family = IPv4or6;
2372         hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2373         hints.ai_socktype = SOCK_STREAM;
2374         snprintf(strport, sizeof strport, "%d", listen_port);
2375         if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2376                 if (addr == NULL) {
2377                         /* This really shouldn't happen */
2378                         packet_disconnect("getaddrinfo: fatal error: %s",
2379                             gai_strerror(r));
2380                 } else {
2381                         error("channel_setup_fwd_listener: "
2382                             "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
2383                 }
2384                 return 0;
2385         }
2386
2387         for (ai = aitop; ai; ai = ai->ai_next) {
2388                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2389                         continue;
2390                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2391                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2392                         error("channel_setup_fwd_listener: getnameinfo failed");
2393                         continue;
2394                 }
2395                 /* Create a port to listen for the host. */
2396                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2397                 if (sock < 0) {
2398                         /* this is no error since kernel may not support ipv6 */
2399                         verbose("socket: %.100s", strerror(errno));
2400                         continue;
2401                 }
2402
2403                 channel_set_reuseaddr(sock);
2404
2405                 debug("Local forwarding listening on %s port %s.", ntop, strport);
2406
2407                 /* Bind the socket to the address. */
2408                 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2409                         /* address can be in use ipv6 address is already bound */
2410                         if (!ai->ai_next)
2411                                 error("bind: %.100s", strerror(errno));
2412                         else
2413                                 verbose("bind: %.100s", strerror(errno));
2414
2415                         close(sock);
2416                         continue;
2417                 }
2418                 /* Start listening for connections on the socket. */
2419                 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2420                         error("listen: %.100s", strerror(errno));
2421                         close(sock);
2422                         continue;
2423                 }
2424                 /* Allocate a channel number for the socket. */
2425                 /* explicitly test for hpn disabled option. if true use smaller window size */
2426                 if (hpn_disabled)
2427                         c = channel_new("port listener", type, sock, sock, -1,
2428                           CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2429                           0, "port listener", 1); 
2430                 else
2431                         c = channel_new("port listener", type, sock, sock, -1,
2432                           hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
2433                           0, "port listener", 1); 
2434                 strlcpy(c->path, host, sizeof(c->path));
2435                 c->host_port = port_to_connect;
2436                 c->listening_port = listen_port;
2437                 success = 1;
2438         }
2439         if (success == 0)
2440                 error("channel_setup_fwd_listener: cannot listen to port: %d",
2441                     listen_port);
2442         freeaddrinfo(aitop);
2443         return success;
2444 }
2445
2446 int
2447 channel_cancel_rport_listener(const char *host, u_short port)
2448 {
2449         u_int i;
2450         int found = 0;
2451
2452         for (i = 0; i < channels_alloc; i++) {
2453                 Channel *c = channels[i];
2454
2455                 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2456                     strncmp(c->path, host, sizeof(c->path)) == 0 &&
2457                     c->listening_port == port) {
2458                         debug2("%s: close channel %d", __func__, i);
2459                         channel_free(c);
2460                         found = 1;
2461                 }
2462         }
2463
2464         return (found);
2465 }
2466
2467 /* protocol local port fwd, used by ssh (and sshd in v1) */
2468 int
2469 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2470     const char *host_to_connect, u_short port_to_connect, int gateway_ports, 
2471     int hpn_disabled, int hpn_buffer_size)
2472 {
2473         return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2474             listen_host, listen_port, host_to_connect, port_to_connect,
2475             gateway_ports, hpn_disabled, hpn_buffer_size);
2476 }
2477
2478 /* protocol v2 remote port fwd, used by sshd */
2479 int
2480 channel_setup_remote_fwd_listener(const char *listen_address,
2481     u_short listen_port, int gateway_ports, int hpn_disabled, int hpn_buffer_size)
2482 {
2483         return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2484             listen_address, listen_port, NULL, 0, gateway_ports, 
2485             hpn_disabled, hpn_buffer_size);
2486 }
2487
2488 /*
2489  * Initiate forwarding of connections to port "port" on remote host through
2490  * the secure channel to host:port from local side.
2491  */
2492
2493 void
2494 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2495     const char *host_to_connect, u_short port_to_connect)
2496 {
2497         int type, success = 0;
2498
2499         /* Record locally that connection to this host/port is permitted. */
2500         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2501                 fatal("channel_request_remote_forwarding: too many forwards");
2502
2503         /* Send the forward request to the remote side. */
2504         if (compat20) {
2505                 const char *address_to_bind;
2506                 if (listen_host == NULL)
2507                         address_to_bind = "localhost";
2508                 else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
2509                         address_to_bind = "";
2510                 else
2511                         address_to_bind = listen_host;
2512
2513                 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2514                 packet_put_cstring("tcpip-forward");
2515                 packet_put_char(1);                     /* boolean: want reply */
2516                 packet_put_cstring(address_to_bind);
2517                 packet_put_int(listen_port);
2518                 packet_send();
2519                 packet_write_wait();
2520                 /* Assume that server accepts the request */
2521                 success = 1;
2522         } else {
2523                 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2524                 packet_put_int(listen_port);
2525                 packet_put_cstring(host_to_connect);
2526                 packet_put_int(port_to_connect);
2527                 packet_send();
2528                 packet_write_wait();
2529
2530                 /* Wait for response from the remote side. */
2531                 type = packet_read();
2532                 switch (type) {
2533                 case SSH_SMSG_SUCCESS:
2534                         success = 1;
2535                         break;
2536                 case SSH_SMSG_FAILURE:
2537                         logit("Warning: Server denied remote port forwarding.");
2538                         break;
2539                 default:
2540                         /* Unknown packet */
2541                         packet_disconnect("Protocol error for port forward request:"
2542                             "received packet type %d.", type);
2543                 }
2544         }
2545         if (success) {
2546                 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2547                 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2548                 permitted_opens[num_permitted_opens].listen_port = listen_port;
2549                 num_permitted_opens++;
2550         }
2551 }
2552
2553 /*
2554  * Request cancellation of remote forwarding of connection host:port from
2555  * local side.
2556  */
2557 void
2558 channel_request_rforward_cancel(const char *host, u_short port)
2559 {
2560         int i;
2561
2562         if (!compat20)
2563                 return;
2564
2565         for (i = 0; i < num_permitted_opens; i++) {
2566                 if (permitted_opens[i].host_to_connect != NULL &&
2567                     permitted_opens[i].listen_port == port)
2568                         break;
2569         }
2570         if (i >= num_permitted_opens) {
2571                 debug("%s: requested forward not found", __func__);
2572                 return;
2573         }
2574         packet_start(SSH2_MSG_GLOBAL_REQUEST);
2575         packet_put_cstring("cancel-tcpip-forward");
2576         packet_put_char(0);
2577         packet_put_cstring(host == NULL ? "" : host);
2578         packet_put_int(port);
2579         packet_send();
2580
2581         permitted_opens[i].listen_port = 0;
2582         permitted_opens[i].port_to_connect = 0;
2583         xfree(permitted_opens[i].host_to_connect);
2584         permitted_opens[i].host_to_connect = NULL;
2585 }
2586
2587 /*
2588  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
2589  * listening for the port, and sends back a success reply (or disconnect
2590  * message if there was an error).  This never returns if there was an error.
2591  */
2592
2593 void
2594 channel_input_port_forward_request(int is_root, int gateway_ports, 
2595         int hpn_disabled, int hpn_buffer_size)
2596 {
2597         u_short port, host_port;
2598         char *hostname;
2599
2600         /* Get arguments from the packet. */
2601         port = packet_get_int();
2602         hostname = packet_get_string(NULL);
2603         host_port = packet_get_int();
2604
2605 #ifndef HAVE_CYGWIN
2606         /*
2607          * Check that an unprivileged user is not trying to forward a
2608          * privileged port.
2609          */
2610         if (port < IPPORT_RESERVED && !is_root)
2611                 packet_disconnect(
2612                     "Requested forwarding of port %d but user is not root.",
2613                     port);
2614         if (host_port == 0)
2615                 packet_disconnect("Dynamic forwarding denied.");
2616 #endif
2617
2618         /* Initiate forwarding */
2619         channel_setup_local_fwd_listener(NULL, port, hostname,
2620             host_port, gateway_ports, hpn_disabled, hpn_buffer_size);
2621
2622         /* Free the argument string. */
2623         xfree(hostname);
2624 }
2625
2626 /*
2627  * Permits opening to any host/port if permitted_opens[] is empty.  This is
2628  * usually called by the server, because the user could connect to any port
2629  * anyway, and the server has no way to know but to trust the client anyway.
2630  */
2631 void
2632 channel_permit_all_opens(void)
2633 {
2634         if (num_permitted_opens == 0)
2635                 all_opens_permitted = 1;
2636 }
2637
2638 void
2639 channel_add_permitted_opens(char *host, int port)
2640 {
2641         if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2642                 fatal("channel_request_remote_forwarding: too many forwards");
2643         debug("allow port forwarding to host %s port %d", host, port);
2644
2645         permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2646         permitted_opens[num_permitted_opens].port_to_connect = port;
2647         num_permitted_opens++;
2648
2649         all_opens_permitted = 0;
2650 }
2651
2652 void
2653 channel_clear_permitted_opens(void)
2654 {
2655         int i;
2656
2657         for (i = 0; i < num_permitted_opens; i++)
2658                 if (permitted_opens[i].host_to_connect != NULL)
2659                         xfree(permitted_opens[i].host_to_connect);
2660         num_permitted_opens = 0;
2661
2662 }
2663
2664
2665 /* return socket to remote host, port */
2666 static int
2667 connect_to(const char *host, u_short port)
2668 {
2669         struct addrinfo hints, *ai, *aitop;
2670         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2671         int gaierr;
2672         int sock = -1;
2673
2674         memset(&hints, 0, sizeof(hints));
2675         hints.ai_family = IPv4or6;
2676         hints.ai_socktype = SOCK_STREAM;
2677         snprintf(strport, sizeof strport, "%d", port);
2678         if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2679                 error("connect_to %.100s: unknown host (%s)", host,
2680                     gai_strerror(gaierr));
2681                 return -1;
2682         }
2683         for (ai = aitop; ai; ai = ai->ai_next) {
2684                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2685                         continue;
2686                 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2687                     strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2688                         error("connect_to: getnameinfo failed");
2689                         continue;
2690                 }
2691                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2692                 if (sock < 0) {
2693                         if (ai->ai_next == NULL)
2694                                 error("socket: %.100s", strerror(errno));
2695                         else
2696                                 verbose("socket: %.100s", strerror(errno));
2697                         continue;
2698                 }
2699                 if (set_nonblock(sock) == -1)
2700                         fatal("%s: set_nonblock(%d)", __func__, sock);
2701                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2702                     errno != EINPROGRESS) {
2703                         error("connect_to %.100s port %s: %.100s", ntop, strport,
2704                             strerror(errno));
2705                         close(sock);
2706                         continue;       /* fail -- try next */
2707                 }
2708                 break; /* success */
2709
2710         }
2711         freeaddrinfo(aitop);
2712         if (!ai) {
2713                 error("connect_to %.100s port %d: failed.", host, port);
2714                 return -1;
2715         }
2716         /* success */
2717         set_nodelay(sock);
2718         return sock;
2719 }
2720
2721 int
2722 channel_connect_by_listen_address(u_short listen_port)
2723 {
2724         int i;
2725
2726         for (i = 0; i < num_permitted_opens; i++)
2727                 if (permitted_opens[i].host_to_connect != NULL &&
2728                     permitted_opens[i].listen_port == listen_port)
2729                         return connect_to(
2730                             permitted_opens[i].host_to_connect,
2731                             permitted_opens[i].port_to_connect);
2732         error("WARNING: Server requests forwarding for unknown listen_port %d",
2733             listen_port);
2734         return -1;
2735 }
2736
2737 /* Check if connecting to that port is permitted and connect. */
2738 int
2739 channel_connect_to(const char *host, u_short port)
2740 {
2741         int i, permit;
2742
2743         permit = all_opens_permitted;
2744         if (!permit) {
2745                 for (i = 0; i < num_permitted_opens; i++)
2746                         if (permitted_opens[i].host_to_connect != NULL &&
2747                             permitted_opens[i].port_to_connect == port &&
2748                             strcmp(permitted_opens[i].host_to_connect, host) == 0)
2749                                 permit = 1;
2750
2751         }
2752         if (!permit) {
2753                 logit("Received request to connect to host %.100s port %d, "
2754                     "but the request was denied.", host, port);
2755                 return -1;
2756         }
2757         return connect_to(host, port);
2758 }
2759
2760 void
2761 channel_send_window_changes(void)
2762 {
2763         u_int i;
2764         struct winsize ws;
2765
2766         for (i = 0; i < channels_alloc; i++) {
2767                 if (channels[i] == NULL || !channels[i]->client_tty ||
2768                     channels[i]->type != SSH_CHANNEL_OPEN)
2769                         continue;
2770                 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2771                         continue;
2772                 channel_request_start(i, "window-change", 0);
2773                 packet_put_int(ws.ws_col);
2774                 packet_put_int(ws.ws_row);
2775                 packet_put_int(ws.ws_xpixel);
2776                 packet_put_int(ws.ws_ypixel);
2777                 packet_send();
2778         }
2779 }
2780
2781 /* -- X11 forwarding */
2782
2783 /*
2784  * Creates an internet domain socket for listening for X11 connections.
2785  * Returns 0 and a suitable display number for the DISPLAY variable
2786  * stored in display_numberp , or -1 if an error occurs.
2787  */
2788 int
2789 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2790     int single_connection, u_int *display_numberp, int **chanids, 
2791     int hpn_disabled, int hpn_buffer_size)
2792 {
2793         Channel *nc = NULL;
2794         int display_number, sock;
2795         u_short port;
2796         struct addrinfo hints, *ai, *aitop;
2797         char strport[NI_MAXSERV];
2798         int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2799
2800         if (chanids == NULL)
2801                 return -1;
2802
2803         for (display_number = x11_display_offset;
2804             display_number < MAX_DISPLAYS;
2805             display_number++) {
2806                 port = 6000 + display_number;
2807                 memset(&hints, 0, sizeof(hints));
2808                 hints.ai_family = IPv4or6;
2809                 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2810                 hints.ai_socktype = SOCK_STREAM;
2811                 snprintf(strport, sizeof strport, "%d", port);
2812                 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2813                         error("getaddrinfo: %.100s", gai_strerror(gaierr));
2814                         return -1;
2815                 }
2816                 for (ai = aitop; ai; ai = ai->ai_next) {
2817                         if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2818                                 continue;
2819                         sock = socket(ai->ai_family, ai->ai_socktype,
2820                             ai->ai_protocol);
2821                         if (sock < 0) {
2822                                 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2823                                         error("socket: %.100s", strerror(errno));
2824                                         freeaddrinfo(aitop);
2825                                         return -1;
2826                                 } else {
2827                                         debug("x11_create_display_inet: Socket family %d not supported",
2828                                                  ai->ai_family);
2829                                         continue;
2830                                 }
2831                         }
2832 #ifdef IPV6_V6ONLY
2833                         if (ai->ai_family == AF_INET6) {
2834                                 int on = 1;
2835                                 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2836                                         error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2837                         }
2838 #endif
2839                         channel_set_reuseaddr(sock);
2840                         if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2841                                 debug2("bind port %d: %.100s", port, strerror(errno));
2842                                 close(sock);
2843
2844                                 if (ai->ai_next)
2845                                         continue;
2846
2847                                 for (n = 0; n < num_socks; n++) {
2848                                         close(socks[n]);
2849                                 }
2850                                 num_socks = 0;
2851                                 break;
2852                         }
2853                         socks[num_socks++] = sock;
2854 #ifndef DONT_TRY_OTHER_AF
2855                         if (num_socks == NUM_SOCKS)
2856                                 break;
2857 #else
2858                         if (x11_use_localhost) {
2859                                 if (num_socks == NUM_SOCKS)
2860                                         break;
2861                         } else {
2862                                 break;
2863                         }
2864 #endif
2865                 }
2866                 freeaddrinfo(aitop);
2867                 if (num_socks > 0)
2868                         break;
2869         }
2870         if (display_number >= MAX_DISPLAYS) {
2871                 error("Failed to allocate internet-domain X11 display socket.");
2872                 return -1;
2873         }
2874         /* Start listening for connections on the socket. */
2875         for (n = 0; n < num_socks; n++) {
2876                 sock = socks[n];
2877                 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2878                         error("listen: %.100s", strerror(errno));
2879                         close(sock);
2880                         return -1;
2881                 }
2882         }
2883
2884         /* Allocate a channel for each socket. */
2885         *chanids = xmalloc(sizeof(**chanids) * (num_socks + 1));
2886         for (n = 0; n < num_socks; n++) {
2887                 sock = socks[n];
2888                 if (hpn_disabled) 
2889                         nc = channel_new("x11 listener",
2890                             SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2891                             CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2892                             0, "X11 inet listener", 1);
2893                 else 
2894                         nc = channel_new("x11 listener",
2895                             SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2896                             hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
2897                             0, "X11 inet listener", 1);
2898                 nc->single_connection = single_connection;
2899                 (*chanids)[n] = nc->self;
2900         }
2901         (*chanids)[n] = -1;
2902
2903         /* Return the display number for the DISPLAY environment variable. */
2904         *display_numberp = display_number;
2905         return (0);
2906 }
2907
2908 static int
2909 connect_local_xsocket(u_int dnr)
2910 {
2911         int sock;
2912         struct sockaddr_un addr;
2913
2914         sock = socket(AF_UNIX, SOCK_STREAM, 0);
2915         if (sock < 0)
2916                 error("socket: %.100s", strerror(errno));
2917         memset(&addr, 0, sizeof(addr));
2918         addr.sun_family = AF_UNIX;
2919         snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2920         if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2921                 return sock;
2922         close(sock);
2923         error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2924         return -1;
2925 }
2926
2927 int
2928 x11_connect_display(void)
2929 {
2930         int display_number, sock = 0;
2931         const char *display;
2932         char buf[1024], *cp;
2933         struct addrinfo hints, *ai, *aitop;
2934         char strport[NI_MAXSERV];
2935         int gaierr;
2936
2937         /* Try to open a socket for the local X server. */
2938         display = getenv("DISPLAY");
2939         if (!display) {
2940                 error("DISPLAY not set.");
2941                 return -1;
2942         }
2943         /*
2944          * Now we decode the value of the DISPLAY variable and make a
2945          * connection to the real X server.
2946          */
2947
2948         /*
2949          * Check if it is a unix domain socket.  Unix domain displays are in
2950          * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2951          */
2952         if (strncmp(display, "unix:", 5) == 0 ||
2953             display[0] == ':') {
2954                 /* Connect to the unix domain socket. */
2955                 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2956                         error("Could not parse display number from DISPLAY: %.100s",
2957                             display);
2958                         return -1;
2959                 }
2960                 /* Create a socket. */
2961                 sock = connect_local_xsocket(display_number);
2962                 if (sock < 0)
2963                         return -1;
2964
2965                 /* OK, we now have a connection to the display. */
2966                 return sock;
2967         }
2968         /*
2969          * Connect to an inet socket.  The DISPLAY value is supposedly
2970          * hostname:d[.s], where hostname may also be numeric IP address.
2971          */
2972         strlcpy(buf, display, sizeof(buf));
2973         cp = strchr(buf, ':');
2974         if (!cp) {
2975                 error("Could not find ':' in DISPLAY: %.100s", display);
2976                 return -1;
2977         }
2978         *cp = 0;
2979         /* buf now contains the host name.  But first we parse the display number. */
2980         if (sscanf(cp + 1, "%d", &display_number) != 1) {
2981                 error("Could not parse display number from DISPLAY: %.100s",
2982                     display);
2983                 return -1;
2984         }
2985
2986         /* Look up the host address */
2987         memset(&hints, 0, sizeof(hints));
2988         hints.ai_family = IPv4or6;
2989         hints.ai_socktype = SOCK_STREAM;
2990         snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2991         if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2992                 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2993                 return -1;
2994         }
2995         for (ai = aitop; ai; ai = ai->ai_next) {
2996                 /* Create a socket. */
2997                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2998                 if (sock < 0) {
2999                         debug2("socket: %.100s", strerror(errno));
3000                         continue;
3001                 }
3002                 /* Connect it to the display. */
3003                 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3004                         debug2("connect %.100s port %d: %.100s", buf,
3005                             6000 + display_number, strerror(errno));
3006                         close(sock);
3007                         continue;
3008                 }
3009                 /* Success */
3010                 break;
3011         }
3012         freeaddrinfo(aitop);
3013         if (!ai) {
3014                 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
3015                     strerror(errno));
3016                 return -1;
3017         }
3018         set_nodelay(sock);
3019         return sock;
3020 }
3021
3022 /*
3023  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
3024  * the remote channel number.  We should do whatever we want, and respond
3025  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3026  */
3027
3028 void
3029 x11_input_open(int type, u_int32_t seq, void *ctxt)
3030 {
3031         Channel *c = NULL;
3032         int remote_id, sock = 0;
3033         char *remote_host;
3034
3035         debug("Received X11 open request.");
3036
3037         remote_id = packet_get_int();
3038
3039         if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3040                 remote_host = packet_get_string(NULL);
3041         } else {
3042                 remote_host = xstrdup("unknown (remote did not supply name)");
3043         }
3044         packet_check_eom();
3045
3046         /* Obtain a connection to the real X display. */
3047         sock = x11_connect_display();
3048         if (sock != -1) {
3049                 /* Allocate a channel for this connection. */
3050                 c = channel_new("connected x11 socket",
3051                     SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3052                     remote_host, 1);
3053                 c->remote_id = remote_id;
3054                 c->force_drain = 1;
3055         }
3056         xfree(remote_host);
3057         if (c == NULL) {
3058                 /* Send refusal to the remote host. */
3059                 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3060                 packet_put_int(remote_id);
3061         } else {
3062                 /* Send a confirmation to the remote host. */
3063                 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3064                 packet_put_int(remote_id);
3065                 packet_put_int(c->self);
3066         }
3067         packet_send();
3068 }
3069
3070 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3071 void
3072 deny_input_open(int type, u_int32_t seq, void *ctxt)
3073 {
3074         int rchan = packet_get_int();
3075
3076         switch (type) {
3077         case SSH_SMSG_AGENT_OPEN:
3078                 error("Warning: ssh server tried agent forwarding.");
3079                 break;
3080         case SSH_SMSG_X11_OPEN:
3081                 error("Warning: ssh server tried X11 forwarding.");
3082                 break;
3083         default:
3084                 error("deny_input_open: type %d", type);
3085                 break;
3086         }
3087         error("Warning: this is probably a break-in attempt by a malicious server.");
3088         packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3089         packet_put_int(rchan);
3090         packet_send();
3091 }
3092
3093 /*
3094  * Requests forwarding of X11 connections, generates fake authentication
3095  * data, and enables authentication spoofing.
3096  * This should be called in the client only.
3097  */
3098 void
3099 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3100     const char *proto, const char *data)
3101 {
3102         u_int data_len = (u_int) strlen(data) / 2;
3103         u_int i, value;
3104         char *new_data;
3105         int screen_number;
3106         const char *cp;
3107         u_int32_t rnd = 0;
3108
3109         if (x11_saved_display == NULL)
3110                 x11_saved_display = xstrdup(disp);
3111         else if (strcmp(disp, x11_saved_display) != 0) {
3112                 error("x11_request_forwarding_with_spoofing: different "
3113                     "$DISPLAY already forwarded");
3114                 return;
3115         }
3116
3117         cp = disp;
3118         if (disp)
3119                 cp = strchr(disp, ':');
3120         if (cp)
3121                 cp = strchr(cp, '.');
3122         if (cp)
3123                 screen_number = atoi(cp + 1);
3124         else
3125                 screen_number = 0;
3126
3127         if (x11_saved_proto == NULL) {
3128                 /* Save protocol name. */
3129                 x11_saved_proto = xstrdup(proto);
3130                 /*
3131                  * Extract real authentication data and generate fake data
3132                  * of the same length.
3133                  */
3134                 x11_saved_data = xmalloc(data_len);
3135                 x11_fake_data = xmalloc(data_len);
3136                 for (i = 0; i < data_len; i++) {
3137                         if (sscanf(data + 2 * i, "%2x", &value) != 1)
3138                                 fatal("x11_request_forwarding: bad "
3139                                     "authentication data: %.100s", data);
3140                         if (i % 4 == 0)
3141                                 rnd = arc4random();
3142                         x11_saved_data[i] = value;
3143                         x11_fake_data[i] = rnd & 0xff;
3144                         rnd >>= 8;
3145                 }
3146                 x11_saved_data_len = data_len;
3147                 x11_fake_data_len = data_len;
3148         }
3149
3150         /* Convert the fake data into hex. */
3151         new_data = tohex(x11_fake_data, data_len);
3152
3153         /* Send the request packet. */
3154         if (compat20) {
3155                 channel_request_start(client_session_id, "x11-req", 0);
3156                 packet_put_char(0);     /* XXX bool single connection */
3157         } else {
3158                 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3159         }
3160         packet_put_cstring(proto);
3161         packet_put_cstring(new_data);
3162         packet_put_int(screen_number);
3163         packet_send();
3164         packet_write_wait();
3165         xfree(new_data);
3166 }
3167
3168
3169 /* -- agent forwarding */
3170
3171 /* Sends a message to the server to request authentication fd forwarding. */
3172
3173 void
3174 auth_request_forwarding(void)
3175 {
3176         packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3177         packet_send();
3178         packet_write_wait();
3179 }
This page took 0.293827 seconds and 5 git commands to generate.