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