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