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