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