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