xref: /freebsd/crypto/openssh/channels.c (revision 87c1498d1a7473ff983e5c0456f30608f3f1e601)
1 /* $OpenBSD: channels.c,v 1.415 2022/03/30 21:10:25 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 
2605 	/* Allocate 4x pollfd for each channel (rfd, wfd, efd, sock) */
2606 	if (sc->channels_alloc >= (INT_MAX / 4) - npfd_reserved)
2607 		fatal_f("too many channels"); /* shouldn't happen */
2608 	if (!ssh_packet_is_rekeying(ssh))
2609 		npfd += sc->channels_alloc * 4;
2610 	if (npfd > *npfd_allocp) {
2611 		*pfdp = xrecallocarray(*pfdp, *npfd_allocp,
2612 		    npfd, sizeof(**pfdp));
2613 		*npfd_allocp = npfd;
2614 	}
2615 	*npfd_activep = npfd_reserved;
2616 	if (ssh_packet_is_rekeying(ssh))
2617 		return;
2618 
2619 	oalloc = sc->channels_alloc;
2620 
2621 	channel_handler(ssh, CHAN_PRE, minwait_secs);
2622 
2623 	if (oalloc != sc->channels_alloc) {
2624 		/* shouldn't happen */
2625 		fatal_f("channels_alloc changed during CHAN_PRE "
2626 		    "(was %u, now %u)", oalloc, sc->channels_alloc);
2627 	}
2628 
2629 	/* Prepare pollfd */
2630 	p = npfd_reserved;
2631 	for (i = 0; i < sc->channels_alloc; i++)
2632 		channel_prepare_pollfd(sc->channels[i], &p, *pfdp, npfd);
2633 	*npfd_activep = p;
2634 }
2635 
2636 static void
2637 fd_ready(Channel *c, int p, struct pollfd *pfds, u_int npfd, int fd,
2638     const char *what, u_int revents_mask, u_int ready)
2639 {
2640 	struct pollfd *pfd = &pfds[p];
2641 
2642 	if (fd == -1)
2643 		return;
2644 	if (p == -1 || (u_int)p >= npfd)
2645 		fatal_f("channel %d: bad pfd %d (max %u)", c->self, p, npfd);
2646 	dump_channel_poll(__func__, what, c, p, pfd);
2647 	if (pfd->fd != fd) {
2648 		fatal("channel %d: inconsistent %s fd=%d pollfd[%u].fd %d "
2649 		    "r%d w%d e%d s%d", c->self, what, fd, p, pfd->fd,
2650 		    c->rfd, c->wfd, c->efd, c->sock);
2651 	}
2652 	if ((pfd->revents & POLLNVAL) != 0) {
2653 		fatal("channel %d: invalid %s pollfd[%u].fd %d r%d w%d e%d s%d",
2654 		    c->self, what, p, pfd->fd, c->rfd, c->wfd, c->efd, c->sock);
2655 	}
2656 	if ((pfd->revents & (revents_mask|POLLHUP|POLLERR)) != 0)
2657 		c->io_ready |= ready & c->io_want;
2658 }
2659 
2660 /*
2661  * After poll, perform any appropriate operations for channels which have
2662  * events pending.
2663  */
2664 void
2665 channel_after_poll(struct ssh *ssh, struct pollfd *pfd, u_int npfd)
2666 {
2667 	struct ssh_channels *sc = ssh->chanctxt;
2668 	u_int i;
2669 	int p;
2670 	Channel *c;
2671 
2672 #ifdef DEBUG_CHANNEL_POLL
2673 	for (p = 0; p < (int)npfd; p++) {
2674 		if (pfd[p].revents == 0)
2675 			continue;
2676 		debug_f("pfd[%u].fd %d rev 0x%04x",
2677 		    p, pfd[p].fd, pfd[p].revents);
2678 	}
2679 #endif
2680 
2681 	/* Convert pollfd into c->io_ready */
2682 	for (i = 0; i < sc->channels_alloc; i++) {
2683 		c = sc->channels[i];
2684 		if (c == NULL)
2685 			continue;
2686 		/* if rfd is shared with efd/sock then wfd should be too */
2687 		if (c->rfd != -1 && c->wfd != -1 && c->rfd != c->wfd &&
2688 		    (c->rfd == c->efd || c->rfd == c->sock)) {
2689 			/* Shouldn't happen */
2690 			fatal_f("channel %d: unexpected fds r%d w%d e%d s%d",
2691 			    c->self, c->rfd, c->wfd, c->efd, c->sock);
2692 		}
2693 		c->io_ready = 0;
2694 		/* rfd, potentially shared with wfd, efd and sock */
2695 		if (c->rfd != -1 && (p = c->pfds[0]) != -1) {
2696 			fd_ready(c, p, pfd, npfd, c->rfd,
2697 			    "rfd", POLLIN, SSH_CHAN_IO_RFD);
2698 			if (c->rfd == c->wfd) {
2699 				fd_ready(c, p, pfd, npfd, c->wfd,
2700 				    "wfd/r", POLLOUT, SSH_CHAN_IO_WFD);
2701 			}
2702 			if (c->rfd == c->efd) {
2703 				fd_ready(c, p, pfd, npfd, c->efd,
2704 				    "efdr/r", POLLIN, SSH_CHAN_IO_EFD_R);
2705 				fd_ready(c, p, pfd, npfd, c->efd,
2706 				    "efdw/r", POLLOUT, SSH_CHAN_IO_EFD_W);
2707 			}
2708 			if (c->rfd == c->sock) {
2709 				fd_ready(c, p, pfd, npfd, c->sock,
2710 				    "sockr/r", POLLIN, SSH_CHAN_IO_SOCK_R);
2711 				fd_ready(c, p, pfd, npfd, c->sock,
2712 				    "sockw/r", POLLOUT, SSH_CHAN_IO_SOCK_W);
2713 			}
2714 			dump_channel_poll(__func__, "rfd", c, p, pfd);
2715 		}
2716 		/* wfd */
2717 		if (c->wfd != -1 && c->wfd != c->rfd &&
2718 		    (p = c->pfds[1]) != -1) {
2719 			fd_ready(c, p, pfd, npfd, c->wfd,
2720 			    "wfd", POLLOUT, SSH_CHAN_IO_WFD);
2721 			dump_channel_poll(__func__, "wfd", c, p, pfd);
2722 		}
2723 		/* efd */
2724 		if (c->efd != -1 && c->efd != c->rfd &&
2725 		    (p = c->pfds[2]) != -1) {
2726 			fd_ready(c, p, pfd, npfd, c->efd,
2727 			    "efdr", POLLIN, SSH_CHAN_IO_EFD_R);
2728 			fd_ready(c, p, pfd, npfd, c->efd,
2729 			    "efdw", POLLOUT, SSH_CHAN_IO_EFD_W);
2730 			dump_channel_poll(__func__, "efd", c, p, pfd);
2731 		}
2732 		/* sock */
2733 		if (c->sock != -1 && c->sock != c->rfd &&
2734 		    (p = c->pfds[3]) != -1) {
2735 			fd_ready(c, p, pfd, npfd, c->sock,
2736 			    "sockr", POLLIN, SSH_CHAN_IO_SOCK_R);
2737 			fd_ready(c, p, pfd, npfd, c->sock,
2738 			    "sockw", POLLOUT, SSH_CHAN_IO_SOCK_W);
2739 			dump_channel_poll(__func__, "sock", c, p, pfd);
2740 		}
2741 	}
2742 	channel_handler(ssh, CHAN_POST, NULL);
2743 }
2744 
2745 /*
2746  * Enqueue data for channels with open or draining c->input.
2747  */
2748 static void
2749 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2750 {
2751 	size_t len, plen;
2752 	const u_char *pkt;
2753 	int r;
2754 
2755 	if ((len = sshbuf_len(c->input)) == 0) {
2756 		if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2757 			/*
2758 			 * input-buffer is empty and read-socket shutdown:
2759 			 * tell peer, that we will not send more data:
2760 			 * send IEOF.
2761 			 * hack for extended data: delay EOF if EFD still
2762 			 * in use.
2763 			 */
2764 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
2765 				debug2("channel %d: "
2766 				    "ibuf_empty delayed efd %d/(%zu)",
2767 				    c->self, c->efd, sshbuf_len(c->extended));
2768 			else
2769 				chan_ibuf_empty(ssh, c);
2770 		}
2771 		return;
2772 	}
2773 
2774 	if (!c->have_remote_id)
2775 		fatal_f("channel %d: no remote id", c->self);
2776 
2777 	if (c->datagram) {
2778 		/* Check datagram will fit; drop if not */
2779 		if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2780 			fatal_fr(r, "channel %i: get datagram", c->self);
2781 		/*
2782 		 * XXX this does tail-drop on the datagram queue which is
2783 		 * usually suboptimal compared to head-drop. Better to have
2784 		 * backpressure at read time? (i.e. read + discard)
2785 		 */
2786 		if (plen > c->remote_window || plen > c->remote_maxpacket) {
2787 			debug("channel %d: datagram too big", c->self);
2788 			return;
2789 		}
2790 		/* Enqueue it */
2791 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2792 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2793 		    (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2794 		    (r = sshpkt_send(ssh)) != 0)
2795 			fatal_fr(r, "channel %i: send datagram", c->self);
2796 		c->remote_window -= plen;
2797 		return;
2798 	}
2799 
2800 	/* Enqueue packet for buffered data. */
2801 	if (len > c->remote_window)
2802 		len = c->remote_window;
2803 	if (len > c->remote_maxpacket)
2804 		len = c->remote_maxpacket;
2805 	if (len == 0)
2806 		return;
2807 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2808 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2809 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2810 	    (r = sshpkt_send(ssh)) != 0)
2811 		fatal_fr(r, "channel %i: send data", c->self);
2812 	if ((r = sshbuf_consume(c->input, len)) != 0)
2813 		fatal_fr(r, "channel %i: consume", c->self);
2814 	c->remote_window -= len;
2815 }
2816 
2817 /*
2818  * Enqueue data for channels with open c->extended in read mode.
2819  */
2820 static void
2821 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2822 {
2823 	size_t len;
2824 	int r;
2825 
2826 	if ((len = sshbuf_len(c->extended)) == 0)
2827 		return;
2828 
2829 	debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2830 	    c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2831 	if (len > c->remote_window)
2832 		len = c->remote_window;
2833 	if (len > c->remote_maxpacket)
2834 		len = c->remote_maxpacket;
2835 	if (len == 0)
2836 		return;
2837 	if (!c->have_remote_id)
2838 		fatal_f("channel %d: no remote id", c->self);
2839 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2840 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2841 	    (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2842 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2843 	    (r = sshpkt_send(ssh)) != 0)
2844 		fatal_fr(r, "channel %i: data", c->self);
2845 	if ((r = sshbuf_consume(c->extended, len)) != 0)
2846 		fatal_fr(r, "channel %i: consume", c->self);
2847 	c->remote_window -= len;
2848 	debug2("channel %d: sent ext data %zu", c->self, len);
2849 }
2850 
2851 /* If there is data to send to the connection, enqueue some of it now. */
2852 void
2853 channel_output_poll(struct ssh *ssh)
2854 {
2855 	struct ssh_channels *sc = ssh->chanctxt;
2856 	Channel *c;
2857 	u_int i;
2858 
2859 	for (i = 0; i < sc->channels_alloc; i++) {
2860 		c = sc->channels[i];
2861 		if (c == NULL)
2862 			continue;
2863 
2864 		/*
2865 		 * We are only interested in channels that can have buffered
2866 		 * incoming data.
2867 		 */
2868 		if (c->type != SSH_CHANNEL_OPEN)
2869 			continue;
2870 		if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2871 			/* XXX is this true? */
2872 			debug3("channel %d: will not send data after close",
2873 			    c->self);
2874 			continue;
2875 		}
2876 
2877 		/* Get the amount of buffered data for this channel. */
2878 		if (c->istate == CHAN_INPUT_OPEN ||
2879 		    c->istate == CHAN_INPUT_WAIT_DRAIN)
2880 			channel_output_poll_input_open(ssh, c);
2881 		/* Send extended data, i.e. stderr */
2882 		if (!(c->flags & CHAN_EOF_SENT) &&
2883 		    c->extended_usage == CHAN_EXTENDED_READ)
2884 			channel_output_poll_extended_read(ssh, c);
2885 	}
2886 }
2887 
2888 /* -- mux proxy support  */
2889 
2890 /*
2891  * When multiplexing channel messages for mux clients we have to deal
2892  * with downstream messages from the mux client and upstream messages
2893  * from the ssh server:
2894  * 1) Handling downstream messages is straightforward and happens
2895  *    in channel_proxy_downstream():
2896  *    - We forward all messages (mostly) unmodified to the server.
2897  *    - However, in order to route messages from upstream to the correct
2898  *      downstream client, we have to replace the channel IDs used by the
2899  *      mux clients with a unique channel ID because the mux clients might
2900  *      use conflicting channel IDs.
2901  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2902  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2903  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2904  *      with the newly allocated channel ID.
2905  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2906  *    channels and processed by channel_proxy_upstream(). The local channel ID
2907  *    is then translated back to the original mux client ID.
2908  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2909  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2910  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2911  *    downstream mux client are removed.
2912  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2913  *    requires more work, because they are not addressed to a specific
2914  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
2915  *    out whether the request is addressed to the local client or a
2916  *    specific downstream client based on the listen-address/port.
2917  * 6) Agent and X11-Forwarding have a similar problem and are currently
2918  *    not supported as the matching session/channel cannot be identified
2919  *    easily.
2920  */
2921 
2922 /*
2923  * receive packets from downstream mux clients:
2924  * channel callback fired on read from mux client, creates
2925  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2926  * on channel creation.
2927  */
2928 int
2929 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2930 {
2931 	Channel *c = NULL;
2932 	struct sshbuf *original = NULL, *modified = NULL;
2933 	const u_char *cp;
2934 	char *ctype = NULL, *listen_host = NULL;
2935 	u_char type;
2936 	size_t have;
2937 	int ret = -1, r;
2938 	u_int id, remote_id, listen_port;
2939 
2940 	/* sshbuf_dump(downstream->input, stderr); */
2941 	if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2942 	    != 0) {
2943 		error_fr(r, "parse");
2944 		return -1;
2945 	}
2946 	if (have < 2) {
2947 		error_f("short message");
2948 		return -1;
2949 	}
2950 	type = cp[1];
2951 	/* skip padlen + type */
2952 	cp += 2;
2953 	have -= 2;
2954 	if (ssh_packet_log_type(type))
2955 		debug3_f("channel %u: down->up: type %u",
2956 		    downstream->self, type);
2957 
2958 	switch (type) {
2959 	case SSH2_MSG_CHANNEL_OPEN:
2960 		if ((original = sshbuf_from(cp, have)) == NULL ||
2961 		    (modified = sshbuf_new()) == NULL) {
2962 			error_f("alloc");
2963 			goto out;
2964 		}
2965 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2966 		    (r = sshbuf_get_u32(original, &id)) != 0) {
2967 			error_fr(r, "parse");
2968 			goto out;
2969 		}
2970 		c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2971 		    -1, -1, -1, 0, 0, 0, ctype, 1);
2972 		c->mux_ctx = downstream;	/* point to mux client */
2973 		c->mux_downstream_id = id;	/* original downstream id */
2974 		if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2975 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2976 		    (r = sshbuf_putb(modified, original)) != 0) {
2977 			error_fr(r, "compose");
2978 			channel_free(ssh, c);
2979 			goto out;
2980 		}
2981 		break;
2982 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2983 		/*
2984 		 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2985 		 * need to parse 'remote_id' instead of 'ctype'.
2986 		 */
2987 		if ((original = sshbuf_from(cp, have)) == NULL ||
2988 		    (modified = sshbuf_new()) == NULL) {
2989 			error_f("alloc");
2990 			goto out;
2991 		}
2992 		if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2993 		    (r = sshbuf_get_u32(original, &id)) != 0) {
2994 			error_fr(r, "parse");
2995 			goto out;
2996 		}
2997 		c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2998 		    -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
2999 		c->mux_ctx = downstream;	/* point to mux client */
3000 		c->mux_downstream_id = id;
3001 		c->remote_id = remote_id;
3002 		c->have_remote_id = 1;
3003 		if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
3004 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3005 		    (r = sshbuf_putb(modified, original)) != 0) {
3006 			error_fr(r, "compose");
3007 			channel_free(ssh, c);
3008 			goto out;
3009 		}
3010 		break;
3011 	case SSH2_MSG_GLOBAL_REQUEST:
3012 		if ((original = sshbuf_from(cp, have)) == NULL) {
3013 			error_f("alloc");
3014 			goto out;
3015 		}
3016 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
3017 			error_fr(r, "parse");
3018 			goto out;
3019 		}
3020 		if (strcmp(ctype, "tcpip-forward") != 0) {
3021 			error_f("unsupported request %s", ctype);
3022 			goto out;
3023 		}
3024 		if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
3025 		    (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
3026 		    (r = sshbuf_get_u32(original, &listen_port)) != 0) {
3027 			error_fr(r, "parse");
3028 			goto out;
3029 		}
3030 		if (listen_port > 65535) {
3031 			error_f("tcpip-forward for %s: bad port %u",
3032 			    listen_host, listen_port);
3033 			goto out;
3034 		}
3035 		/* Record that connection to this host/port is permitted. */
3036 		permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
3037 		    listen_host, NULL, (int)listen_port, downstream);
3038 		listen_host = NULL;
3039 		break;
3040 	case SSH2_MSG_CHANNEL_CLOSE:
3041 		if (have < 4)
3042 			break;
3043 		remote_id = PEEK_U32(cp);
3044 		if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
3045 			if (c->flags & CHAN_CLOSE_RCVD)
3046 				channel_free(ssh, c);
3047 			else
3048 				c->flags |= CHAN_CLOSE_SENT;
3049 		}
3050 		break;
3051 	}
3052 	if (modified) {
3053 		if ((r = sshpkt_start(ssh, type)) != 0 ||
3054 		    (r = sshpkt_putb(ssh, modified)) != 0 ||
3055 		    (r = sshpkt_send(ssh)) != 0) {
3056 			error_fr(r, "send");
3057 			goto out;
3058 		}
3059 	} else {
3060 		if ((r = sshpkt_start(ssh, type)) != 0 ||
3061 		    (r = sshpkt_put(ssh, cp, have)) != 0 ||
3062 		    (r = sshpkt_send(ssh)) != 0) {
3063 			error_fr(r, "send");
3064 			goto out;
3065 		}
3066 	}
3067 	ret = 0;
3068  out:
3069 	free(ctype);
3070 	free(listen_host);
3071 	sshbuf_free(original);
3072 	sshbuf_free(modified);
3073 	return ret;
3074 }
3075 
3076 /*
3077  * receive packets from upstream server and de-multiplex packets
3078  * to correct downstream:
3079  * implemented as a helper for channel input handlers,
3080  * replaces local (proxy) channel ID with downstream channel ID.
3081  */
3082 int
3083 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
3084 {
3085 	struct sshbuf *b = NULL;
3086 	Channel *downstream;
3087 	const u_char *cp = NULL;
3088 	size_t len;
3089 	int r;
3090 
3091 	/*
3092 	 * When receiving packets from the peer we need to check whether we
3093 	 * need to forward the packets to the mux client. In this case we
3094 	 * restore the original channel id and keep track of CLOSE messages,
3095 	 * so we can cleanup the channel.
3096 	 */
3097 	if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
3098 		return 0;
3099 	if ((downstream = c->mux_ctx) == NULL)
3100 		return 0;
3101 	switch (type) {
3102 	case SSH2_MSG_CHANNEL_CLOSE:
3103 	case SSH2_MSG_CHANNEL_DATA:
3104 	case SSH2_MSG_CHANNEL_EOF:
3105 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
3106 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3107 	case SSH2_MSG_CHANNEL_OPEN_FAILURE:
3108 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
3109 	case SSH2_MSG_CHANNEL_SUCCESS:
3110 	case SSH2_MSG_CHANNEL_FAILURE:
3111 	case SSH2_MSG_CHANNEL_REQUEST:
3112 		break;
3113 	default:
3114 		debug2_f("channel %u: unsupported type %u", c->self, type);
3115 		return 0;
3116 	}
3117 	if ((b = sshbuf_new()) == NULL) {
3118 		error_f("alloc reply");
3119 		goto out;
3120 	}
3121 	/* get remaining payload (after id) */
3122 	cp = sshpkt_ptr(ssh, &len);
3123 	if (cp == NULL) {
3124 		error_f("no packet");
3125 		goto out;
3126 	}
3127 	/* translate id and send to muxclient */
3128 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* padlen */
3129 	    (r = sshbuf_put_u8(b, type)) != 0 ||
3130 	    (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
3131 	    (r = sshbuf_put(b, cp, len)) != 0 ||
3132 	    (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
3133 		error_fr(r, "compose muxclient");
3134 		goto out;
3135 	}
3136 	/* sshbuf_dump(b, stderr); */
3137 	if (ssh_packet_log_type(type))
3138 		debug3_f("channel %u: up->down: type %u", c->self, type);
3139  out:
3140 	/* update state */
3141 	switch (type) {
3142 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3143 		/* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
3144 		if (cp && len > 4) {
3145 			c->remote_id = PEEK_U32(cp);
3146 			c->have_remote_id = 1;
3147 		}
3148 		break;
3149 	case SSH2_MSG_CHANNEL_CLOSE:
3150 		if (c->flags & CHAN_CLOSE_SENT)
3151 			channel_free(ssh, c);
3152 		else
3153 			c->flags |= CHAN_CLOSE_RCVD;
3154 		break;
3155 	}
3156 	sshbuf_free(b);
3157 	return 1;
3158 }
3159 
3160 /* -- protocol input */
3161 
3162 /* Parse a channel ID from the current packet */
3163 static int
3164 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
3165 {
3166 	u_int32_t id;
3167 	int r;
3168 
3169 	if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
3170 		error_r(r, "%s: parse id", where);
3171 		ssh_packet_disconnect(ssh, "Invalid %s message", what);
3172 	}
3173 	if (id > INT_MAX) {
3174 		error_r(r, "%s: bad channel id %u", where, id);
3175 		ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
3176 	}
3177 	return (int)id;
3178 }
3179 
3180 /* Lookup a channel from an ID in the current packet */
3181 static Channel *
3182 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
3183 {
3184 	int id = channel_parse_id(ssh, where, what);
3185 	Channel *c;
3186 
3187 	if ((c = channel_lookup(ssh, id)) == NULL) {
3188 		ssh_packet_disconnect(ssh,
3189 		    "%s packet referred to nonexistent channel %d", what, id);
3190 	}
3191 	return c;
3192 }
3193 
3194 int
3195 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
3196 {
3197 	const u_char *data;
3198 	size_t data_len, win_len;
3199 	Channel *c = channel_from_packet_id(ssh, __func__, "data");
3200 	int r;
3201 
3202 	if (channel_proxy_upstream(c, type, seq, ssh))
3203 		return 0;
3204 
3205 	/* Ignore any data for non-open channels (might happen on close) */
3206 	if (c->type != SSH_CHANNEL_OPEN &&
3207 	    c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
3208 	    c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
3209 	    c->type != SSH_CHANNEL_X11_OPEN)
3210 		return 0;
3211 
3212 	/* Get the data. */
3213 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3214             (r = sshpkt_get_end(ssh)) != 0)
3215 		fatal_fr(r, "channel %i: get data", c->self);
3216 
3217 	win_len = data_len;
3218 	if (c->datagram)
3219 		win_len += 4;  /* string length header */
3220 
3221 	/*
3222 	 * The sending side reduces its window as it sends data, so we
3223 	 * must 'fake' consumption of the data in order to ensure that window
3224 	 * updates are sent back. Otherwise the connection might deadlock.
3225 	 */
3226 	if (c->ostate != CHAN_OUTPUT_OPEN) {
3227 		c->local_window -= win_len;
3228 		c->local_consumed += win_len;
3229 		return 0;
3230 	}
3231 
3232 	if (win_len > c->local_maxpacket) {
3233 		logit("channel %d: rcvd big packet %zu, maxpack %u",
3234 		    c->self, win_len, c->local_maxpacket);
3235 		return 0;
3236 	}
3237 	if (win_len > c->local_window) {
3238 		logit("channel %d: rcvd too much data %zu, win %u",
3239 		    c->self, win_len, c->local_window);
3240 		return 0;
3241 	}
3242 	c->local_window -= win_len;
3243 
3244 	if (c->datagram) {
3245 		if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3246 			fatal_fr(r, "channel %i: append datagram", c->self);
3247 	} else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3248 		fatal_fr(r, "channel %i: append data", c->self);
3249 
3250 	return 0;
3251 }
3252 
3253 int
3254 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3255 {
3256 	const u_char *data;
3257 	size_t data_len;
3258 	u_int32_t tcode;
3259 	Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3260 	int r;
3261 
3262 	if (channel_proxy_upstream(c, type, seq, ssh))
3263 		return 0;
3264 	if (c->type != SSH_CHANNEL_OPEN) {
3265 		logit("channel %d: ext data for non open", c->self);
3266 		return 0;
3267 	}
3268 	if (c->flags & CHAN_EOF_RCVD) {
3269 		if (ssh->compat & SSH_BUG_EXTEOF)
3270 			debug("channel %d: accepting ext data after eof",
3271 			    c->self);
3272 		else
3273 			ssh_packet_disconnect(ssh, "Received extended_data "
3274 			    "after EOF on channel %d.", c->self);
3275 	}
3276 
3277 	if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3278 		error_fr(r, "parse tcode");
3279 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
3280 	}
3281 	if (c->efd == -1 ||
3282 	    c->extended_usage != CHAN_EXTENDED_WRITE ||
3283 	    tcode != SSH2_EXTENDED_DATA_STDERR) {
3284 		logit("channel %d: bad ext data", c->self);
3285 		return 0;
3286 	}
3287 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3288             (r = sshpkt_get_end(ssh)) != 0) {
3289 		error_fr(r, "parse data");
3290 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
3291 	}
3292 
3293 	if (data_len > c->local_window) {
3294 		logit("channel %d: rcvd too much extended_data %zu, win %u",
3295 		    c->self, data_len, c->local_window);
3296 		return 0;
3297 	}
3298 	debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3299 	/* XXX sshpkt_getb? */
3300 	if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3301 		error_fr(r, "append");
3302 	c->local_window -= data_len;
3303 	return 0;
3304 }
3305 
3306 int
3307 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3308 {
3309 	Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3310 	int r;
3311 
3312         if ((r = sshpkt_get_end(ssh)) != 0) {
3313 		error_fr(r, "parse data");
3314 		ssh_packet_disconnect(ssh, "Invalid ieof message");
3315 	}
3316 
3317 	if (channel_proxy_upstream(c, type, seq, ssh))
3318 		return 0;
3319 	chan_rcvd_ieof(ssh, c);
3320 
3321 	/* XXX force input close */
3322 	if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3323 		debug("channel %d: FORCE input drain", c->self);
3324 		c->istate = CHAN_INPUT_WAIT_DRAIN;
3325 		if (sshbuf_len(c->input) == 0)
3326 			chan_ibuf_empty(ssh, c);
3327 	}
3328 	return 0;
3329 }
3330 
3331 int
3332 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3333 {
3334 	Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3335 	int r;
3336 
3337 	if (channel_proxy_upstream(c, type, seq, ssh))
3338 		return 0;
3339         if ((r = sshpkt_get_end(ssh)) != 0) {
3340 		error_fr(r, "parse data");
3341 		ssh_packet_disconnect(ssh, "Invalid oclose message");
3342 	}
3343 	chan_rcvd_oclose(ssh, c);
3344 	return 0;
3345 }
3346 
3347 int
3348 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3349 {
3350 	Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3351 	u_int32_t remote_window, remote_maxpacket;
3352 	int r;
3353 
3354 	if (channel_proxy_upstream(c, type, seq, ssh))
3355 		return 0;
3356 	if (c->type != SSH_CHANNEL_OPENING)
3357 		ssh_packet_disconnect(ssh, "Received open confirmation for "
3358 		    "non-opening channel %d.", c->self);
3359 	/*
3360 	 * Record the remote channel number and mark that the channel
3361 	 * is now open.
3362 	 */
3363 	if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3364 	    (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3365 	    (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3366             (r = sshpkt_get_end(ssh)) != 0) {
3367 		error_fr(r, "window/maxpacket");
3368 		ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3369 	}
3370 
3371 	c->have_remote_id = 1;
3372 	c->remote_window = remote_window;
3373 	c->remote_maxpacket = remote_maxpacket;
3374 	c->type = SSH_CHANNEL_OPEN;
3375 	if (c->open_confirm) {
3376 		debug2_f("channel %d: callback start", c->self);
3377 		c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3378 		debug2_f("channel %d: callback done", c->self);
3379 	}
3380 	debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3381 	    c->remote_window, c->remote_maxpacket);
3382 	return 0;
3383 }
3384 
3385 static char *
3386 reason2txt(int reason)
3387 {
3388 	switch (reason) {
3389 	case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3390 		return "administratively prohibited";
3391 	case SSH2_OPEN_CONNECT_FAILED:
3392 		return "connect failed";
3393 	case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3394 		return "unknown channel type";
3395 	case SSH2_OPEN_RESOURCE_SHORTAGE:
3396 		return "resource shortage";
3397 	}
3398 	return "unknown reason";
3399 }
3400 
3401 int
3402 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3403 {
3404 	Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3405 	u_int32_t reason;
3406 	char *msg = NULL;
3407 	int r;
3408 
3409 	if (channel_proxy_upstream(c, type, seq, ssh))
3410 		return 0;
3411 	if (c->type != SSH_CHANNEL_OPENING)
3412 		ssh_packet_disconnect(ssh, "Received open failure for "
3413 		    "non-opening channel %d.", c->self);
3414 	if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3415 		error_fr(r, "parse reason");
3416 		ssh_packet_disconnect(ssh, "Invalid open failure message");
3417 	}
3418 	/* skip language */
3419 	if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3420 	    (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3421             (r = sshpkt_get_end(ssh)) != 0) {
3422 		error_fr(r, "parse msg/lang");
3423 		ssh_packet_disconnect(ssh, "Invalid open failure message");
3424 	}
3425 	logit("channel %d: open failed: %s%s%s", c->self,
3426 	    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3427 	free(msg);
3428 	if (c->open_confirm) {
3429 		debug2_f("channel %d: callback start", c->self);
3430 		c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3431 		debug2_f("channel %d: callback done", c->self);
3432 	}
3433 	/* Schedule the channel for cleanup/deletion. */
3434 	chan_mark_dead(ssh, c);
3435 	return 0;
3436 }
3437 
3438 int
3439 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3440 {
3441 	int id = channel_parse_id(ssh, __func__, "window adjust");
3442 	Channel *c;
3443 	u_int32_t adjust;
3444 	u_int new_rwin;
3445 	int r;
3446 
3447 	if ((c = channel_lookup(ssh, id)) == NULL) {
3448 		logit("Received window adjust for non-open channel %d.", id);
3449 		return 0;
3450 	}
3451 
3452 	if (channel_proxy_upstream(c, type, seq, ssh))
3453 		return 0;
3454 	if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3455             (r = sshpkt_get_end(ssh)) != 0) {
3456 		error_fr(r, "parse adjust");
3457 		ssh_packet_disconnect(ssh, "Invalid window adjust message");
3458 	}
3459 	debug2("channel %d: rcvd adjust %u", c->self, adjust);
3460 	if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3461 		fatal("channel %d: adjust %u overflows remote window %u",
3462 		    c->self, adjust, c->remote_window);
3463 	}
3464 	c->remote_window = new_rwin;
3465 	return 0;
3466 }
3467 
3468 int
3469 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3470 {
3471 	int id = channel_parse_id(ssh, __func__, "status confirm");
3472 	Channel *c;
3473 	struct channel_confirm *cc;
3474 
3475 	/* Reset keepalive timeout */
3476 	ssh_packet_set_alive_timeouts(ssh, 0);
3477 
3478 	debug2_f("type %d id %d", type, id);
3479 
3480 	if ((c = channel_lookup(ssh, id)) == NULL) {
3481 		logit_f("%d: unknown", id);
3482 		return 0;
3483 	}
3484 	if (channel_proxy_upstream(c, type, seq, ssh))
3485 		return 0;
3486         if (sshpkt_get_end(ssh) != 0)
3487 		ssh_packet_disconnect(ssh, "Invalid status confirm message");
3488 	if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3489 		return 0;
3490 	cc->cb(ssh, type, c, cc->ctx);
3491 	TAILQ_REMOVE(&c->status_confirms, cc, entry);
3492 	freezero(cc, sizeof(*cc));
3493 	return 0;
3494 }
3495 
3496 /* -- tcp forwarding */
3497 
3498 void
3499 channel_set_af(struct ssh *ssh, int af)
3500 {
3501 	ssh->chanctxt->IPv4or6 = af;
3502 }
3503 
3504 
3505 /*
3506  * Determine whether or not a port forward listens to loopback, the
3507  * specified address or wildcard. On the client, a specified bind
3508  * address will always override gateway_ports. On the server, a
3509  * gateway_ports of 1 (``yes'') will override the client's specification
3510  * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3511  * will bind to whatever address the client asked for.
3512  *
3513  * Special-case listen_addrs are:
3514  *
3515  * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3516  * "" (empty string), "*"  -> wildcard v4/v6
3517  * "localhost"             -> loopback v4/v6
3518  * "127.0.0.1" / "::1"     -> accepted even if gateway_ports isn't set
3519  */
3520 static const char *
3521 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3522     int is_client, struct ForwardOptions *fwd_opts)
3523 {
3524 	const char *addr = NULL;
3525 	int wildcard = 0;
3526 
3527 	if (listen_addr == NULL) {
3528 		/* No address specified: default to gateway_ports setting */
3529 		if (fwd_opts->gateway_ports)
3530 			wildcard = 1;
3531 	} else if (fwd_opts->gateway_ports || is_client) {
3532 		if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3533 		    strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3534 		    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3535 		    (!is_client && fwd_opts->gateway_ports == 1)) {
3536 			wildcard = 1;
3537 			/*
3538 			 * Notify client if they requested a specific listen
3539 			 * address and it was overridden.
3540 			 */
3541 			if (*listen_addr != '\0' &&
3542 			    strcmp(listen_addr, "0.0.0.0") != 0 &&
3543 			    strcmp(listen_addr, "*") != 0) {
3544 				ssh_packet_send_debug(ssh,
3545 				    "Forwarding listen address "
3546 				    "\"%s\" overridden by server "
3547 				    "GatewayPorts", listen_addr);
3548 			}
3549 		} else if (strcmp(listen_addr, "localhost") != 0 ||
3550 		    strcmp(listen_addr, "127.0.0.1") == 0 ||
3551 		    strcmp(listen_addr, "::1") == 0) {
3552 			/*
3553 			 * Accept explicit localhost address when
3554 			 * GatewayPorts=yes. The "localhost" hostname is
3555 			 * deliberately skipped here so it will listen on all
3556 			 * available local address families.
3557 			 */
3558 			addr = listen_addr;
3559 		}
3560 	} else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3561 	    strcmp(listen_addr, "::1") == 0) {
3562 		/*
3563 		 * If a specific IPv4/IPv6 localhost address has been
3564 		 * requested then accept it even if gateway_ports is in
3565 		 * effect. This allows the client to prefer IPv4 or IPv6.
3566 		 */
3567 		addr = listen_addr;
3568 	}
3569 	if (wildcardp != NULL)
3570 		*wildcardp = wildcard;
3571 	return addr;
3572 }
3573 
3574 static int
3575 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3576     struct Forward *fwd, int *allocated_listen_port,
3577     struct ForwardOptions *fwd_opts)
3578 {
3579 	Channel *c;
3580 	int sock, r, success = 0, wildcard = 0, is_client;
3581 	struct addrinfo hints, *ai, *aitop;
3582 	const char *host, *addr;
3583 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3584 	in_port_t *lport_p;
3585 
3586 	is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3587 
3588 	if (is_client && fwd->connect_path != NULL) {
3589 		host = fwd->connect_path;
3590 	} else {
3591 		host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3592 		    fwd->listen_host : fwd->connect_host;
3593 		if (host == NULL) {
3594 			error("No forward host name.");
3595 			return 0;
3596 		}
3597 		if (strlen(host) >= NI_MAXHOST) {
3598 			error("Forward host name too long.");
3599 			return 0;
3600 		}
3601 	}
3602 
3603 	/* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3604 	addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3605 	    is_client, fwd_opts);
3606 	debug3_f("type %d wildcard %d addr %s", type, wildcard,
3607 	    (addr == NULL) ? "NULL" : addr);
3608 
3609 	/*
3610 	 * getaddrinfo returns a loopback address if the hostname is
3611 	 * set to NULL and hints.ai_flags is not AI_PASSIVE
3612 	 */
3613 	memset(&hints, 0, sizeof(hints));
3614 	hints.ai_family = ssh->chanctxt->IPv4or6;
3615 	hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3616 	hints.ai_socktype = SOCK_STREAM;
3617 	snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3618 	if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3619 		if (addr == NULL) {
3620 			/* This really shouldn't happen */
3621 			ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3622 			    ssh_gai_strerror(r));
3623 		} else {
3624 			error_f("getaddrinfo(%.64s): %s", addr,
3625 			    ssh_gai_strerror(r));
3626 		}
3627 		return 0;
3628 	}
3629 	if (allocated_listen_port != NULL)
3630 		*allocated_listen_port = 0;
3631 	for (ai = aitop; ai; ai = ai->ai_next) {
3632 		switch (ai->ai_family) {
3633 		case AF_INET:
3634 			lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3635 			    sin_port;
3636 			break;
3637 		case AF_INET6:
3638 			lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3639 			    sin6_port;
3640 			break;
3641 		default:
3642 			continue;
3643 		}
3644 		/*
3645 		 * If allocating a port for -R forwards, then use the
3646 		 * same port for all address families.
3647 		 */
3648 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
3649 		    fwd->listen_port == 0 && allocated_listen_port != NULL &&
3650 		    *allocated_listen_port > 0)
3651 			*lport_p = htons(*allocated_listen_port);
3652 
3653 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3654 		    strport, sizeof(strport),
3655 		    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3656 			error_f("getnameinfo failed");
3657 			continue;
3658 		}
3659 		/* Create a port to listen for the host. */
3660 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3661 		if (sock == -1) {
3662 			/* this is no error since kernel may not support ipv6 */
3663 			verbose("socket [%s]:%s: %.100s", ntop, strport,
3664 			    strerror(errno));
3665 			continue;
3666 		}
3667 
3668 		set_reuseaddr(sock);
3669 		if (ai->ai_family == AF_INET6)
3670 			sock_set_v6only(sock);
3671 
3672 		debug("Local forwarding listening on %s port %s.",
3673 		    ntop, strport);
3674 
3675 		/* Bind the socket to the address. */
3676 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3677 			/*
3678 			 * address can be in if use ipv6 address is
3679 			 * already bound
3680 			 */
3681 			if (!ai->ai_next)
3682 				error("bind [%s]:%s: %.100s",
3683 				    ntop, strport, strerror(errno));
3684 			else
3685 				verbose("bind [%s]:%s: %.100s",
3686 				    ntop, strport, strerror(errno));
3687 
3688 			close(sock);
3689 			continue;
3690 		}
3691 		/* Start listening for connections on the socket. */
3692 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3693 			error("listen [%s]:%s: %.100s", ntop, strport,
3694 			    strerror(errno));
3695 			close(sock);
3696 			continue;
3697 		}
3698 
3699 		/*
3700 		 * fwd->listen_port == 0 requests a dynamically allocated port -
3701 		 * record what we got.
3702 		 */
3703 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
3704 		    fwd->listen_port == 0 &&
3705 		    allocated_listen_port != NULL &&
3706 		    *allocated_listen_port == 0) {
3707 			*allocated_listen_port = get_local_port(sock);
3708 			debug("Allocated listen port %d",
3709 			    *allocated_listen_port);
3710 		}
3711 
3712 		/* Allocate a channel number for the socket. */
3713 		c = channel_new(ssh, "port listener", type, sock, sock, -1,
3714 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3715 		    0, "port listener", 1);
3716 		c->path = xstrdup(host);
3717 		c->host_port = fwd->connect_port;
3718 		c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3719 		if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3720 		    !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3721 			c->listening_port = *allocated_listen_port;
3722 		else
3723 			c->listening_port = fwd->listen_port;
3724 		success = 1;
3725 	}
3726 	if (success == 0)
3727 		error_f("cannot listen to port: %d", fwd->listen_port);
3728 	freeaddrinfo(aitop);
3729 	return success;
3730 }
3731 
3732 static int
3733 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3734     struct Forward *fwd, struct ForwardOptions *fwd_opts)
3735 {
3736 	struct sockaddr_un sunaddr;
3737 	const char *path;
3738 	Channel *c;
3739 	int port, sock;
3740 	mode_t omask;
3741 
3742 	switch (type) {
3743 	case SSH_CHANNEL_UNIX_LISTENER:
3744 		if (fwd->connect_path != NULL) {
3745 			if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3746 				error("Local connecting path too long: %s",
3747 				    fwd->connect_path);
3748 				return 0;
3749 			}
3750 			path = fwd->connect_path;
3751 			port = PORT_STREAMLOCAL;
3752 		} else {
3753 			if (fwd->connect_host == NULL) {
3754 				error("No forward host name.");
3755 				return 0;
3756 			}
3757 			if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3758 				error("Forward host name too long.");
3759 				return 0;
3760 			}
3761 			path = fwd->connect_host;
3762 			port = fwd->connect_port;
3763 		}
3764 		break;
3765 	case SSH_CHANNEL_RUNIX_LISTENER:
3766 		path = fwd->listen_path;
3767 		port = PORT_STREAMLOCAL;
3768 		break;
3769 	default:
3770 		error_f("unexpected channel type %d", type);
3771 		return 0;
3772 	}
3773 
3774 	if (fwd->listen_path == NULL) {
3775 		error("No forward path name.");
3776 		return 0;
3777 	}
3778 	if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3779 		error("Local listening path too long: %s", fwd->listen_path);
3780 		return 0;
3781 	}
3782 
3783 	debug3_f("type %d path %s", type, fwd->listen_path);
3784 
3785 	/* Start a Unix domain listener. */
3786 	omask = umask(fwd_opts->streamlocal_bind_mask);
3787 	sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3788 	    fwd_opts->streamlocal_bind_unlink);
3789 	umask(omask);
3790 	if (sock < 0)
3791 		return 0;
3792 
3793 	debug("Local forwarding listening on path %s.", fwd->listen_path);
3794 
3795 	/* Allocate a channel number for the socket. */
3796 	c = channel_new(ssh, "unix listener", type, sock, sock, -1,
3797 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3798 	    0, "unix listener", 1);
3799 	c->path = xstrdup(path);
3800 	c->host_port = port;
3801 	c->listening_port = PORT_STREAMLOCAL;
3802 	c->listening_addr = xstrdup(fwd->listen_path);
3803 	return 1;
3804 }
3805 
3806 static int
3807 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3808     const char *host, u_short port)
3809 {
3810 	u_int i;
3811 	int found = 0;
3812 
3813 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3814 		Channel *c = ssh->chanctxt->channels[i];
3815 		if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3816 			continue;
3817 		if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3818 			debug2_f("close channel %d", i);
3819 			channel_free(ssh, c);
3820 			found = 1;
3821 		}
3822 	}
3823 
3824 	return found;
3825 }
3826 
3827 static int
3828 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3829 {
3830 	u_int i;
3831 	int found = 0;
3832 
3833 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3834 		Channel *c = ssh->chanctxt->channels[i];
3835 		if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3836 			continue;
3837 		if (c->path == NULL)
3838 			continue;
3839 		if (strcmp(c->path, path) == 0) {
3840 			debug2_f("close channel %d", i);
3841 			channel_free(ssh, c);
3842 			found = 1;
3843 		}
3844 	}
3845 
3846 	return found;
3847 }
3848 
3849 int
3850 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3851 {
3852 	if (fwd->listen_path != NULL) {
3853 		return channel_cancel_rport_listener_streamlocal(ssh,
3854 		    fwd->listen_path);
3855 	} else {
3856 		return channel_cancel_rport_listener_tcpip(ssh,
3857 		    fwd->listen_host, fwd->listen_port);
3858 	}
3859 }
3860 
3861 static int
3862 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3863     const char *lhost, u_short lport, int cport,
3864     struct ForwardOptions *fwd_opts)
3865 {
3866 	u_int i;
3867 	int found = 0;
3868 	const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
3869 
3870 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3871 		Channel *c = ssh->chanctxt->channels[i];
3872 		if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3873 			continue;
3874 		if (c->listening_port != lport)
3875 			continue;
3876 		if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3877 			/* skip dynamic forwardings */
3878 			if (c->host_port == 0)
3879 				continue;
3880 		} else {
3881 			if (c->host_port != cport)
3882 				continue;
3883 		}
3884 		if ((c->listening_addr == NULL && addr != NULL) ||
3885 		    (c->listening_addr != NULL && addr == NULL))
3886 			continue;
3887 		if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3888 			debug2_f("close channel %d", i);
3889 			channel_free(ssh, c);
3890 			found = 1;
3891 		}
3892 	}
3893 
3894 	return found;
3895 }
3896 
3897 static int
3898 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
3899 {
3900 	u_int i;
3901 	int found = 0;
3902 
3903 	if (path == NULL) {
3904 		error_f("no path specified.");
3905 		return 0;
3906 	}
3907 
3908 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3909 		Channel *c = ssh->chanctxt->channels[i];
3910 		if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
3911 			continue;
3912 		if (c->listening_addr == NULL)
3913 			continue;
3914 		if (strcmp(c->listening_addr, path) == 0) {
3915 			debug2_f("close channel %d", i);
3916 			channel_free(ssh, c);
3917 			found = 1;
3918 		}
3919 	}
3920 
3921 	return found;
3922 }
3923 
3924 int
3925 channel_cancel_lport_listener(struct ssh *ssh,
3926     struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
3927 {
3928 	if (fwd->listen_path != NULL) {
3929 		return channel_cancel_lport_listener_streamlocal(ssh,
3930 		    fwd->listen_path);
3931 	} else {
3932 		return channel_cancel_lport_listener_tcpip(ssh,
3933 		    fwd->listen_host, fwd->listen_port, cport, fwd_opts);
3934 	}
3935 }
3936 
3937 /* protocol local port fwd, used by ssh */
3938 int
3939 channel_setup_local_fwd_listener(struct ssh *ssh,
3940     struct Forward *fwd, struct ForwardOptions *fwd_opts)
3941 {
3942 	if (fwd->listen_path != NULL) {
3943 		return channel_setup_fwd_listener_streamlocal(ssh,
3944 		    SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
3945 	} else {
3946 		return channel_setup_fwd_listener_tcpip(ssh,
3947 		    SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
3948 	}
3949 }
3950 
3951 /* Matches a remote forwarding permission against a requested forwarding */
3952 static int
3953 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
3954 {
3955 	int ret;
3956 	char *lhost;
3957 
3958 	/* XXX add ACLs for streamlocal */
3959 	if (fwd->listen_path != NULL)
3960 		return 1;
3961 
3962 	if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
3963 		return 0;
3964 
3965 	if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
3966 	    allowed_open->listen_port != fwd->listen_port)
3967 		return 0;
3968 
3969 	/* Match hostnames case-insensitively */
3970 	lhost = xstrdup(fwd->listen_host);
3971 	lowercase(lhost);
3972 	ret = match_pattern(lhost, allowed_open->listen_host);
3973 	free(lhost);
3974 
3975 	return ret;
3976 }
3977 
3978 /* Checks whether a requested remote forwarding is permitted */
3979 static int
3980 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
3981 {
3982 	struct ssh_channels *sc = ssh->chanctxt;
3983 	struct permission_set *pset = &sc->remote_perms;
3984 	u_int i, permit, permit_adm = 1;
3985 	struct permission *perm;
3986 
3987 	/* XXX apply GatewayPorts override before checking? */
3988 
3989 	permit = pset->all_permitted;
3990 	if (!permit) {
3991 		for (i = 0; i < pset->num_permitted_user; i++) {
3992 			perm = &pset->permitted_user[i];
3993 			if (remote_open_match(perm, fwd)) {
3994 				permit = 1;
3995 				break;
3996 			}
3997 		}
3998 	}
3999 
4000 	if (pset->num_permitted_admin > 0) {
4001 		permit_adm = 0;
4002 		for (i = 0; i < pset->num_permitted_admin; i++) {
4003 			perm = &pset->permitted_admin[i];
4004 			if (remote_open_match(perm, fwd)) {
4005 				permit_adm = 1;
4006 				break;
4007 			}
4008 		}
4009 	}
4010 
4011 	return permit && permit_adm;
4012 }
4013 
4014 /* protocol v2 remote port fwd, used by sshd */
4015 int
4016 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
4017     int *allocated_listen_port, struct ForwardOptions *fwd_opts)
4018 {
4019 	if (!check_rfwd_permission(ssh, fwd)) {
4020 		ssh_packet_send_debug(ssh, "port forwarding refused");
4021 		if (fwd->listen_path != NULL)
4022 			/* XXX always allowed, see remote_open_match() */
4023 			logit("Received request from %.100s port %d to "
4024 			    "remote forward to path \"%.100s\", "
4025 			    "but the request was denied.",
4026 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4027 			    fwd->listen_path);
4028 		else if(fwd->listen_host != NULL)
4029 			logit("Received request from %.100s port %d to "
4030 			    "remote forward to host %.100s port %d, "
4031 			    "but the request was denied.",
4032 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4033 			    fwd->listen_host, fwd->listen_port );
4034 		else
4035 			logit("Received request from %.100s port %d to remote "
4036 			    "forward, but the request was denied.",
4037 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
4038 		return 0;
4039 	}
4040 	if (fwd->listen_path != NULL) {
4041 		return channel_setup_fwd_listener_streamlocal(ssh,
4042 		    SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
4043 	} else {
4044 		return channel_setup_fwd_listener_tcpip(ssh,
4045 		    SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
4046 		    fwd_opts);
4047 	}
4048 }
4049 
4050 /*
4051  * Translate the requested rfwd listen host to something usable for
4052  * this server.
4053  */
4054 static const char *
4055 channel_rfwd_bind_host(const char *listen_host)
4056 {
4057 	if (listen_host == NULL) {
4058 		return "localhost";
4059 	} else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
4060 		return "";
4061 	} else
4062 		return listen_host;
4063 }
4064 
4065 /*
4066  * Initiate forwarding of connections to port "port" on remote host through
4067  * the secure channel to host:port from local side.
4068  * Returns handle (index) for updating the dynamic listen port with
4069  * channel_update_permission().
4070  */
4071 int
4072 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
4073 {
4074 	int r, success = 0, idx = -1;
4075 	char *host_to_connect, *listen_host, *listen_path;
4076 	int port_to_connect, listen_port;
4077 
4078 	/* Send the forward request to the remote side. */
4079 	if (fwd->listen_path != NULL) {
4080 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4081 		    (r = sshpkt_put_cstring(ssh,
4082 		    "streamlocal-forward@openssh.com")) != 0 ||
4083 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4084 		    (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
4085 		    (r = sshpkt_send(ssh)) != 0 ||
4086 		    (r = ssh_packet_write_wait(ssh)) != 0)
4087 			fatal_fr(r, "request streamlocal");
4088 	} else {
4089 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4090 		    (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
4091 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4092 		    (r = sshpkt_put_cstring(ssh,
4093 		    channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
4094 		    (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
4095 		    (r = sshpkt_send(ssh)) != 0 ||
4096 		    (r = ssh_packet_write_wait(ssh)) != 0)
4097 			fatal_fr(r, "request tcpip-forward");
4098 	}
4099 	/* Assume that server accepts the request */
4100 	success = 1;
4101 	if (success) {
4102 		/* Record that connection to this host/port is permitted. */
4103 		host_to_connect = listen_host = listen_path = NULL;
4104 		port_to_connect = listen_port = 0;
4105 		if (fwd->connect_path != NULL) {
4106 			host_to_connect = xstrdup(fwd->connect_path);
4107 			port_to_connect = PORT_STREAMLOCAL;
4108 		} else {
4109 			host_to_connect = xstrdup(fwd->connect_host);
4110 			port_to_connect = fwd->connect_port;
4111 		}
4112 		if (fwd->listen_path != NULL) {
4113 			listen_path = xstrdup(fwd->listen_path);
4114 			listen_port = PORT_STREAMLOCAL;
4115 		} else {
4116 			if (fwd->listen_host != NULL)
4117 				listen_host = xstrdup(fwd->listen_host);
4118 			listen_port = fwd->listen_port;
4119 		}
4120 		idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
4121 		    host_to_connect, port_to_connect,
4122 		    listen_host, listen_path, listen_port, NULL);
4123 	}
4124 	return idx;
4125 }
4126 
4127 static int
4128 open_match(struct permission *allowed_open, const char *requestedhost,
4129     int requestedport)
4130 {
4131 	if (allowed_open->host_to_connect == NULL)
4132 		return 0;
4133 	if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
4134 	    allowed_open->port_to_connect != requestedport)
4135 		return 0;
4136 	if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
4137 	    strcmp(allowed_open->host_to_connect, requestedhost) != 0)
4138 		return 0;
4139 	return 1;
4140 }
4141 
4142 /*
4143  * Note that in the listen host/port case
4144  * we don't support FWD_PERMIT_ANY_PORT and
4145  * need to translate between the configured-host (listen_host)
4146  * and what we've sent to the remote server (channel_rfwd_bind_host)
4147  */
4148 static int
4149 open_listen_match_tcpip(struct permission *allowed_open,
4150     const char *requestedhost, u_short requestedport, int translate)
4151 {
4152 	const char *allowed_host;
4153 
4154 	if (allowed_open->host_to_connect == NULL)
4155 		return 0;
4156 	if (allowed_open->listen_port != requestedport)
4157 		return 0;
4158 	if (!translate && allowed_open->listen_host == NULL &&
4159 	    requestedhost == NULL)
4160 		return 1;
4161 	allowed_host = translate ?
4162 	    channel_rfwd_bind_host(allowed_open->listen_host) :
4163 	    allowed_open->listen_host;
4164 	if (allowed_host == NULL || requestedhost == NULL ||
4165 	    strcmp(allowed_host, requestedhost) != 0)
4166 		return 0;
4167 	return 1;
4168 }
4169 
4170 static int
4171 open_listen_match_streamlocal(struct permission *allowed_open,
4172     const char *requestedpath)
4173 {
4174 	if (allowed_open->host_to_connect == NULL)
4175 		return 0;
4176 	if (allowed_open->listen_port != PORT_STREAMLOCAL)
4177 		return 0;
4178 	if (allowed_open->listen_path == NULL ||
4179 	    strcmp(allowed_open->listen_path, requestedpath) != 0)
4180 		return 0;
4181 	return 1;
4182 }
4183 
4184 /*
4185  * Request cancellation of remote forwarding of connection host:port from
4186  * local side.
4187  */
4188 static int
4189 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
4190     const char *host, u_short port)
4191 {
4192 	struct ssh_channels *sc = ssh->chanctxt;
4193 	struct permission_set *pset = &sc->local_perms;
4194 	int r;
4195 	u_int i;
4196 	struct permission *perm = NULL;
4197 
4198 	for (i = 0; i < pset->num_permitted_user; i++) {
4199 		perm = &pset->permitted_user[i];
4200 		if (open_listen_match_tcpip(perm, host, port, 0))
4201 			break;
4202 		perm = NULL;
4203 	}
4204 	if (perm == NULL) {
4205 		debug_f("requested forward not found");
4206 		return -1;
4207 	}
4208 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4209 	    (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
4210 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4211 	    (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
4212 	    (r = sshpkt_put_u32(ssh, port)) != 0 ||
4213 	    (r = sshpkt_send(ssh)) != 0)
4214 		fatal_fr(r, "send cancel");
4215 
4216 	fwd_perm_clear(perm); /* unregister */
4217 
4218 	return 0;
4219 }
4220 
4221 /*
4222  * Request cancellation of remote forwarding of Unix domain socket
4223  * path from local side.
4224  */
4225 static int
4226 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
4227 {
4228 	struct ssh_channels *sc = ssh->chanctxt;
4229 	struct permission_set *pset = &sc->local_perms;
4230 	int r;
4231 	u_int i;
4232 	struct permission *perm = NULL;
4233 
4234 	for (i = 0; i < pset->num_permitted_user; i++) {
4235 		perm = &pset->permitted_user[i];
4236 		if (open_listen_match_streamlocal(perm, path))
4237 			break;
4238 		perm = NULL;
4239 	}
4240 	if (perm == NULL) {
4241 		debug_f("requested forward not found");
4242 		return -1;
4243 	}
4244 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4245 	    (r = sshpkt_put_cstring(ssh,
4246 	    "cancel-streamlocal-forward@openssh.com")) != 0 ||
4247 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4248 	    (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4249 	    (r = sshpkt_send(ssh)) != 0)
4250 		fatal_fr(r, "send cancel");
4251 
4252 	fwd_perm_clear(perm); /* unregister */
4253 
4254 	return 0;
4255 }
4256 
4257 /*
4258  * Request cancellation of remote forwarding of a connection from local side.
4259  */
4260 int
4261 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4262 {
4263 	if (fwd->listen_path != NULL) {
4264 		return channel_request_rforward_cancel_streamlocal(ssh,
4265 		    fwd->listen_path);
4266 	} else {
4267 		return channel_request_rforward_cancel_tcpip(ssh,
4268 		    fwd->listen_host,
4269 		    fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4270 	}
4271 }
4272 
4273 /*
4274  * Permits opening to any host/port if permitted_user[] is empty.  This is
4275  * usually called by the server, because the user could connect to any port
4276  * anyway, and the server has no way to know but to trust the client anyway.
4277  */
4278 void
4279 channel_permit_all(struct ssh *ssh, int where)
4280 {
4281 	struct permission_set *pset = permission_set_get(ssh, where);
4282 
4283 	if (pset->num_permitted_user == 0)
4284 		pset->all_permitted = 1;
4285 }
4286 
4287 /*
4288  * Permit the specified host/port for forwarding.
4289  */
4290 void
4291 channel_add_permission(struct ssh *ssh, int who, int where,
4292     char *host, int port)
4293 {
4294 	int local = where == FORWARD_LOCAL;
4295 	struct permission_set *pset = permission_set_get(ssh, where);
4296 
4297 	debug("allow %s forwarding to host %s port %d",
4298 	    fwd_ident(who, where), host, port);
4299 	/*
4300 	 * Remote forwards set listen_host/port, local forwards set
4301 	 * host/port_to_connect.
4302 	 */
4303 	permission_set_add(ssh, who, where,
4304 	    local ? host : 0, local ? port : 0,
4305 	    local ? NULL : host, NULL, local ? 0 : port, NULL);
4306 	pset->all_permitted = 0;
4307 }
4308 
4309 /*
4310  * Administratively disable forwarding.
4311  */
4312 void
4313 channel_disable_admin(struct ssh *ssh, int where)
4314 {
4315 	channel_clear_permission(ssh, FORWARD_ADM, where);
4316 	permission_set_add(ssh, FORWARD_ADM, where,
4317 	    NULL, 0, NULL, NULL, 0, NULL);
4318 }
4319 
4320 /*
4321  * Clear a list of permitted opens.
4322  */
4323 void
4324 channel_clear_permission(struct ssh *ssh, int who, int where)
4325 {
4326 	struct permission **permp;
4327 	u_int *npermp;
4328 
4329 	permission_set_get_array(ssh, who, where, &permp, &npermp);
4330 	*permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4331 	*npermp = 0;
4332 }
4333 
4334 /*
4335  * Update the listen port for a dynamic remote forward, after
4336  * the actual 'newport' has been allocated. If 'newport' < 0 is
4337  * passed then they entry will be invalidated.
4338  */
4339 void
4340 channel_update_permission(struct ssh *ssh, int idx, int newport)
4341 {
4342 	struct permission_set *pset = &ssh->chanctxt->local_perms;
4343 
4344 	if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4345 		debug_f("index out of range: %d num_permitted_user %d",
4346 		    idx, pset->num_permitted_user);
4347 		return;
4348 	}
4349 	debug("%s allowed port %d for forwarding to host %s port %d",
4350 	    newport > 0 ? "Updating" : "Removing",
4351 	    newport,
4352 	    pset->permitted_user[idx].host_to_connect,
4353 	    pset->permitted_user[idx].port_to_connect);
4354 	if (newport <= 0)
4355 		fwd_perm_clear(&pset->permitted_user[idx]);
4356 	else {
4357 		pset->permitted_user[idx].listen_port =
4358 		    (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4359 	}
4360 }
4361 
4362 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4363 int
4364 permitopen_port(const char *p)
4365 {
4366 	int port;
4367 
4368 	if (strcmp(p, "*") == 0)
4369 		return FWD_PERMIT_ANY_PORT;
4370 	if ((port = a2port(p)) > 0)
4371 		return port;
4372 	return -1;
4373 }
4374 
4375 /* Try to start non-blocking connect to next host in cctx list */
4376 static int
4377 connect_next(struct channel_connect *cctx)
4378 {
4379 	int sock, saved_errno;
4380 	struct sockaddr_un *sunaddr;
4381 	char ntop[NI_MAXHOST];
4382 	char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4383 
4384 	for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4385 		switch (cctx->ai->ai_family) {
4386 		case AF_UNIX:
4387 			/* unix:pathname instead of host:port */
4388 			sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4389 			strlcpy(ntop, "unix", sizeof(ntop));
4390 			strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4391 			break;
4392 		case AF_INET:
4393 		case AF_INET6:
4394 			if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4395 			    ntop, sizeof(ntop), strport, sizeof(strport),
4396 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4397 				error("connect_next: getnameinfo failed");
4398 				continue;
4399 			}
4400 			break;
4401 		default:
4402 			continue;
4403 		}
4404 		if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4405 		    cctx->ai->ai_protocol)) == -1) {
4406 			if (cctx->ai->ai_next == NULL)
4407 				error("socket: %.100s", strerror(errno));
4408 			else
4409 				verbose("socket: %.100s", strerror(errno));
4410 			continue;
4411 		}
4412 		if (set_nonblock(sock) == -1)
4413 			fatal_f("set_nonblock(%d)", sock);
4414 		if (connect(sock, cctx->ai->ai_addr,
4415 		    cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4416 			debug("connect_next: host %.100s ([%.100s]:%s): "
4417 			    "%.100s", cctx->host, ntop, strport,
4418 			    strerror(errno));
4419 			saved_errno = errno;
4420 			close(sock);
4421 			errno = saved_errno;
4422 			continue;	/* fail -- try next */
4423 		}
4424 		if (cctx->ai->ai_family != AF_UNIX)
4425 			set_nodelay(sock);
4426 		debug("connect_next: host %.100s ([%.100s]:%s) "
4427 		    "in progress, fd=%d", cctx->host, ntop, strport, sock);
4428 		cctx->ai = cctx->ai->ai_next;
4429 		return sock;
4430 	}
4431 	return -1;
4432 }
4433 
4434 static void
4435 channel_connect_ctx_free(struct channel_connect *cctx)
4436 {
4437 	free(cctx->host);
4438 	if (cctx->aitop) {
4439 		if (cctx->aitop->ai_family == AF_UNIX)
4440 			free(cctx->aitop);
4441 		else
4442 			freeaddrinfo(cctx->aitop);
4443 	}
4444 	memset(cctx, 0, sizeof(*cctx));
4445 }
4446 
4447 /*
4448  * Return connecting socket to remote host:port or local socket path,
4449  * passing back the failure reason if appropriate.
4450  */
4451 static int
4452 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4453     char *ctype, char *rname, struct channel_connect *cctx,
4454     int *reason, const char **errmsg)
4455 {
4456 	struct addrinfo hints;
4457 	int gaierr;
4458 	int sock = -1;
4459 	char strport[NI_MAXSERV];
4460 
4461 	if (port == PORT_STREAMLOCAL) {
4462 		struct sockaddr_un *sunaddr;
4463 		struct addrinfo *ai;
4464 
4465 		if (strlen(name) > sizeof(sunaddr->sun_path)) {
4466 			error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4467 			return -1;
4468 		}
4469 
4470 		/*
4471 		 * Fake up a struct addrinfo for AF_UNIX connections.
4472 		 * channel_connect_ctx_free() must check ai_family
4473 		 * and use free() not freeaddirinfo() for AF_UNIX.
4474 		 */
4475 		ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4476 		memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4477 		ai->ai_addr = (struct sockaddr *)(ai + 1);
4478 		ai->ai_addrlen = sizeof(*sunaddr);
4479 		ai->ai_family = AF_UNIX;
4480 		ai->ai_socktype = socktype;
4481 		ai->ai_protocol = PF_UNSPEC;
4482 		sunaddr = (struct sockaddr_un *)ai->ai_addr;
4483 		sunaddr->sun_family = AF_UNIX;
4484 		strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4485 		cctx->aitop = ai;
4486 	} else {
4487 		memset(&hints, 0, sizeof(hints));
4488 		hints.ai_family = ssh->chanctxt->IPv4or6;
4489 		hints.ai_socktype = socktype;
4490 		snprintf(strport, sizeof strport, "%d", port);
4491 		if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4492 		    != 0) {
4493 			if (errmsg != NULL)
4494 				*errmsg = ssh_gai_strerror(gaierr);
4495 			if (reason != NULL)
4496 				*reason = SSH2_OPEN_CONNECT_FAILED;
4497 			error("connect_to %.100s: unknown host (%s)", name,
4498 			    ssh_gai_strerror(gaierr));
4499 			return -1;
4500 		}
4501 	}
4502 
4503 	cctx->host = xstrdup(name);
4504 	cctx->port = port;
4505 	cctx->ai = cctx->aitop;
4506 
4507 	if ((sock = connect_next(cctx)) == -1) {
4508 		error("connect to %.100s port %d failed: %s",
4509 		    name, port, strerror(errno));
4510 		return -1;
4511 	}
4512 
4513 	return sock;
4514 }
4515 
4516 /* Return CONNECTING channel to remote host:port or local socket path */
4517 static Channel *
4518 connect_to(struct ssh *ssh, const char *host, int port,
4519     char *ctype, char *rname)
4520 {
4521 	struct channel_connect cctx;
4522 	Channel *c;
4523 	int sock;
4524 
4525 	memset(&cctx, 0, sizeof(cctx));
4526 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4527 	    &cctx, NULL, NULL);
4528 	if (sock == -1) {
4529 		channel_connect_ctx_free(&cctx);
4530 		return NULL;
4531 	}
4532 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4533 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4534 	c->host_port = port;
4535 	c->path = xstrdup(host);
4536 	c->connect_ctx = cctx;
4537 
4538 	return c;
4539 }
4540 
4541 /*
4542  * returns either the newly connected channel or the downstream channel
4543  * that needs to deal with this connection.
4544  */
4545 Channel *
4546 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4547     u_short listen_port, char *ctype, char *rname)
4548 {
4549 	struct ssh_channels *sc = ssh->chanctxt;
4550 	struct permission_set *pset = &sc->local_perms;
4551 	u_int i;
4552 	struct permission *perm;
4553 
4554 	for (i = 0; i < pset->num_permitted_user; i++) {
4555 		perm = &pset->permitted_user[i];
4556 		if (open_listen_match_tcpip(perm,
4557 		    listen_host, listen_port, 1)) {
4558 			if (perm->downstream)
4559 				return perm->downstream;
4560 			if (perm->port_to_connect == 0)
4561 				return rdynamic_connect_prepare(ssh,
4562 				    ctype, rname);
4563 			return connect_to(ssh,
4564 			    perm->host_to_connect, perm->port_to_connect,
4565 			    ctype, rname);
4566 		}
4567 	}
4568 	error("WARNING: Server requests forwarding for unknown listen_port %d",
4569 	    listen_port);
4570 	return NULL;
4571 }
4572 
4573 Channel *
4574 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4575     char *ctype, char *rname)
4576 {
4577 	struct ssh_channels *sc = ssh->chanctxt;
4578 	struct permission_set *pset = &sc->local_perms;
4579 	u_int i;
4580 	struct permission *perm;
4581 
4582 	for (i = 0; i < pset->num_permitted_user; i++) {
4583 		perm = &pset->permitted_user[i];
4584 		if (open_listen_match_streamlocal(perm, path)) {
4585 			return connect_to(ssh,
4586 			    perm->host_to_connect, perm->port_to_connect,
4587 			    ctype, rname);
4588 		}
4589 	}
4590 	error("WARNING: Server requests forwarding for unknown path %.100s",
4591 	    path);
4592 	return NULL;
4593 }
4594 
4595 /* Check if connecting to that port is permitted and connect. */
4596 Channel *
4597 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4598     char *ctype, char *rname, int *reason, const char **errmsg)
4599 {
4600 	struct ssh_channels *sc = ssh->chanctxt;
4601 	struct permission_set *pset = &sc->local_perms;
4602 	struct channel_connect cctx;
4603 	Channel *c;
4604 	u_int i, permit, permit_adm = 1;
4605 	int sock;
4606 	struct permission *perm;
4607 
4608 	permit = pset->all_permitted;
4609 	if (!permit) {
4610 		for (i = 0; i < pset->num_permitted_user; i++) {
4611 			perm = &pset->permitted_user[i];
4612 			if (open_match(perm, host, port)) {
4613 				permit = 1;
4614 				break;
4615 			}
4616 		}
4617 	}
4618 
4619 	if (pset->num_permitted_admin > 0) {
4620 		permit_adm = 0;
4621 		for (i = 0; i < pset->num_permitted_admin; i++) {
4622 			perm = &pset->permitted_admin[i];
4623 			if (open_match(perm, host, port)) {
4624 				permit_adm = 1;
4625 				break;
4626 			}
4627 		}
4628 	}
4629 
4630 	if (!permit || !permit_adm) {
4631 		logit("Received request from %.100s port %d to connect to "
4632 		    "host %.100s port %d, but the request was denied.",
4633 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4634 		if (reason != NULL)
4635 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4636 		return NULL;
4637 	}
4638 
4639 	memset(&cctx, 0, sizeof(cctx));
4640 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4641 	    &cctx, reason, errmsg);
4642 	if (sock == -1) {
4643 		channel_connect_ctx_free(&cctx);
4644 		return NULL;
4645 	}
4646 
4647 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4648 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4649 	c->host_port = port;
4650 	c->path = xstrdup(host);
4651 	c->connect_ctx = cctx;
4652 
4653 	return c;
4654 }
4655 
4656 /* Check if connecting to that path is permitted and connect. */
4657 Channel *
4658 channel_connect_to_path(struct ssh *ssh, const char *path,
4659     char *ctype, char *rname)
4660 {
4661 	struct ssh_channels *sc = ssh->chanctxt;
4662 	struct permission_set *pset = &sc->local_perms;
4663 	u_int i, permit, permit_adm = 1;
4664 	struct permission *perm;
4665 
4666 	permit = pset->all_permitted;
4667 	if (!permit) {
4668 		for (i = 0; i < pset->num_permitted_user; i++) {
4669 			perm = &pset->permitted_user[i];
4670 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
4671 				permit = 1;
4672 				break;
4673 			}
4674 		}
4675 	}
4676 
4677 	if (pset->num_permitted_admin > 0) {
4678 		permit_adm = 0;
4679 		for (i = 0; i < pset->num_permitted_admin; i++) {
4680 			perm = &pset->permitted_admin[i];
4681 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
4682 				permit_adm = 1;
4683 				break;
4684 			}
4685 		}
4686 	}
4687 
4688 	if (!permit || !permit_adm) {
4689 		logit("Received request to connect to path %.100s, "
4690 		    "but the request was denied.", path);
4691 		return NULL;
4692 	}
4693 	return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4694 }
4695 
4696 void
4697 channel_send_window_changes(struct ssh *ssh)
4698 {
4699 	struct ssh_channels *sc = ssh->chanctxt;
4700 	struct winsize ws;
4701 	int r;
4702 	u_int i;
4703 
4704 	for (i = 0; i < sc->channels_alloc; i++) {
4705 		if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4706 		    sc->channels[i]->type != SSH_CHANNEL_OPEN)
4707 			continue;
4708 		if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4709 			continue;
4710 		channel_request_start(ssh, i, "window-change", 0);
4711 		if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4712 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4713 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4714 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4715 		    (r = sshpkt_send(ssh)) != 0)
4716 			fatal_fr(r, "channel %u; send window-change", i);
4717 	}
4718 }
4719 
4720 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4721 static Channel *
4722 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4723 {
4724 	Channel *c;
4725 	int r;
4726 
4727 	c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4728 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4729 	c->host_port = 0;
4730 	c->path = NULL;
4731 
4732 	/*
4733 	 * We need to open the channel before we have a FD,
4734 	 * so that we can get SOCKS header from peer.
4735 	 */
4736 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4737 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4738 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4739 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4740 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4741 		fatal_fr(r, "channel %i; confirm", c->self);
4742 	return c;
4743 }
4744 
4745 /* Return CONNECTING socket to remote host:port or local socket path */
4746 static int
4747 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4748 {
4749 	struct ssh_channels *sc = ssh->chanctxt;
4750 	struct permission_set *pset = &sc->local_perms;
4751 	struct permission *perm;
4752 	struct channel_connect cctx;
4753 	u_int i, permit_adm = 1;
4754 	int sock;
4755 
4756 	if (pset->num_permitted_admin > 0) {
4757 		permit_adm = 0;
4758 		for (i = 0; i < pset->num_permitted_admin; i++) {
4759 			perm = &pset->permitted_admin[i];
4760 			if (open_match(perm, c->path, c->host_port)) {
4761 				permit_adm = 1;
4762 				break;
4763 			}
4764 		}
4765 	}
4766 	if (!permit_adm) {
4767 		debug_f("requested forward not permitted");
4768 		return -1;
4769 	}
4770 
4771 	memset(&cctx, 0, sizeof(cctx));
4772 	sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4773 	    NULL, &cctx, NULL, NULL);
4774 	if (sock == -1)
4775 		channel_connect_ctx_free(&cctx);
4776 	else {
4777 		/* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4778 		c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4779 		c->connect_ctx = cctx;
4780 		channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4781 	}
4782 	return sock;
4783 }
4784 
4785 /* -- X11 forwarding */
4786 
4787 /*
4788  * Creates an internet domain socket for listening for X11 connections.
4789  * Returns 0 and a suitable display number for the DISPLAY variable
4790  * stored in display_numberp , or -1 if an error occurs.
4791  */
4792 int
4793 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4794     int x11_use_localhost, int single_connection,
4795     u_int *display_numberp, int **chanids)
4796 {
4797 	Channel *nc = NULL;
4798 	int display_number, sock;
4799 	u_short port;
4800 	struct addrinfo hints, *ai, *aitop;
4801 	char strport[NI_MAXSERV];
4802 	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4803 
4804 	if (chanids == NULL)
4805 		return -1;
4806 
4807 	for (display_number = x11_display_offset;
4808 	    display_number < MAX_DISPLAYS;
4809 	    display_number++) {
4810 		port = 6000 + display_number;
4811 		memset(&hints, 0, sizeof(hints));
4812 		hints.ai_family = ssh->chanctxt->IPv4or6;
4813 		hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4814 		hints.ai_socktype = SOCK_STREAM;
4815 		snprintf(strport, sizeof strport, "%d", port);
4816 		if ((gaierr = getaddrinfo(NULL, strport,
4817 		    &hints, &aitop)) != 0) {
4818 			error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4819 			return -1;
4820 		}
4821 		for (ai = aitop; ai; ai = ai->ai_next) {
4822 			if (ai->ai_family != AF_INET &&
4823 			    ai->ai_family != AF_INET6)
4824 				continue;
4825 			sock = socket(ai->ai_family, ai->ai_socktype,
4826 			    ai->ai_protocol);
4827 			if (sock == -1) {
4828 				if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4829 #ifdef EPFNOSUPPORT
4830 				    && (errno != EPFNOSUPPORT)
4831 #endif
4832 				    ) {
4833 					error("socket: %.100s", strerror(errno));
4834 					freeaddrinfo(aitop);
4835 					return -1;
4836 				} else {
4837 					debug("x11_create_display_inet: Socket family %d not supported",
4838 						 ai->ai_family);
4839 					continue;
4840 				}
4841 			}
4842 			if (ai->ai_family == AF_INET6)
4843 				sock_set_v6only(sock);
4844 			if (x11_use_localhost)
4845 				set_reuseaddr(sock);
4846 			if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4847 				debug2_f("bind port %d: %.100s", port,
4848 				    strerror(errno));
4849 				close(sock);
4850 				for (n = 0; n < num_socks; n++)
4851 					close(socks[n]);
4852 				num_socks = 0;
4853 				break;
4854 			}
4855 			socks[num_socks++] = sock;
4856 			if (num_socks == NUM_SOCKS)
4857 				break;
4858 		}
4859 		freeaddrinfo(aitop);
4860 		if (num_socks > 0)
4861 			break;
4862 	}
4863 	if (display_number >= MAX_DISPLAYS) {
4864 		error("Failed to allocate internet-domain X11 display socket.");
4865 		return -1;
4866 	}
4867 	/* Start listening for connections on the socket. */
4868 	for (n = 0; n < num_socks; n++) {
4869 		sock = socks[n];
4870 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
4871 			error("listen: %.100s", strerror(errno));
4872 			close(sock);
4873 			return -1;
4874 		}
4875 	}
4876 
4877 	/* Allocate a channel for each socket. */
4878 	*chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4879 	for (n = 0; n < num_socks; n++) {
4880 		sock = socks[n];
4881 		nc = channel_new(ssh, "x11 listener",
4882 		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4883 		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4884 		    0, "X11 inet listener", 1);
4885 		nc->single_connection = single_connection;
4886 		(*chanids)[n] = nc->self;
4887 	}
4888 	(*chanids)[n] = -1;
4889 
4890 	/* Return the display number for the DISPLAY environment variable. */
4891 	*display_numberp = display_number;
4892 	return 0;
4893 }
4894 
4895 static int
4896 connect_local_xsocket_path(const char *pathname)
4897 {
4898 	int sock;
4899 	struct sockaddr_un addr;
4900 
4901 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
4902 	if (sock == -1)
4903 		error("socket: %.100s", strerror(errno));
4904 	memset(&addr, 0, sizeof(addr));
4905 	addr.sun_family = AF_UNIX;
4906 	strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
4907 	if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4908 		return sock;
4909 	close(sock);
4910 	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4911 	return -1;
4912 }
4913 
4914 static int
4915 connect_local_xsocket(u_int dnr)
4916 {
4917 	char buf[1024];
4918 	snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
4919 	return connect_local_xsocket_path(buf);
4920 }
4921 
4922 #ifdef __APPLE__
4923 static int
4924 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
4925 {
4926 	struct stat sbuf;
4927 
4928 	if (strlcpy(path, display, pathlen) >= pathlen) {
4929 		error("%s: display path too long", __func__);
4930 		return 0;
4931 	}
4932 	if (display[0] != '/')
4933 		return 0;
4934 	if (stat(path, &sbuf) == 0) {
4935 		return 1;
4936 	} else {
4937 		char *dot = strrchr(path, '.');
4938 		if (dot != NULL) {
4939 			*dot = '\0';
4940 			if (stat(path, &sbuf) == 0) {
4941 				return 1;
4942 			}
4943 		}
4944 	}
4945 	return 0;
4946 }
4947 #endif
4948 
4949 int
4950 x11_connect_display(struct ssh *ssh)
4951 {
4952 	u_int display_number;
4953 	const char *display;
4954 	char buf[1024], *cp;
4955 	struct addrinfo hints, *ai, *aitop;
4956 	char strport[NI_MAXSERV];
4957 	int gaierr, sock = 0;
4958 
4959 	/* Try to open a socket for the local X server. */
4960 	display = getenv("DISPLAY");
4961 	if (!display) {
4962 		error("DISPLAY not set.");
4963 		return -1;
4964 	}
4965 	/*
4966 	 * Now we decode the value of the DISPLAY variable and make a
4967 	 * connection to the real X server.
4968 	 */
4969 
4970 #ifdef __APPLE__
4971 	/* Check if display is a path to a socket (as set by launchd). */
4972 	{
4973 		char path[PATH_MAX];
4974 
4975 		if (is_path_to_xsocket(display, path, sizeof(path))) {
4976 			debug("x11_connect_display: $DISPLAY is launchd");
4977 
4978 			/* Create a socket. */
4979 			sock = connect_local_xsocket_path(path);
4980 			if (sock < 0)
4981 				return -1;
4982 
4983 			/* OK, we now have a connection to the display. */
4984 			return sock;
4985 		}
4986 	}
4987 #endif
4988 	/*
4989 	 * Check if it is a unix domain socket.  Unix domain displays are in
4990 	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4991 	 */
4992 	if (strncmp(display, "unix:", 5) == 0 ||
4993 	    display[0] == ':') {
4994 		/* Connect to the unix domain socket. */
4995 		if (sscanf(strrchr(display, ':') + 1, "%u",
4996 		    &display_number) != 1) {
4997 			error("Could not parse display number from DISPLAY: "
4998 			    "%.100s", display);
4999 			return -1;
5000 		}
5001 		/* Create a socket. */
5002 		sock = connect_local_xsocket(display_number);
5003 		if (sock < 0)
5004 			return -1;
5005 
5006 		/* OK, we now have a connection to the display. */
5007 		return sock;
5008 	}
5009 	/*
5010 	 * Connect to an inet socket.  The DISPLAY value is supposedly
5011 	 * hostname:d[.s], where hostname may also be numeric IP address.
5012 	 */
5013 	strlcpy(buf, display, sizeof(buf));
5014 	cp = strchr(buf, ':');
5015 	if (!cp) {
5016 		error("Could not find ':' in DISPLAY: %.100s", display);
5017 		return -1;
5018 	}
5019 	*cp = 0;
5020 	/*
5021 	 * buf now contains the host name.  But first we parse the
5022 	 * display number.
5023 	 */
5024 	if (sscanf(cp + 1, "%u", &display_number) != 1) {
5025 		error("Could not parse display number from DISPLAY: %.100s",
5026 		    display);
5027 		return -1;
5028 	}
5029 
5030 	/* Look up the host address */
5031 	memset(&hints, 0, sizeof(hints));
5032 	hints.ai_family = ssh->chanctxt->IPv4or6;
5033 	hints.ai_socktype = SOCK_STREAM;
5034 	snprintf(strport, sizeof strport, "%u", 6000 + display_number);
5035 	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
5036 		error("%.100s: unknown host. (%s)", buf,
5037 		ssh_gai_strerror(gaierr));
5038 		return -1;
5039 	}
5040 	for (ai = aitop; ai; ai = ai->ai_next) {
5041 		/* Create a socket. */
5042 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
5043 		if (sock == -1) {
5044 			debug2("socket: %.100s", strerror(errno));
5045 			continue;
5046 		}
5047 		/* Connect it to the display. */
5048 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
5049 			debug2("connect %.100s port %u: %.100s", buf,
5050 			    6000 + display_number, strerror(errno));
5051 			close(sock);
5052 			continue;
5053 		}
5054 		/* Success */
5055 		break;
5056 	}
5057 	freeaddrinfo(aitop);
5058 	if (!ai) {
5059 		error("connect %.100s port %u: %.100s", buf,
5060 		    6000 + display_number, strerror(errno));
5061 		return -1;
5062 	}
5063 	set_nodelay(sock);
5064 	return sock;
5065 }
5066 
5067 /*
5068  * Requests forwarding of X11 connections, generates fake authentication
5069  * data, and enables authentication spoofing.
5070  * This should be called in the client only.
5071  */
5072 void
5073 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
5074     const char *disp, const char *proto, const char *data, int want_reply)
5075 {
5076 	struct ssh_channels *sc = ssh->chanctxt;
5077 	u_int data_len = (u_int) strlen(data) / 2;
5078 	u_int i, value;
5079 	const char *cp;
5080 	char *new_data;
5081 	int r, screen_number;
5082 
5083 	if (sc->x11_saved_display == NULL)
5084 		sc->x11_saved_display = xstrdup(disp);
5085 	else if (strcmp(disp, sc->x11_saved_display) != 0) {
5086 		error("x11_request_forwarding_with_spoofing: different "
5087 		    "$DISPLAY already forwarded");
5088 		return;
5089 	}
5090 
5091 	cp = strchr(disp, ':');
5092 	if (cp)
5093 		cp = strchr(cp, '.');
5094 	if (cp)
5095 		screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
5096 	else
5097 		screen_number = 0;
5098 
5099 	if (sc->x11_saved_proto == NULL) {
5100 		/* Save protocol name. */
5101 		sc->x11_saved_proto = xstrdup(proto);
5102 
5103 		/* Extract real authentication data. */
5104 		sc->x11_saved_data = xmalloc(data_len);
5105 		for (i = 0; i < data_len; i++) {
5106 			if (sscanf(data + 2 * i, "%2x", &value) != 1) {
5107 				fatal("x11_request_forwarding: bad "
5108 				    "authentication data: %.100s", data);
5109 			}
5110 			sc->x11_saved_data[i] = value;
5111 		}
5112 		sc->x11_saved_data_len = data_len;
5113 
5114 		/* Generate fake data of the same length. */
5115 		sc->x11_fake_data = xmalloc(data_len);
5116 		arc4random_buf(sc->x11_fake_data, data_len);
5117 		sc->x11_fake_data_len = data_len;
5118 	}
5119 
5120 	/* Convert the fake data into hex. */
5121 	new_data = tohex(sc->x11_fake_data, data_len);
5122 
5123 	/* Send the request packet. */
5124 	channel_request_start(ssh, client_session_id, "x11-req", want_reply);
5125 	if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
5126 	    (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
5127 	    (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
5128 	    (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
5129 	    (r = sshpkt_send(ssh)) != 0 ||
5130 	    (r = ssh_packet_write_wait(ssh)) != 0)
5131 		fatal_fr(r, "send x11-req");
5132 	free(new_data);
5133 }
5134