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