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