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