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