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