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