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