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