xref: /openssh-portable/channels.c (revision 107eb3ee)
1 /* $OpenBSD: channels.c,v 1.402 2020/09/20 05:47:25 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains functions for generic socket connection forwarding.
7  * There is also code for initiating connection forwarding for X11 connections,
8  * arbitrary tcp/ip connections, and the authentication agent connection.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * SSH2 support added by Markus Friedl.
17  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
18  * Copyright (c) 1999 Dug Song.  All rights reserved.
19  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 #include "includes.h"
43 
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/ioctl.h>
47 #include <sys/un.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
51 #endif
52 
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <netdb.h>
60 #include <stdarg.h>
61 #ifdef HAVE_STDINT_H
62 # include <stdint.h>
63 #endif
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <termios.h>
68 #include <unistd.h>
69 
70 #include "openbsd-compat/sys-queue.h"
71 #include "xmalloc.h"
72 #include "ssh.h"
73 #include "ssh2.h"
74 #include "ssherr.h"
75 #include "sshbuf.h"
76 #include "packet.h"
77 #include "log.h"
78 #include "misc.h"
79 #include "channels.h"
80 #include "compat.h"
81 #include "canohost.h"
82 #include "sshkey.h"
83 #include "authfd.h"
84 #include "pathnames.h"
85 #include "match.h"
86 
87 /* -- agent forwarding */
88 #define	NUM_SOCKS	10
89 
90 /* -- tcp forwarding */
91 /* special-case port number meaning allow any port */
92 #define FWD_PERMIT_ANY_PORT	0
93 
94 /* special-case wildcard meaning allow any host */
95 #define FWD_PERMIT_ANY_HOST	"*"
96 
97 /* -- X11 forwarding */
98 /* Maximum number of fake X11 displays to try. */
99 #define MAX_DISPLAYS  1000
100 
101 /* Per-channel callback for pre/post select() actions */
102 typedef void chan_fn(struct ssh *, Channel *c,
103     fd_set *readset, fd_set *writeset);
104 
105 /*
106  * Data structure for storing which hosts are permitted for forward requests.
107  * The local sides of any remote forwards are stored in this array to prevent
108  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
109  * network (which might be behind a firewall).
110  */
111 /* XXX: streamlocal wants a path instead of host:port */
112 /*      Overload host_to_connect; we could just make this match Forward */
113 /*	XXX - can we use listen_host instead of listen_path? */
114 struct permission {
115 	char *host_to_connect;		/* Connect to 'host'. */
116 	int port_to_connect;		/* Connect to 'port'. */
117 	char *listen_host;		/* Remote side should listen address. */
118 	char *listen_path;		/* Remote side should listen path. */
119 	int listen_port;		/* Remote side should listen port. */
120 	Channel *downstream;		/* Downstream mux*/
121 };
122 
123 /*
124  * Stores the forwarding permission state for a single direction (local or
125  * remote).
126  */
127 struct permission_set {
128 	/*
129 	 * List of all local permitted host/port pairs to allow for the
130 	 * user.
131 	 */
132 	u_int num_permitted_user;
133 	struct permission *permitted_user;
134 
135 	/*
136 	 * List of all permitted host/port pairs to allow for the admin.
137 	 */
138 	u_int num_permitted_admin;
139 	struct permission *permitted_admin;
140 
141 	/*
142 	 * If this is true, all opens/listens are permitted.  This is the
143 	 * case on the server on which we have to trust the client anyway,
144 	 * and the user could do anything after logging in.
145 	 */
146 	int all_permitted;
147 };
148 
149 /* Master structure for channels state */
150 struct ssh_channels {
151 	/*
152 	 * Pointer to an array containing all allocated channels.  The array
153 	 * is dynamically extended as needed.
154 	 */
155 	Channel **channels;
156 
157 	/*
158 	 * Size of the channel array.  All slots of the array must always be
159 	 * initialized (at least the type field); unused slots set to NULL
160 	 */
161 	u_int channels_alloc;
162 
163 	/*
164 	 * Maximum file descriptor value used in any of the channels.  This is
165 	 * updated in channel_new.
166 	 */
167 	int channel_max_fd;
168 
169 	/*
170 	 * 'channel_pre*' are called just before select() to add any bits
171 	 * relevant to channels in the select bitmasks.
172 	 *
173 	 * 'channel_post*': perform any appropriate operations for
174 	 * channels which have events pending.
175 	 */
176 	chan_fn **channel_pre;
177 	chan_fn **channel_post;
178 
179 	/* -- tcp forwarding */
180 	struct permission_set local_perms;
181 	struct permission_set remote_perms;
182 
183 	/* -- X11 forwarding */
184 
185 	/* Saved X11 local (client) display. */
186 	char *x11_saved_display;
187 
188 	/* Saved X11 authentication protocol name. */
189 	char *x11_saved_proto;
190 
191 	/* Saved X11 authentication data.  This is the real data. */
192 	char *x11_saved_data;
193 	u_int x11_saved_data_len;
194 
195 	/* Deadline after which all X11 connections are refused */
196 	u_int x11_refuse_time;
197 
198 	/*
199 	 * Fake X11 authentication data.  This is what the server will be
200 	 * sending us; we should replace any occurrences of this by the
201 	 * real data.
202 	 */
203 	u_char *x11_fake_data;
204 	u_int x11_fake_data_len;
205 
206 	/* AF_UNSPEC or AF_INET or AF_INET6 */
207 	int IPv4or6;
208 };
209 
210 /* helper */
211 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
212 static const char *channel_rfwd_bind_host(const char *listen_host);
213 
214 /* non-blocking connect helpers */
215 static int connect_next(struct channel_connect *);
216 static void channel_connect_ctx_free(struct channel_connect *);
217 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
218 static int rdynamic_connect_finish(struct ssh *, Channel *);
219 
220 /* Setup helper */
221 static void channel_handler_init(struct ssh_channels *sc);
222 
223 /* -- channel core */
224 
225 void
226 channel_init_channels(struct ssh *ssh)
227 {
228 	struct ssh_channels *sc;
229 
230 	if ((sc = calloc(1, sizeof(*sc))) == NULL)
231 		fatal("%s: allocation failed", __func__);
232 	sc->channels_alloc = 10;
233 	sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
234 	sc->IPv4or6 = AF_UNSPEC;
235 	channel_handler_init(sc);
236 
237 	ssh->chanctxt = sc;
238 }
239 
240 Channel *
241 channel_by_id(struct ssh *ssh, int id)
242 {
243 	Channel *c;
244 
245 	if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
246 		logit("%s: %d: bad id", __func__, id);
247 		return NULL;
248 	}
249 	c = ssh->chanctxt->channels[id];
250 	if (c == NULL) {
251 		logit("%s: %d: bad id: channel free", __func__, id);
252 		return NULL;
253 	}
254 	return c;
255 }
256 
257 Channel *
258 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
259 {
260 	Channel *c;
261 	u_int i;
262 
263 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
264 		c = ssh->chanctxt->channels[i];
265 		if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
266 			return c;
267 	}
268 	return NULL;
269 }
270 
271 /*
272  * Returns the channel if it is allowed to receive protocol messages.
273  * Private channels, like listening sockets, may not receive messages.
274  */
275 Channel *
276 channel_lookup(struct ssh *ssh, int id)
277 {
278 	Channel *c;
279 
280 	if ((c = channel_by_id(ssh, id)) == NULL)
281 		return NULL;
282 
283 	switch (c->type) {
284 	case SSH_CHANNEL_X11_OPEN:
285 	case SSH_CHANNEL_LARVAL:
286 	case SSH_CHANNEL_CONNECTING:
287 	case SSH_CHANNEL_DYNAMIC:
288 	case SSH_CHANNEL_RDYNAMIC_OPEN:
289 	case SSH_CHANNEL_RDYNAMIC_FINISH:
290 	case SSH_CHANNEL_OPENING:
291 	case SSH_CHANNEL_OPEN:
292 	case SSH_CHANNEL_ABANDONED:
293 	case SSH_CHANNEL_MUX_PROXY:
294 		return c;
295 	}
296 	logit("Non-public channel %d, type %d.", id, c->type);
297 	return NULL;
298 }
299 
300 /*
301  * Register filedescriptors for a channel, used when allocating a channel or
302  * when the channel consumer/producer is ready, e.g. shell exec'd
303  */
304 static void
305 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
306     int extusage, int nonblock, int is_tty)
307 {
308 	struct ssh_channels *sc = ssh->chanctxt;
309 
310 	/* Update the maximum file descriptor value. */
311 	sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, rfd);
312 	sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, wfd);
313 	sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, efd);
314 
315 	if (rfd != -1)
316 		fcntl(rfd, F_SETFD, FD_CLOEXEC);
317 	if (wfd != -1 && wfd != rfd)
318 		fcntl(wfd, F_SETFD, FD_CLOEXEC);
319 	if (efd != -1 && efd != rfd && efd != wfd)
320 		fcntl(efd, F_SETFD, FD_CLOEXEC);
321 
322 	c->rfd = rfd;
323 	c->wfd = wfd;
324 	c->sock = (rfd == wfd) ? rfd : -1;
325 	c->efd = efd;
326 	c->extended_usage = extusage;
327 
328 	if ((c->isatty = is_tty) != 0)
329 		debug2("channel %d: rfd %d isatty", c->self, c->rfd);
330 #ifdef _AIX
331 	/* XXX: Later AIX versions can't push as much data to tty */
332 	c->wfd_isatty = is_tty || isatty(c->wfd);
333 #endif
334 
335 	/* enable nonblocking mode */
336 	if (nonblock) {
337 		if (rfd != -1)
338 			set_nonblock(rfd);
339 		if (wfd != -1)
340 			set_nonblock(wfd);
341 		if (efd != -1)
342 			set_nonblock(efd);
343 	}
344 }
345 
346 /*
347  * Allocate a new channel object and set its type and socket. This will cause
348  * remote_name to be freed.
349  */
350 Channel *
351 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
352     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
353 {
354 	struct ssh_channels *sc = ssh->chanctxt;
355 	u_int i, found;
356 	Channel *c;
357 	int r;
358 
359 	/* Try to find a free slot where to put the new channel. */
360 	for (i = 0; i < sc->channels_alloc; i++) {
361 		if (sc->channels[i] == NULL) {
362 			/* Found a free slot. */
363 			found = i;
364 			break;
365 		}
366 	}
367 	if (i >= sc->channels_alloc) {
368 		/*
369 		 * There are no free slots. Take last+1 slot and expand
370 		 * the array.
371 		 */
372 		found = sc->channels_alloc;
373 		if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
374 			fatal("%s: internal error: channels_alloc %d too big",
375 			    __func__, sc->channels_alloc);
376 		sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
377 		    sc->channels_alloc + 10, sizeof(*sc->channels));
378 		sc->channels_alloc += 10;
379 		debug2("channel: expanding %d", sc->channels_alloc);
380 	}
381 	/* Initialize and return new channel. */
382 	c = sc->channels[found] = xcalloc(1, sizeof(Channel));
383 	if ((c->input = sshbuf_new()) == NULL ||
384 	    (c->output = sshbuf_new()) == NULL ||
385 	    (c->extended = sshbuf_new()) == NULL)
386 		fatal("%s: sshbuf_new failed", __func__);
387 	if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
388 		fatal("%s: sshbuf_set_max_size: %s", __func__, ssh_err(r));
389 	c->ostate = CHAN_OUTPUT_OPEN;
390 	c->istate = CHAN_INPUT_OPEN;
391 	channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
392 	c->self = found;
393 	c->type = type;
394 	c->ctype = ctype;
395 	c->local_window = window;
396 	c->local_window_max = window;
397 	c->local_maxpacket = maxpack;
398 	c->remote_name = xstrdup(remote_name);
399 	c->ctl_chan = -1;
400 	c->delayed = 1;		/* prevent call to channel_post handler */
401 	TAILQ_INIT(&c->status_confirms);
402 	debug("channel %d: new [%s]", found, remote_name);
403 	return c;
404 }
405 
406 static void
407 channel_find_maxfd(struct ssh_channels *sc)
408 {
409 	u_int i;
410 	int max = 0;
411 	Channel *c;
412 
413 	for (i = 0; i < sc->channels_alloc; i++) {
414 		c = sc->channels[i];
415 		if (c != NULL) {
416 			max = MAXIMUM(max, c->rfd);
417 			max = MAXIMUM(max, c->wfd);
418 			max = MAXIMUM(max, c->efd);
419 		}
420 	}
421 	sc->channel_max_fd = max;
422 }
423 
424 int
425 channel_close_fd(struct ssh *ssh, int *fdp)
426 {
427 	struct ssh_channels *sc = ssh->chanctxt;
428 	int ret = 0, fd = *fdp;
429 
430 	if (fd != -1) {
431 		ret = close(fd);
432 		*fdp = -1;
433 		if (fd == sc->channel_max_fd)
434 			channel_find_maxfd(sc);
435 	}
436 	return ret;
437 }
438 
439 /* Close all channel fd/socket. */
440 static void
441 channel_close_fds(struct ssh *ssh, Channel *c)
442 {
443 	int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
444 
445 	channel_close_fd(ssh, &c->sock);
446 	if (rfd != sock)
447 		channel_close_fd(ssh, &c->rfd);
448 	if (wfd != sock && wfd != rfd)
449 		channel_close_fd(ssh, &c->wfd);
450 	if (efd != sock && efd != rfd && efd != wfd)
451 		channel_close_fd(ssh, &c->efd);
452 }
453 
454 static void
455 fwd_perm_clear(struct permission *perm)
456 {
457 	free(perm->host_to_connect);
458 	free(perm->listen_host);
459 	free(perm->listen_path);
460 	memset(perm, 0, sizeof(*perm));
461 }
462 
463 /* Returns an printable name for the specified forwarding permission list */
464 static const char *
465 fwd_ident(int who, int where)
466 {
467 	if (who == FORWARD_ADM) {
468 		if (where == FORWARD_LOCAL)
469 			return "admin local";
470 		else if (where == FORWARD_REMOTE)
471 			return "admin remote";
472 	} else if (who == FORWARD_USER) {
473 		if (where == FORWARD_LOCAL)
474 			return "user local";
475 		else if (where == FORWARD_REMOTE)
476 			return "user remote";
477 	}
478 	fatal("Unknown forward permission list %d/%d", who, where);
479 }
480 
481 /* Returns the forwarding permission list for the specified direction */
482 static struct permission_set *
483 permission_set_get(struct ssh *ssh, int where)
484 {
485 	struct ssh_channels *sc = ssh->chanctxt;
486 
487 	switch (where) {
488 	case FORWARD_LOCAL:
489 		return &sc->local_perms;
490 		break;
491 	case FORWARD_REMOTE:
492 		return &sc->remote_perms;
493 		break;
494 	default:
495 		fatal("%s: invalid forwarding direction %d", __func__, where);
496 	}
497 }
498 
499 /* Returns pointers to the specified forwarding list and its element count */
500 static void
501 permission_set_get_array(struct ssh *ssh, int who, int where,
502     struct permission ***permpp, u_int **npermpp)
503 {
504 	struct permission_set *pset = permission_set_get(ssh, where);
505 
506 	switch (who) {
507 	case FORWARD_USER:
508 		*permpp = &pset->permitted_user;
509 		*npermpp = &pset->num_permitted_user;
510 		break;
511 	case FORWARD_ADM:
512 		*permpp = &pset->permitted_admin;
513 		*npermpp = &pset->num_permitted_admin;
514 		break;
515 	default:
516 		fatal("%s: invalid forwarding client %d", __func__, who);
517 	}
518 }
519 
520 /* Adds an entry to the spcified forwarding list */
521 static int
522 permission_set_add(struct ssh *ssh, int who, int where,
523     const char *host_to_connect, int port_to_connect,
524     const char *listen_host, const char *listen_path, int listen_port,
525     Channel *downstream)
526 {
527 	struct permission **permp;
528 	u_int n, *npermp;
529 
530 	permission_set_get_array(ssh, who, where, &permp, &npermp);
531 
532 	if (*npermp >= INT_MAX)
533 		fatal("%s: %s overflow", __func__, fwd_ident(who, where));
534 
535 	*permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
536 	n = (*npermp)++;
537 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
538 	(*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
539 	(*permp)[n].port_to_connect = port_to_connect;
540 	(*permp)[n].listen_host = MAYBE_DUP(listen_host);
541 	(*permp)[n].listen_path = MAYBE_DUP(listen_path);
542 	(*permp)[n].listen_port = listen_port;
543 	(*permp)[n].downstream = downstream;
544 #undef MAYBE_DUP
545 	return (int)n;
546 }
547 
548 static void
549 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
550 {
551 	struct ssh_channels *sc = ssh->chanctxt;
552 	struct permission_set *pset = &sc->local_perms;
553 	struct permission *perm;
554 	int r;
555 	u_int i;
556 
557 	for (i = 0; i < pset->num_permitted_user; i++) {
558 		perm = &pset->permitted_user[i];
559 		if (perm->downstream != c)
560 			continue;
561 
562 		/* cancel on the server, since mux client is gone */
563 		debug("channel %d: cleanup remote forward for %s:%u",
564 		    c->self, perm->listen_host, perm->listen_port);
565 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
566 		    (r = sshpkt_put_cstring(ssh,
567 		    "cancel-tcpip-forward")) != 0 ||
568 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
569 		    (r = sshpkt_put_cstring(ssh,
570 		    channel_rfwd_bind_host(perm->listen_host))) != 0 ||
571 		    (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
572 		    (r = sshpkt_send(ssh)) != 0) {
573 			fatal("%s: channel %i: %s", __func__,
574 			    c->self, ssh_err(r));
575 		}
576 		fwd_perm_clear(perm); /* unregister */
577 	}
578 }
579 
580 /* Free the channel and close its fd/socket. */
581 void
582 channel_free(struct ssh *ssh, Channel *c)
583 {
584 	struct ssh_channels *sc = ssh->chanctxt;
585 	char *s;
586 	u_int i, n;
587 	Channel *other;
588 	struct channel_confirm *cc;
589 
590 	for (n = 0, i = 0; i < sc->channels_alloc; i++) {
591 		if ((other = sc->channels[i]) == NULL)
592 			continue;
593 		n++;
594 		/* detach from mux client and prepare for closing */
595 		if (c->type == SSH_CHANNEL_MUX_CLIENT &&
596 		    other->type == SSH_CHANNEL_MUX_PROXY &&
597 		    other->mux_ctx == c) {
598 			other->mux_ctx = NULL;
599 			other->type = SSH_CHANNEL_OPEN;
600 			other->istate = CHAN_INPUT_CLOSED;
601 			other->ostate = CHAN_OUTPUT_CLOSED;
602 		}
603 	}
604 	debug("channel %d: free: %s, nchannels %u", c->self,
605 	    c->remote_name ? c->remote_name : "???", n);
606 
607 	if (c->type == SSH_CHANNEL_MUX_CLIENT)
608 		mux_remove_remote_forwardings(ssh, c);
609 	else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
610 		free(c->mux_ctx);
611 		c->mux_ctx = NULL;
612 	}
613 
614 	if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
615 		s = channel_open_message(ssh);
616 		debug3("channel %d: status: %s", c->self, s);
617 		free(s);
618 	}
619 
620 	channel_close_fds(ssh, c);
621 	sshbuf_free(c->input);
622 	sshbuf_free(c->output);
623 	sshbuf_free(c->extended);
624 	c->input = c->output = c->extended = NULL;
625 	free(c->remote_name);
626 	c->remote_name = NULL;
627 	free(c->path);
628 	c->path = NULL;
629 	free(c->listening_addr);
630 	c->listening_addr = NULL;
631 	while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
632 		if (cc->abandon_cb != NULL)
633 			cc->abandon_cb(ssh, c, cc->ctx);
634 		TAILQ_REMOVE(&c->status_confirms, cc, entry);
635 		freezero(cc, sizeof(*cc));
636 	}
637 	if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
638 		c->filter_cleanup(ssh, c->self, c->filter_ctx);
639 	sc->channels[c->self] = NULL;
640 	freezero(c, sizeof(*c));
641 }
642 
643 void
644 channel_free_all(struct ssh *ssh)
645 {
646 	u_int i;
647 	struct ssh_channels *sc = ssh->chanctxt;
648 
649 	for (i = 0; i < sc->channels_alloc; i++)
650 		if (sc->channels[i] != NULL)
651 			channel_free(ssh, sc->channels[i]);
652 
653 	free(sc->channels);
654 	sc->channels = NULL;
655 	sc->channels_alloc = 0;
656 	sc->channel_max_fd = 0;
657 
658 	free(sc->x11_saved_display);
659 	sc->x11_saved_display = NULL;
660 
661 	free(sc->x11_saved_proto);
662 	sc->x11_saved_proto = NULL;
663 
664 	free(sc->x11_saved_data);
665 	sc->x11_saved_data = NULL;
666 	sc->x11_saved_data_len = 0;
667 
668 	free(sc->x11_fake_data);
669 	sc->x11_fake_data = NULL;
670 	sc->x11_fake_data_len = 0;
671 }
672 
673 /*
674  * Closes the sockets/fds of all channels.  This is used to close extra file
675  * descriptors after a fork.
676  */
677 void
678 channel_close_all(struct ssh *ssh)
679 {
680 	u_int i;
681 
682 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
683 		if (ssh->chanctxt->channels[i] != NULL)
684 			channel_close_fds(ssh, ssh->chanctxt->channels[i]);
685 }
686 
687 /*
688  * Stop listening to channels.
689  */
690 void
691 channel_stop_listening(struct ssh *ssh)
692 {
693 	u_int i;
694 	Channel *c;
695 
696 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
697 		c = ssh->chanctxt->channels[i];
698 		if (c != NULL) {
699 			switch (c->type) {
700 			case SSH_CHANNEL_AUTH_SOCKET:
701 			case SSH_CHANNEL_PORT_LISTENER:
702 			case SSH_CHANNEL_RPORT_LISTENER:
703 			case SSH_CHANNEL_X11_LISTENER:
704 			case SSH_CHANNEL_UNIX_LISTENER:
705 			case SSH_CHANNEL_RUNIX_LISTENER:
706 				channel_close_fd(ssh, &c->sock);
707 				channel_free(ssh, c);
708 				break;
709 			}
710 		}
711 	}
712 }
713 
714 /*
715  * Returns true if no channel has too much buffered data, and false if one or
716  * more channel is overfull.
717  */
718 int
719 channel_not_very_much_buffered_data(struct ssh *ssh)
720 {
721 	u_int i;
722 	u_int maxsize = ssh_packet_get_maxsize(ssh);
723 	Channel *c;
724 
725 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
726 		c = ssh->chanctxt->channels[i];
727 		if (c == NULL || c->type != SSH_CHANNEL_OPEN)
728 			continue;
729 		if (sshbuf_len(c->output) > maxsize) {
730 			debug2("channel %d: big output buffer %zu > %u",
731 			    c->self, sshbuf_len(c->output), maxsize);
732 			return 0;
733 		}
734 	}
735 	return 1;
736 }
737 
738 /* Returns true if any channel is still open. */
739 int
740 channel_still_open(struct ssh *ssh)
741 {
742 	u_int i;
743 	Channel *c;
744 
745 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
746 		c = ssh->chanctxt->channels[i];
747 		if (c == NULL)
748 			continue;
749 		switch (c->type) {
750 		case SSH_CHANNEL_X11_LISTENER:
751 		case SSH_CHANNEL_PORT_LISTENER:
752 		case SSH_CHANNEL_RPORT_LISTENER:
753 		case SSH_CHANNEL_MUX_LISTENER:
754 		case SSH_CHANNEL_CLOSED:
755 		case SSH_CHANNEL_AUTH_SOCKET:
756 		case SSH_CHANNEL_DYNAMIC:
757 		case SSH_CHANNEL_RDYNAMIC_OPEN:
758 		case SSH_CHANNEL_CONNECTING:
759 		case SSH_CHANNEL_ZOMBIE:
760 		case SSH_CHANNEL_ABANDONED:
761 		case SSH_CHANNEL_UNIX_LISTENER:
762 		case SSH_CHANNEL_RUNIX_LISTENER:
763 			continue;
764 		case SSH_CHANNEL_LARVAL:
765 			continue;
766 		case SSH_CHANNEL_OPENING:
767 		case SSH_CHANNEL_OPEN:
768 		case SSH_CHANNEL_RDYNAMIC_FINISH:
769 		case SSH_CHANNEL_X11_OPEN:
770 		case SSH_CHANNEL_MUX_CLIENT:
771 		case SSH_CHANNEL_MUX_PROXY:
772 			return 1;
773 		default:
774 			fatal("%s: bad channel type %d", __func__, c->type);
775 			/* NOTREACHED */
776 		}
777 	}
778 	return 0;
779 }
780 
781 /* Returns the id of an open channel suitable for keepaliving */
782 int
783 channel_find_open(struct ssh *ssh)
784 {
785 	u_int i;
786 	Channel *c;
787 
788 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
789 		c = ssh->chanctxt->channels[i];
790 		if (c == NULL || !c->have_remote_id)
791 			continue;
792 		switch (c->type) {
793 		case SSH_CHANNEL_CLOSED:
794 		case SSH_CHANNEL_DYNAMIC:
795 		case SSH_CHANNEL_RDYNAMIC_OPEN:
796 		case SSH_CHANNEL_RDYNAMIC_FINISH:
797 		case SSH_CHANNEL_X11_LISTENER:
798 		case SSH_CHANNEL_PORT_LISTENER:
799 		case SSH_CHANNEL_RPORT_LISTENER:
800 		case SSH_CHANNEL_MUX_LISTENER:
801 		case SSH_CHANNEL_MUX_CLIENT:
802 		case SSH_CHANNEL_MUX_PROXY:
803 		case SSH_CHANNEL_OPENING:
804 		case SSH_CHANNEL_CONNECTING:
805 		case SSH_CHANNEL_ZOMBIE:
806 		case SSH_CHANNEL_ABANDONED:
807 		case SSH_CHANNEL_UNIX_LISTENER:
808 		case SSH_CHANNEL_RUNIX_LISTENER:
809 			continue;
810 		case SSH_CHANNEL_LARVAL:
811 		case SSH_CHANNEL_AUTH_SOCKET:
812 		case SSH_CHANNEL_OPEN:
813 		case SSH_CHANNEL_X11_OPEN:
814 			return i;
815 		default:
816 			fatal("%s: bad channel type %d", __func__, c->type);
817 			/* NOTREACHED */
818 		}
819 	}
820 	return -1;
821 }
822 
823 /* Returns the state of the channel's extended usage flag */
824 const char *
825 channel_format_extended_usage(const Channel *c)
826 {
827 	if (c->efd == -1)
828 		return "closed";
829 
830 	switch (c->extended_usage) {
831 	case CHAN_EXTENDED_WRITE:
832 		return "write";
833 	case CHAN_EXTENDED_READ:
834 		return "read";
835 	case CHAN_EXTENDED_IGNORE:
836 		return "ignore";
837 	default:
838 		return "UNKNOWN";
839 	}
840 }
841 
842 static char *
843 channel_format_status(const Channel *c)
844 {
845 	char *ret = NULL;
846 
847 	xasprintf(&ret, "t%d %s%u i%u/%zu o%u/%zu e[%s]/%zu "
848 	    "fd %d/%d/%d sock %d cc %d",
849 	    c->type,
850 	    c->have_remote_id ? "r" : "nr", c->remote_id,
851 	    c->istate, sshbuf_len(c->input),
852 	    c->ostate, sshbuf_len(c->output),
853 	    channel_format_extended_usage(c), sshbuf_len(c->extended),
854 	    c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan);
855 	return ret;
856 }
857 
858 /*
859  * Returns a message describing the currently open forwarded connections,
860  * suitable for sending to the client.  The message contains crlf pairs for
861  * newlines.
862  */
863 char *
864 channel_open_message(struct ssh *ssh)
865 {
866 	struct sshbuf *buf;
867 	Channel *c;
868 	u_int i;
869 	int r;
870 	char *cp, *ret;
871 
872 	if ((buf = sshbuf_new()) == NULL)
873 		fatal("%s: sshbuf_new", __func__);
874 	if ((r = sshbuf_putf(buf,
875 	    "The following connections are open:\r\n")) != 0)
876 		fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
877 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
878 		c = ssh->chanctxt->channels[i];
879 		if (c == NULL)
880 			continue;
881 		switch (c->type) {
882 		case SSH_CHANNEL_X11_LISTENER:
883 		case SSH_CHANNEL_PORT_LISTENER:
884 		case SSH_CHANNEL_RPORT_LISTENER:
885 		case SSH_CHANNEL_CLOSED:
886 		case SSH_CHANNEL_AUTH_SOCKET:
887 		case SSH_CHANNEL_ZOMBIE:
888 		case SSH_CHANNEL_ABANDONED:
889 		case SSH_CHANNEL_MUX_LISTENER:
890 		case SSH_CHANNEL_UNIX_LISTENER:
891 		case SSH_CHANNEL_RUNIX_LISTENER:
892 			continue;
893 		case SSH_CHANNEL_LARVAL:
894 		case SSH_CHANNEL_OPENING:
895 		case SSH_CHANNEL_CONNECTING:
896 		case SSH_CHANNEL_DYNAMIC:
897 		case SSH_CHANNEL_RDYNAMIC_OPEN:
898 		case SSH_CHANNEL_RDYNAMIC_FINISH:
899 		case SSH_CHANNEL_OPEN:
900 		case SSH_CHANNEL_X11_OPEN:
901 		case SSH_CHANNEL_MUX_PROXY:
902 		case SSH_CHANNEL_MUX_CLIENT:
903 			cp = channel_format_status(c);
904 			if ((r = sshbuf_putf(buf, "  #%d %.300s (%s)\r\n",
905 			    c->self, c->remote_name, cp)) != 0) {
906 				free(cp);
907 				fatal("%s: sshbuf_putf: %s",
908 				    __func__, ssh_err(r));
909 			}
910 			free(cp);
911 			continue;
912 		default:
913 			fatal("%s: bad channel type %d", __func__, c->type);
914 			/* NOTREACHED */
915 		}
916 	}
917 	if ((ret = sshbuf_dup_string(buf)) == NULL)
918 		fatal("%s: sshbuf_dup_string", __func__);
919 	sshbuf_free(buf);
920 	return ret;
921 }
922 
923 static void
924 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
925 {
926 	int r;
927 
928 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
929 	    (r = sshpkt_put_cstring(ssh, type)) != 0 ||
930 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
931 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
932 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
933 		fatal("%s: channel %i: open: %s", where, c->self, ssh_err(r));
934 	}
935 }
936 
937 void
938 channel_send_open(struct ssh *ssh, int id)
939 {
940 	Channel *c = channel_lookup(ssh, id);
941 	int r;
942 
943 	if (c == NULL) {
944 		logit("channel_send_open: %d: bad id", id);
945 		return;
946 	}
947 	debug2("channel %d: send open", id);
948 	open_preamble(ssh, __func__, c, c->ctype);
949 	if ((r = sshpkt_send(ssh)) != 0)
950 		fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
951 }
952 
953 void
954 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
955 {
956 	Channel *c = channel_lookup(ssh, id);
957 	int r;
958 
959 	if (c == NULL) {
960 		logit("%s: %d: unknown channel id", __func__, id);
961 		return;
962 	}
963 	if (!c->have_remote_id)
964 		fatal(":%s: channel %d: no remote id", __func__, c->self);
965 
966 	debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
967 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
968 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
969 	    (r = sshpkt_put_cstring(ssh, service)) != 0 ||
970 	    (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
971 		fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
972 	}
973 }
974 
975 void
976 channel_register_status_confirm(struct ssh *ssh, int id,
977     channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
978 {
979 	struct channel_confirm *cc;
980 	Channel *c;
981 
982 	if ((c = channel_lookup(ssh, id)) == NULL)
983 		fatal("%s: %d: bad id", __func__, id);
984 
985 	cc = xcalloc(1, sizeof(*cc));
986 	cc->cb = cb;
987 	cc->abandon_cb = abandon_cb;
988 	cc->ctx = ctx;
989 	TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
990 }
991 
992 void
993 channel_register_open_confirm(struct ssh *ssh, int id,
994     channel_open_fn *fn, void *ctx)
995 {
996 	Channel *c = channel_lookup(ssh, id);
997 
998 	if (c == NULL) {
999 		logit("%s: %d: bad id", __func__, id);
1000 		return;
1001 	}
1002 	c->open_confirm = fn;
1003 	c->open_confirm_ctx = ctx;
1004 }
1005 
1006 void
1007 channel_register_cleanup(struct ssh *ssh, int id,
1008     channel_callback_fn *fn, int do_close)
1009 {
1010 	Channel *c = channel_by_id(ssh, id);
1011 
1012 	if (c == NULL) {
1013 		logit("%s: %d: bad id", __func__, id);
1014 		return;
1015 	}
1016 	c->detach_user = fn;
1017 	c->detach_close = do_close;
1018 }
1019 
1020 void
1021 channel_cancel_cleanup(struct ssh *ssh, int id)
1022 {
1023 	Channel *c = channel_by_id(ssh, id);
1024 
1025 	if (c == NULL) {
1026 		logit("%s: %d: bad id", __func__, id);
1027 		return;
1028 	}
1029 	c->detach_user = NULL;
1030 	c->detach_close = 0;
1031 }
1032 
1033 void
1034 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1035     channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1036 {
1037 	Channel *c = channel_lookup(ssh, id);
1038 
1039 	if (c == NULL) {
1040 		logit("%s: %d: bad id", __func__, id);
1041 		return;
1042 	}
1043 	c->input_filter = ifn;
1044 	c->output_filter = ofn;
1045 	c->filter_ctx = ctx;
1046 	c->filter_cleanup = cfn;
1047 }
1048 
1049 void
1050 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1051     int extusage, int nonblock, int is_tty, u_int window_max)
1052 {
1053 	Channel *c = channel_lookup(ssh, id);
1054 	int r;
1055 
1056 	if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1057 		fatal("channel_activate for non-larval channel %d.", id);
1058 	if (!c->have_remote_id)
1059 		fatal(":%s: channel %d: no remote id", __func__, c->self);
1060 
1061 	channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1062 	c->type = SSH_CHANNEL_OPEN;
1063 	c->local_window = c->local_window_max = window_max;
1064 
1065 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1066 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1067 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1068 	    (r = sshpkt_send(ssh)) != 0)
1069 		fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
1070 }
1071 
1072 static void
1073 channel_pre_listener(struct ssh *ssh, Channel *c,
1074     fd_set *readset, fd_set *writeset)
1075 {
1076 	FD_SET(c->sock, readset);
1077 }
1078 
1079 static void
1080 channel_pre_connecting(struct ssh *ssh, Channel *c,
1081     fd_set *readset, fd_set *writeset)
1082 {
1083 	debug3("channel %d: waiting for connection", c->self);
1084 	FD_SET(c->sock, writeset);
1085 }
1086 
1087 static void
1088 channel_pre_open(struct ssh *ssh, Channel *c,
1089     fd_set *readset, fd_set *writeset)
1090 {
1091 	if (c->istate == CHAN_INPUT_OPEN &&
1092 	    c->remote_window > 0 &&
1093 	    sshbuf_len(c->input) < c->remote_window &&
1094 	    sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1095 		FD_SET(c->rfd, readset);
1096 	if (c->ostate == CHAN_OUTPUT_OPEN ||
1097 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1098 		if (sshbuf_len(c->output) > 0) {
1099 			FD_SET(c->wfd, writeset);
1100 		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1101 			if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1102 				debug2("channel %d: "
1103 				    "obuf_empty delayed efd %d/(%zu)", c->self,
1104 				    c->efd, sshbuf_len(c->extended));
1105 			else
1106 				chan_obuf_empty(ssh, c);
1107 		}
1108 	}
1109 	/** XXX check close conditions, too */
1110 	if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1111 	    c->ostate == CHAN_OUTPUT_CLOSED)) {
1112 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1113 		    sshbuf_len(c->extended) > 0)
1114 			FD_SET(c->efd, writeset);
1115 		else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1116 		    (c->extended_usage == CHAN_EXTENDED_READ ||
1117 		    c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1118 		    sshbuf_len(c->extended) < c->remote_window)
1119 			FD_SET(c->efd, readset);
1120 	}
1121 	/* XXX: What about efd? races? */
1122 }
1123 
1124 /*
1125  * This is a special state for X11 authentication spoofing.  An opened X11
1126  * connection (when authentication spoofing is being done) remains in this
1127  * state until the first packet has been completely read.  The authentication
1128  * data in that packet is then substituted by the real data if it matches the
1129  * fake data, and the channel is put into normal mode.
1130  * XXX All this happens at the client side.
1131  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1132  */
1133 static int
1134 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1135 {
1136 	struct ssh_channels *sc = ssh->chanctxt;
1137 	u_char *ucp;
1138 	u_int proto_len, data_len;
1139 
1140 	/* Is this being called after the refusal deadline? */
1141 	if (sc->x11_refuse_time != 0 &&
1142 	    (u_int)monotime() >= sc->x11_refuse_time) {
1143 		verbose("Rejected X11 connection after ForwardX11Timeout "
1144 		    "expired");
1145 		return -1;
1146 	}
1147 
1148 	/* Check if the fixed size part of the packet is in buffer. */
1149 	if (sshbuf_len(b) < 12)
1150 		return 0;
1151 
1152 	/* Parse the lengths of variable-length fields. */
1153 	ucp = sshbuf_mutable_ptr(b);
1154 	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
1155 		proto_len = 256 * ucp[6] + ucp[7];
1156 		data_len = 256 * ucp[8] + ucp[9];
1157 	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
1158 		proto_len = ucp[6] + 256 * ucp[7];
1159 		data_len = ucp[8] + 256 * ucp[9];
1160 	} else {
1161 		debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1162 		    ucp[0]);
1163 		return -1;
1164 	}
1165 
1166 	/* Check if the whole packet is in buffer. */
1167 	if (sshbuf_len(b) <
1168 	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1169 		return 0;
1170 
1171 	/* Check if authentication protocol matches. */
1172 	if (proto_len != strlen(sc->x11_saved_proto) ||
1173 	    memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1174 		debug2("X11 connection uses different authentication protocol.");
1175 		return -1;
1176 	}
1177 	/* Check if authentication data matches our fake data. */
1178 	if (data_len != sc->x11_fake_data_len ||
1179 	    timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1180 		sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1181 		debug2("X11 auth data does not match fake data.");
1182 		return -1;
1183 	}
1184 	/* Check fake data length */
1185 	if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1186 		error("X11 fake_data_len %d != saved_data_len %d",
1187 		    sc->x11_fake_data_len, sc->x11_saved_data_len);
1188 		return -1;
1189 	}
1190 	/*
1191 	 * Received authentication protocol and data match
1192 	 * our fake data. Substitute the fake data with real
1193 	 * data.
1194 	 */
1195 	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1196 	    sc->x11_saved_data, sc->x11_saved_data_len);
1197 	return 1;
1198 }
1199 
1200 static void
1201 channel_pre_x11_open(struct ssh *ssh, Channel *c,
1202     fd_set *readset, fd_set *writeset)
1203 {
1204 	int ret = x11_open_helper(ssh, c->output);
1205 
1206 	/* c->force_drain = 1; */
1207 
1208 	if (ret == 1) {
1209 		c->type = SSH_CHANNEL_OPEN;
1210 		channel_pre_open(ssh, c, readset, writeset);
1211 	} else if (ret == -1) {
1212 		logit("X11 connection rejected because of wrong authentication.");
1213 		debug2("X11 rejected %d i%d/o%d",
1214 		    c->self, c->istate, c->ostate);
1215 		chan_read_failed(ssh, c);
1216 		sshbuf_reset(c->input);
1217 		chan_ibuf_empty(ssh, c);
1218 		sshbuf_reset(c->output);
1219 		chan_write_failed(ssh, c);
1220 		debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1221 	}
1222 }
1223 
1224 static void
1225 channel_pre_mux_client(struct ssh *ssh,
1226     Channel *c, fd_set *readset, fd_set *writeset)
1227 {
1228 	if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1229 	    sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1230 		FD_SET(c->rfd, readset);
1231 	if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1232 		/* clear buffer immediately (discard any partial packet) */
1233 		sshbuf_reset(c->input);
1234 		chan_ibuf_empty(ssh, c);
1235 		/* Start output drain. XXX just kill chan? */
1236 		chan_rcvd_oclose(ssh, c);
1237 	}
1238 	if (c->ostate == CHAN_OUTPUT_OPEN ||
1239 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1240 		if (sshbuf_len(c->output) > 0)
1241 			FD_SET(c->wfd, writeset);
1242 		else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1243 			chan_obuf_empty(ssh, c);
1244 	}
1245 }
1246 
1247 /* try to decode a socks4 header */
1248 static int
1249 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1250 {
1251 	const u_char *p;
1252 	char *host;
1253 	u_int len, have, i, found, need;
1254 	char username[256];
1255 	struct {
1256 		u_int8_t version;
1257 		u_int8_t command;
1258 		u_int16_t dest_port;
1259 		struct in_addr dest_addr;
1260 	} s4_req, s4_rsp;
1261 	int r;
1262 
1263 	debug2("channel %d: decode socks4", c->self);
1264 
1265 	have = sshbuf_len(input);
1266 	len = sizeof(s4_req);
1267 	if (have < len)
1268 		return 0;
1269 	p = sshbuf_ptr(input);
1270 
1271 	need = 1;
1272 	/* SOCKS4A uses an invalid IP address 0.0.0.x */
1273 	if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1274 		debug2("channel %d: socks4a request", c->self);
1275 		/* ... and needs an extra string (the hostname) */
1276 		need = 2;
1277 	}
1278 	/* Check for terminating NUL on the string(s) */
1279 	for (found = 0, i = len; i < have; i++) {
1280 		if (p[i] == '\0') {
1281 			found++;
1282 			if (found == need)
1283 				break;
1284 		}
1285 		if (i > 1024) {
1286 			/* the peer is probably sending garbage */
1287 			debug("channel %d: decode socks4: too long",
1288 			    c->self);
1289 			return -1;
1290 		}
1291 	}
1292 	if (found < need)
1293 		return 0;
1294 	if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1295 	    (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1296 	    (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1297 	    (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1298 		debug("channels %d: decode socks4: %s", c->self, ssh_err(r));
1299 		return -1;
1300 	}
1301 	have = sshbuf_len(input);
1302 	p = sshbuf_ptr(input);
1303 	if (memchr(p, '\0', have) == NULL) {
1304 		error("channel %d: decode socks4: user not nul terminated",
1305 		    c->self);
1306 		return -1;
1307 	}
1308 	len = strlen(p);
1309 	debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1310 	len++; /* trailing '\0' */
1311 	strlcpy(username, p, sizeof(username));
1312 	if ((r = sshbuf_consume(input, len)) != 0) {
1313 		fatal("%s: channel %d: consume: %s", __func__,
1314 		    c->self, ssh_err(r));
1315 	}
1316 	free(c->path);
1317 	c->path = NULL;
1318 	if (need == 1) {			/* SOCKS4: one string */
1319 		host = inet_ntoa(s4_req.dest_addr);
1320 		c->path = xstrdup(host);
1321 	} else {				/* SOCKS4A: two strings */
1322 		have = sshbuf_len(input);
1323 		p = sshbuf_ptr(input);
1324 		if (memchr(p, '\0', have) == NULL) {
1325 			error("channel %d: decode socks4a: host not nul "
1326 			    "terminated", c->self);
1327 			return -1;
1328 		}
1329 		len = strlen(p);
1330 		debug2("channel %d: decode socks4a: host %s/%d",
1331 		    c->self, p, len);
1332 		len++;				/* trailing '\0' */
1333 		if (len > NI_MAXHOST) {
1334 			error("channel %d: hostname \"%.100s\" too long",
1335 			    c->self, p);
1336 			return -1;
1337 		}
1338 		c->path = xstrdup(p);
1339 		if ((r = sshbuf_consume(input, len)) != 0) {
1340 			fatal("%s: channel %d: consume: %s", __func__,
1341 			    c->self, ssh_err(r));
1342 		}
1343 	}
1344 	c->host_port = ntohs(s4_req.dest_port);
1345 
1346 	debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1347 	    c->self, c->path, c->host_port, s4_req.command);
1348 
1349 	if (s4_req.command != 1) {
1350 		debug("channel %d: cannot handle: %s cn %d",
1351 		    c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1352 		return -1;
1353 	}
1354 	s4_rsp.version = 0;			/* vn: 0 for reply */
1355 	s4_rsp.command = 90;			/* cd: req granted */
1356 	s4_rsp.dest_port = 0;			/* ignored */
1357 	s4_rsp.dest_addr.s_addr = INADDR_ANY;	/* ignored */
1358 	if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0) {
1359 		fatal("%s: channel %d: append reply: %s", __func__,
1360 		    c->self, ssh_err(r));
1361 	}
1362 	return 1;
1363 }
1364 
1365 /* try to decode a socks5 header */
1366 #define SSH_SOCKS5_AUTHDONE	0x1000
1367 #define SSH_SOCKS5_NOAUTH	0x00
1368 #define SSH_SOCKS5_IPV4		0x01
1369 #define SSH_SOCKS5_DOMAIN	0x03
1370 #define SSH_SOCKS5_IPV6		0x04
1371 #define SSH_SOCKS5_CONNECT	0x01
1372 #define SSH_SOCKS5_SUCCESS	0x00
1373 
1374 static int
1375 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1376 {
1377 	/* XXX use get/put_u8 instead of trusting struct padding */
1378 	struct {
1379 		u_int8_t version;
1380 		u_int8_t command;
1381 		u_int8_t reserved;
1382 		u_int8_t atyp;
1383 	} s5_req, s5_rsp;
1384 	u_int16_t dest_port;
1385 	char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1386 	const u_char *p;
1387 	u_int have, need, i, found, nmethods, addrlen, af;
1388 	int r;
1389 
1390 	debug2("channel %d: decode socks5", c->self);
1391 	p = sshbuf_ptr(input);
1392 	if (p[0] != 0x05)
1393 		return -1;
1394 	have = sshbuf_len(input);
1395 	if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1396 		/* format: ver | nmethods | methods */
1397 		if (have < 2)
1398 			return 0;
1399 		nmethods = p[1];
1400 		if (have < nmethods + 2)
1401 			return 0;
1402 		/* look for method: "NO AUTHENTICATION REQUIRED" */
1403 		for (found = 0, i = 2; i < nmethods + 2; i++) {
1404 			if (p[i] == SSH_SOCKS5_NOAUTH) {
1405 				found = 1;
1406 				break;
1407 			}
1408 		}
1409 		if (!found) {
1410 			debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1411 			    c->self);
1412 			return -1;
1413 		}
1414 		if ((r = sshbuf_consume(input, nmethods + 2)) != 0) {
1415 			fatal("%s: channel %d: consume: %s", __func__,
1416 			    c->self, ssh_err(r));
1417 		}
1418 		/* version, method */
1419 		if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1420 		    (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0) {
1421 			fatal("%s: channel %d: append reply: %s", __func__,
1422 			    c->self, ssh_err(r));
1423 		}
1424 		c->flags |= SSH_SOCKS5_AUTHDONE;
1425 		debug2("channel %d: socks5 auth done", c->self);
1426 		return 0;				/* need more */
1427 	}
1428 	debug2("channel %d: socks5 post auth", c->self);
1429 	if (have < sizeof(s5_req)+1)
1430 		return 0;			/* need more */
1431 	memcpy(&s5_req, p, sizeof(s5_req));
1432 	if (s5_req.version != 0x05 ||
1433 	    s5_req.command != SSH_SOCKS5_CONNECT ||
1434 	    s5_req.reserved != 0x00) {
1435 		debug2("channel %d: only socks5 connect supported", c->self);
1436 		return -1;
1437 	}
1438 	switch (s5_req.atyp){
1439 	case SSH_SOCKS5_IPV4:
1440 		addrlen = 4;
1441 		af = AF_INET;
1442 		break;
1443 	case SSH_SOCKS5_DOMAIN:
1444 		addrlen = p[sizeof(s5_req)];
1445 		af = -1;
1446 		break;
1447 	case SSH_SOCKS5_IPV6:
1448 		addrlen = 16;
1449 		af = AF_INET6;
1450 		break;
1451 	default:
1452 		debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1453 		return -1;
1454 	}
1455 	need = sizeof(s5_req) + addrlen + 2;
1456 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1457 		need++;
1458 	if (have < need)
1459 		return 0;
1460 	if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0) {
1461 		fatal("%s: channel %d: consume: %s", __func__,
1462 		    c->self, ssh_err(r));
1463 	}
1464 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1465 		/* host string length */
1466 		if ((r = sshbuf_consume(input, 1)) != 0) {
1467 			fatal("%s: channel %d: consume: %s", __func__,
1468 			    c->self, ssh_err(r));
1469 		}
1470 	}
1471 	if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1472 	    (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1473 		debug("channel %d: parse addr/port: %s", c->self, ssh_err(r));
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("%s: channel %d: append reply: %s", __func__,
1506 		    c->self, ssh_err(r));
1507 	return 1;
1508 }
1509 
1510 Channel *
1511 channel_connect_stdio_fwd(struct ssh *ssh,
1512     const char *host_to_connect, u_short port_to_connect, int in, int out)
1513 {
1514 	Channel *c;
1515 
1516 	debug("%s %s:%d", __func__, 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*/0);
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     fd_set *readset, fd_set *writeset)
1537 {
1538 	const u_char *p;
1539 	u_int have;
1540 	int ret;
1541 
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 		FD_SET(c->sock, readset);
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 		FD_SET(c->sock, readset);
1571 		if (sshbuf_len(c->output))
1572 			FD_SET(c->sock, writeset);
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_select_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("%s: channel %d: consume: %s",
1607 			    __func__, c->self, ssh_err(r));
1608 		}
1609 		rdynamic_close(ssh, c);
1610 		return;
1611 	}
1612 	/* check if the fixed size part of the packet is in buffer. */
1613 	if (have < 3)
1614 		return;
1615 	/* try to guess the protocol */
1616 	p = sshbuf_ptr(c->output);
1617 	switch (p[0]) {
1618 	case 0x04:
1619 		/* switch input/output for reverse forwarding */
1620 		ret = channel_decode_socks4(c, c->output, c->input);
1621 		break;
1622 	case 0x05:
1623 		ret = channel_decode_socks5(c, c->output, c->input);
1624 		break;
1625 	default:
1626 		ret = -1;
1627 		break;
1628 	}
1629 	if (ret < 0) {
1630 		rdynamic_close(ssh, c);
1631 	} else if (ret == 0) {
1632 		debug2("channel %d: pre_rdynamic: need more", c->self);
1633 		/* send socks request to peer */
1634 		len = sshbuf_len(c->input);
1635 		if (len > 0 && len < c->remote_window) {
1636 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1637 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1638 			    (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1639 			    (r = sshpkt_send(ssh)) != 0) {
1640 				fatal("%s: channel %i: rdynamic: %s", __func__,
1641 				    c->self, ssh_err(r));
1642 			}
1643 			if ((r = sshbuf_consume(c->input, len)) != 0) {
1644 				fatal("%s: channel %d: consume: %s",
1645 				    __func__, c->self, ssh_err(r));
1646 			}
1647 			c->remote_window -= len;
1648 		}
1649 	} else if (rdynamic_connect_finish(ssh, c) < 0) {
1650 		/* the connect failed */
1651 		rdynamic_close(ssh, c);
1652 	}
1653 }
1654 
1655 /* This is our fake X11 server socket. */
1656 static void
1657 channel_post_x11_listener(struct ssh *ssh, Channel *c,
1658     fd_set *readset, fd_set *writeset)
1659 {
1660 	Channel *nc;
1661 	struct sockaddr_storage addr;
1662 	int r, newsock, oerrno, remote_port;
1663 	socklen_t addrlen;
1664 	char buf[16384], *remote_ipaddr;
1665 
1666 	if (!FD_ISSET(c->sock, readset))
1667 		return;
1668 
1669 	debug("X11 connection requested.");
1670 	addrlen = sizeof(addr);
1671 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1672 	if (c->single_connection) {
1673 		oerrno = errno;
1674 		debug2("single_connection: closing X11 listener.");
1675 		channel_close_fd(ssh, &c->sock);
1676 		chan_mark_dead(ssh, c);
1677 		errno = oerrno;
1678 	}
1679 	if (newsock == -1) {
1680 		if (errno != EINTR && errno != EWOULDBLOCK &&
1681 		    errno != ECONNABORTED)
1682 			error("accept: %.100s", strerror(errno));
1683 		if (errno == EMFILE || errno == ENFILE)
1684 			c->notbefore = monotime() + 1;
1685 		return;
1686 	}
1687 	set_nodelay(newsock);
1688 	remote_ipaddr = get_peer_ipaddr(newsock);
1689 	remote_port = get_peer_port(newsock);
1690 	snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1691 	    remote_ipaddr, remote_port);
1692 
1693 	nc = channel_new(ssh, "accepted x11 socket",
1694 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1695 	    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1696 	open_preamble(ssh, __func__, nc, "x11");
1697 	if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1698 	    (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1699 		fatal("%s: channel %i: reply %s", __func__,
1700 		    c->self, ssh_err(r));
1701 	}
1702 	if ((r = sshpkt_send(ssh)) != 0)
1703 		fatal("%s: channel %i: send %s", __func__, c->self, ssh_err(r));
1704 	free(remote_ipaddr);
1705 }
1706 
1707 static void
1708 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1709 {
1710 	char *local_ipaddr = get_local_ipaddr(c->sock);
1711 	int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1712 	char *remote_ipaddr = get_peer_ipaddr(c->sock);
1713 	int remote_port = get_peer_port(c->sock);
1714 	int r;
1715 
1716 	if (remote_port == -1) {
1717 		/* Fake addr/port to appease peers that validate it (Tectia) */
1718 		free(remote_ipaddr);
1719 		remote_ipaddr = xstrdup("127.0.0.1");
1720 		remote_port = 65535;
1721 	}
1722 
1723 	free(c->remote_name);
1724 	xasprintf(&c->remote_name,
1725 	    "%s: listening port %d for %.100s port %d, "
1726 	    "connect from %.200s port %d to %.100s port %d",
1727 	    rtype, c->listening_port, c->path, c->host_port,
1728 	    remote_ipaddr, remote_port, local_ipaddr, local_port);
1729 
1730 	open_preamble(ssh, __func__, c, rtype);
1731 	if (strcmp(rtype, "direct-tcpip") == 0) {
1732 		/* target host, port */
1733 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1734 		    (r = sshpkt_put_u32(ssh, c->host_port)) != 0) {
1735 			fatal("%s: channel %i: reply %s", __func__,
1736 			    c->self, ssh_err(r));
1737 		}
1738 	} else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1739 		/* target path */
1740 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0) {
1741 			fatal("%s: channel %i: reply %s", __func__,
1742 			    c->self, ssh_err(r));
1743 		}
1744 	} else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1745 		/* listen path */
1746 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0) {
1747 			fatal("%s: channel %i: reply %s", __func__,
1748 			    c->self, ssh_err(r));
1749 		}
1750 	} else {
1751 		/* listen address, port */
1752 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1753 		    (r = sshpkt_put_u32(ssh, local_port)) != 0) {
1754 			fatal("%s: channel %i: reply %s", __func__,
1755 			    c->self, ssh_err(r));
1756 		}
1757 	}
1758 	if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1759 		/* reserved for future owner/mode info */
1760 		if ((r = sshpkt_put_cstring(ssh, "")) != 0) {
1761 			fatal("%s: channel %i: reply %s", __func__,
1762 			    c->self, ssh_err(r));
1763 		}
1764 	} else {
1765 		/* originator host and port */
1766 		if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1767 		    (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0) {
1768 			fatal("%s: channel %i: reply %s", __func__,
1769 			    c->self, ssh_err(r));
1770 		}
1771 	}
1772 	if ((r = sshpkt_send(ssh)) != 0)
1773 		fatal("%s: channel %i: send %s", __func__, c->self, ssh_err(r));
1774 	free(remote_ipaddr);
1775 	free(local_ipaddr);
1776 }
1777 
1778 void
1779 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1780 {
1781 	ssh->chanctxt->x11_refuse_time = refuse_time;
1782 }
1783 
1784 /*
1785  * This socket is listening for connections to a forwarded TCP/IP port.
1786  */
1787 static void
1788 channel_post_port_listener(struct ssh *ssh, Channel *c,
1789     fd_set *readset, fd_set *writeset)
1790 {
1791 	Channel *nc;
1792 	struct sockaddr_storage addr;
1793 	int newsock, nextstate;
1794 	socklen_t addrlen;
1795 	char *rtype;
1796 
1797 	if (!FD_ISSET(c->sock, readset))
1798 		return;
1799 
1800 	debug("Connection to port %d forwarding to %.100s port %d requested.",
1801 	    c->listening_port, c->path, c->host_port);
1802 
1803 	if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1804 		nextstate = SSH_CHANNEL_OPENING;
1805 		rtype = "forwarded-tcpip";
1806 	} else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1807 		nextstate = SSH_CHANNEL_OPENING;
1808 		rtype = "forwarded-streamlocal@openssh.com";
1809 	} else if (c->host_port == PORT_STREAMLOCAL) {
1810 		nextstate = SSH_CHANNEL_OPENING;
1811 		rtype = "direct-streamlocal@openssh.com";
1812 	} else if (c->host_port == 0) {
1813 		nextstate = SSH_CHANNEL_DYNAMIC;
1814 		rtype = "dynamic-tcpip";
1815 	} else {
1816 		nextstate = SSH_CHANNEL_OPENING;
1817 		rtype = "direct-tcpip";
1818 	}
1819 
1820 	addrlen = sizeof(addr);
1821 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1822 	if (newsock == -1) {
1823 		if (errno != EINTR && errno != EWOULDBLOCK &&
1824 		    errno != ECONNABORTED)
1825 			error("accept: %.100s", strerror(errno));
1826 		if (errno == EMFILE || errno == ENFILE)
1827 			c->notbefore = monotime() + 1;
1828 		return;
1829 	}
1830 	if (c->host_port != PORT_STREAMLOCAL)
1831 		set_nodelay(newsock);
1832 	nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1833 	    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1834 	nc->listening_port = c->listening_port;
1835 	nc->host_port = c->host_port;
1836 	if (c->path != NULL)
1837 		nc->path = xstrdup(c->path);
1838 
1839 	if (nextstate != SSH_CHANNEL_DYNAMIC)
1840 		port_open_helper(ssh, nc, rtype);
1841 }
1842 
1843 /*
1844  * This is the authentication agent socket listening for connections from
1845  * clients.
1846  */
1847 static void
1848 channel_post_auth_listener(struct ssh *ssh, Channel *c,
1849     fd_set *readset, fd_set *writeset)
1850 {
1851 	Channel *nc;
1852 	int r, newsock;
1853 	struct sockaddr_storage addr;
1854 	socklen_t addrlen;
1855 
1856 	if (!FD_ISSET(c->sock, readset))
1857 		return;
1858 
1859 	addrlen = sizeof(addr);
1860 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1861 	if (newsock == -1) {
1862 		error("accept from auth socket: %.100s", strerror(errno));
1863 		if (errno == EMFILE || errno == ENFILE)
1864 			c->notbefore = monotime() + 1;
1865 		return;
1866 	}
1867 	nc = channel_new(ssh, "accepted auth socket",
1868 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1869 	    c->local_window_max, c->local_maxpacket,
1870 	    0, "accepted auth socket", 1);
1871 	open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1872 	if ((r = sshpkt_send(ssh)) != 0)
1873 		fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
1874 }
1875 
1876 static void
1877 channel_post_connecting(struct ssh *ssh, Channel *c,
1878     fd_set *readset, fd_set *writeset)
1879 {
1880 	int err = 0, sock, isopen, r;
1881 	socklen_t sz = sizeof(err);
1882 
1883 	if (!FD_ISSET(c->sock, writeset))
1884 		return;
1885 	if (!c->have_remote_id)
1886 		fatal(":%s: channel %d: no remote id", __func__, c->self);
1887 	/* for rdynamic the OPEN_CONFIRMATION has been sent already */
1888 	isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1889 	if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1890 		err = errno;
1891 		error("getsockopt SO_ERROR failed");
1892 	}
1893 	if (err == 0) {
1894 		debug("channel %d: connected to %s port %d",
1895 		    c->self, c->connect_ctx.host, c->connect_ctx.port);
1896 		channel_connect_ctx_free(&c->connect_ctx);
1897 		c->type = SSH_CHANNEL_OPEN;
1898 		if (isopen) {
1899 			/* no message necessary */
1900 		} else {
1901 			if ((r = sshpkt_start(ssh,
1902 			    SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1903 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1904 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1905 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1906 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket))
1907 			    != 0)
1908 				fatal("%s: channel %i: confirm: %s", __func__,
1909 				    c->self, ssh_err(r));
1910 			if ((r = sshpkt_send(ssh)) != 0)
1911 				fatal("%s: channel %i: %s", __func__, c->self,
1912 				    ssh_err(r));
1913 		}
1914 	} else {
1915 		debug("channel %d: connection failed: %s",
1916 		    c->self, strerror(err));
1917 		/* Try next address, if any */
1918 		if ((sock = connect_next(&c->connect_ctx)) > 0) {
1919 			close(c->sock);
1920 			c->sock = c->rfd = c->wfd = sock;
1921 			channel_find_maxfd(ssh->chanctxt);
1922 			return;
1923 		}
1924 		/* Exhausted all addresses */
1925 		error("connect_to %.100s port %d: failed.",
1926 		    c->connect_ctx.host, c->connect_ctx.port);
1927 		channel_connect_ctx_free(&c->connect_ctx);
1928 		if (isopen) {
1929 			rdynamic_close(ssh, c);
1930 		} else {
1931 			if ((r = sshpkt_start(ssh,
1932 			    SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1933 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1934 			    (r = sshpkt_put_u32(ssh,
1935 			    SSH2_OPEN_CONNECT_FAILED)) != 0 ||
1936 			    (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
1937 			    (r = sshpkt_put_cstring(ssh, "")) != 0) {
1938 				fatal("%s: channel %i: failure: %s", __func__,
1939 				    c->self, ssh_err(r));
1940 			}
1941 			if ((r = sshpkt_send(ssh)) != 0)
1942 				fatal("%s: channel %i: %s", __func__, c->self,
1943 				    ssh_err(r));
1944 			chan_mark_dead(ssh, c);
1945 		}
1946 	}
1947 }
1948 
1949 static int
1950 channel_handle_rfd(struct ssh *ssh, Channel *c,
1951     fd_set *readset, fd_set *writeset)
1952 {
1953 	char buf[CHAN_RBUF];
1954 	ssize_t len;
1955 	int r, force;
1956 
1957 	force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1958 
1959 	if (c->rfd == -1 || (!force && !FD_ISSET(c->rfd, readset)))
1960 		return 1;
1961 
1962 	errno = 0;
1963 	len = read(c->rfd, buf, sizeof(buf));
1964 	if (len == -1 && (errno == EINTR ||
1965 	    ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1966 		return 1;
1967 #ifndef PTY_ZEROREAD
1968  	if (len <= 0) {
1969 #else
1970 	if ((!c->isatty && len <= 0) ||
1971 	    (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1972 #endif
1973 		debug2("channel %d: read<=0 rfd %d len %zd",
1974 		    c->self, c->rfd, len);
1975 		if (c->type != SSH_CHANNEL_OPEN) {
1976 			debug2("channel %d: not open", c->self);
1977 			chan_mark_dead(ssh, c);
1978 			return -1;
1979 		} else {
1980 			chan_read_failed(ssh, c);
1981 		}
1982 		return -1;
1983 	}
1984 	if (c->input_filter != NULL) {
1985 		if (c->input_filter(ssh, c, buf, len) == -1) {
1986 			debug2("channel %d: filter stops", c->self);
1987 			chan_read_failed(ssh, c);
1988 		}
1989 	} else if (c->datagram) {
1990 		if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
1991 			fatal("%s: channel %d: put datagram: %s", __func__,
1992 			    c->self, ssh_err(r));
1993 	} else if ((r = sshbuf_put(c->input, buf, len)) != 0) {
1994 		fatal("%s: channel %d: put data: %s", __func__,
1995 		    c->self, ssh_err(r));
1996 	}
1997 	return 1;
1998 }
1999 
2000 static int
2001 channel_handle_wfd(struct ssh *ssh, Channel *c,
2002    fd_set *readset, fd_set *writeset)
2003 {
2004 	struct termios tio;
2005 	u_char *data = NULL, *buf; /* XXX const; need filter API change */
2006 	size_t dlen, olen = 0;
2007 	int r, len;
2008 
2009 	if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
2010 	    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("%s: channel %d: get datagram: %s", __func__,
2027 			    c->self, ssh_err(r));
2028 		buf = data;
2029 	} else {
2030 		buf = data = sshbuf_mutable_ptr(c->output);
2031 		dlen = sshbuf_len(c->output);
2032 	}
2033 
2034 	if (c->datagram) {
2035 		/* ignore truncated writes, datagrams might get lost */
2036 		len = write(c->wfd, buf, dlen);
2037 		free(data);
2038 		if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2039 		    errno == EWOULDBLOCK))
2040 			return 1;
2041 		if (len <= 0)
2042 			goto write_fail;
2043 		goto out;
2044 	}
2045 
2046 #ifdef _AIX
2047 	/* XXX: Later AIX versions can't push as much data to tty */
2048 	if (c->wfd_isatty)
2049 		dlen = MIN(dlen, 8*1024);
2050 #endif
2051 
2052 	len = write(c->wfd, buf, dlen);
2053 	if (len == -1 &&
2054 	    (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2055 		return 1;
2056 	if (len <= 0) {
2057  write_fail:
2058 		if (c->type != SSH_CHANNEL_OPEN) {
2059 			debug2("channel %d: not open", c->self);
2060 			chan_mark_dead(ssh, c);
2061 			return -1;
2062 		} else {
2063 			chan_write_failed(ssh, c);
2064 		}
2065 		return -1;
2066 	}
2067 #ifndef BROKEN_TCGETATTR_ICANON
2068 	if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2069 		if (tcgetattr(c->wfd, &tio) == 0 &&
2070 		    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2071 			/*
2072 			 * Simulate echo to reduce the impact of
2073 			 * traffic analysis. We need to match the
2074 			 * size of a SSH2_MSG_CHANNEL_DATA message
2075 			 * (4 byte channel id + buf)
2076 			 */
2077 			if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2078 			    (r = sshpkt_send(ssh)) != 0)
2079 				fatal("%s: channel %d: ignore: %s",
2080 				    __func__, c->self, ssh_err(r));
2081 		}
2082 	}
2083 #endif /* BROKEN_TCGETATTR_ICANON */
2084 	if ((r = sshbuf_consume(c->output, len)) != 0) {
2085 		fatal("%s: channel %d: consume: %s",
2086 		    __func__, c->self, ssh_err(r));
2087 	}
2088  out:
2089 	c->local_consumed += olen - sshbuf_len(c->output);
2090 
2091 	return 1;
2092 }
2093 
2094 static int
2095 channel_handle_efd_write(struct ssh *ssh, Channel *c,
2096     fd_set *readset, fd_set *writeset)
2097 {
2098 	int r;
2099 	ssize_t len;
2100 
2101 	if (!FD_ISSET(c->efd, writeset) || sshbuf_len(c->extended) == 0)
2102 		return 1;
2103 
2104 	len = write(c->efd, sshbuf_ptr(c->extended),
2105 	    sshbuf_len(c->extended));
2106 	debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2107 	if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2108 	    errno == EWOULDBLOCK))
2109 		return 1;
2110 	if (len <= 0) {
2111 		debug2("channel %d: closing write-efd %d", c->self, c->efd);
2112 		channel_close_fd(ssh, &c->efd);
2113 	} else {
2114 		if ((r = sshbuf_consume(c->extended, len)) != 0) {
2115 			fatal("%s: channel %d: consume: %s",
2116 			    __func__, c->self, ssh_err(r));
2117 		}
2118 		c->local_consumed += len;
2119 	}
2120 	return 1;
2121 }
2122 
2123 static int
2124 channel_handle_efd_read(struct ssh *ssh, Channel *c,
2125     fd_set *readset, fd_set *writeset)
2126 {
2127 	char buf[CHAN_RBUF];
2128 	ssize_t len;
2129 	int r, force;
2130 
2131 	force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2132 
2133 	if (c->efd == -1 || (!force && !FD_ISSET(c->efd, readset)))
2134 		return 1;
2135 
2136 	len = read(c->efd, buf, sizeof(buf));
2137 	debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2138 	if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
2139 	    errno == EWOULDBLOCK) && !force)))
2140 		return 1;
2141 	if (len <= 0) {
2142 		debug2("channel %d: closing read-efd %d",
2143 		    c->self, c->efd);
2144 		channel_close_fd(ssh, &c->efd);
2145 	} else {
2146 		if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
2147 			debug3("channel %d: discard efd",
2148 			    c->self);
2149 		} else if ((r = sshbuf_put(c->extended, buf, len)) != 0) {
2150 			fatal("%s: channel %d: append: %s",
2151 			    __func__, c->self, ssh_err(r));
2152 		}
2153 	}
2154 	return 1;
2155 }
2156 
2157 static int
2158 channel_handle_efd(struct ssh *ssh, Channel *c,
2159     fd_set *readset, fd_set *writeset)
2160 {
2161 	if (c->efd == -1)
2162 		return 1;
2163 
2164 	/** XXX handle drain efd, too */
2165 
2166 	if (c->extended_usage == CHAN_EXTENDED_WRITE)
2167 		return channel_handle_efd_write(ssh, c, readset, writeset);
2168 	else if (c->extended_usage == CHAN_EXTENDED_READ ||
2169 	    c->extended_usage == CHAN_EXTENDED_IGNORE)
2170 		return channel_handle_efd_read(ssh, c, readset, writeset);
2171 
2172 	return 1;
2173 }
2174 
2175 static int
2176 channel_check_window(struct ssh *ssh, Channel *c)
2177 {
2178 	int r;
2179 
2180 	if (c->type == SSH_CHANNEL_OPEN &&
2181 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2182 	    ((c->local_window_max - c->local_window >
2183 	    c->local_maxpacket*3) ||
2184 	    c->local_window < c->local_window_max/2) &&
2185 	    c->local_consumed > 0) {
2186 		if (!c->have_remote_id)
2187 			fatal(":%s: channel %d: no remote id",
2188 			    __func__, c->self);
2189 		if ((r = sshpkt_start(ssh,
2190 		    SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2191 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2192 		    (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2193 		    (r = sshpkt_send(ssh)) != 0) {
2194 			fatal("%s: channel %i: %s", __func__,
2195 			    c->self, ssh_err(r));
2196 		}
2197 		debug2("channel %d: window %d sent adjust %d",
2198 		    c->self, c->local_window,
2199 		    c->local_consumed);
2200 		c->local_window += c->local_consumed;
2201 		c->local_consumed = 0;
2202 	}
2203 	return 1;
2204 }
2205 
2206 static void
2207 channel_post_open(struct ssh *ssh, Channel *c,
2208     fd_set *readset, fd_set *writeset)
2209 {
2210 	channel_handle_rfd(ssh, c, readset, writeset);
2211 	channel_handle_wfd(ssh, c, readset, writeset);
2212 	channel_handle_efd(ssh, c, readset, writeset);
2213 	channel_check_window(ssh, c);
2214 }
2215 
2216 static u_int
2217 read_mux(struct ssh *ssh, Channel *c, u_int need)
2218 {
2219 	char buf[CHAN_RBUF];
2220 	ssize_t len;
2221 	u_int rlen;
2222 	int r;
2223 
2224 	if (sshbuf_len(c->input) < need) {
2225 		rlen = need - sshbuf_len(c->input);
2226 		len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2227 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
2228 			return sshbuf_len(c->input);
2229 		if (len <= 0) {
2230 			debug2("channel %d: ctl read<=0 rfd %d len %zd",
2231 			    c->self, c->rfd, len);
2232 			chan_read_failed(ssh, c);
2233 			return 0;
2234 		} else if ((r = sshbuf_put(c->input, buf, len)) != 0) {
2235 			fatal("%s: channel %d: append: %s",
2236 			    __func__, c->self, ssh_err(r));
2237 		}
2238 	}
2239 	return sshbuf_len(c->input);
2240 }
2241 
2242 static void
2243 channel_post_mux_client_read(struct ssh *ssh, Channel *c,
2244     fd_set *readset, fd_set *writeset)
2245 {
2246 	u_int need;
2247 
2248 	if (c->rfd == -1 || !FD_ISSET(c->rfd, readset))
2249 		return;
2250 	if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2251 		return;
2252 	if (c->mux_pause)
2253 		return;
2254 
2255 	/*
2256 	 * Don't not read past the precise end of packets to
2257 	 * avoid disrupting fd passing.
2258 	 */
2259 	if (read_mux(ssh, c, 4) < 4) /* read header */
2260 		return;
2261 	/* XXX sshbuf_peek_u32 */
2262 	need = PEEK_U32(sshbuf_ptr(c->input));
2263 #define CHANNEL_MUX_MAX_PACKET	(256 * 1024)
2264 	if (need > CHANNEL_MUX_MAX_PACKET) {
2265 		debug2("channel %d: packet too big %u > %u",
2266 		    c->self, CHANNEL_MUX_MAX_PACKET, need);
2267 		chan_rcvd_oclose(ssh, c);
2268 		return;
2269 	}
2270 	if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2271 		return;
2272 	if (c->mux_rcb(ssh, c) != 0) {
2273 		debug("channel %d: mux_rcb failed", c->self);
2274 		chan_mark_dead(ssh, c);
2275 		return;
2276 	}
2277 }
2278 
2279 static void
2280 channel_post_mux_client_write(struct ssh *ssh, Channel *c,
2281     fd_set *readset, fd_set *writeset)
2282 {
2283 	ssize_t len;
2284 	int r;
2285 
2286 	if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
2287 	    sshbuf_len(c->output) == 0)
2288 		return;
2289 
2290 	len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2291 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2292 		return;
2293 	if (len <= 0) {
2294 		chan_mark_dead(ssh, c);
2295 		return;
2296 	}
2297 	if ((r = sshbuf_consume(c->output, len)) != 0)
2298 		fatal("%s: channel %d: consume: %s", __func__,
2299 		    c->self, ssh_err(r));
2300 }
2301 
2302 static void
2303 channel_post_mux_client(struct ssh *ssh, Channel *c,
2304     fd_set *readset, fd_set *writeset)
2305 {
2306 	channel_post_mux_client_read(ssh, c, readset, writeset);
2307 	channel_post_mux_client_write(ssh, c, readset, writeset);
2308 }
2309 
2310 static void
2311 channel_post_mux_listener(struct ssh *ssh, Channel *c,
2312     fd_set *readset, fd_set *writeset)
2313 {
2314 	Channel *nc;
2315 	struct sockaddr_storage addr;
2316 	socklen_t addrlen;
2317 	int newsock;
2318 	uid_t euid;
2319 	gid_t egid;
2320 
2321 	if (!FD_ISSET(c->sock, readset))
2322 		return;
2323 
2324 	debug("multiplexing control connection");
2325 
2326 	/*
2327 	 * Accept connection on control socket
2328 	 */
2329 	memset(&addr, 0, sizeof(addr));
2330 	addrlen = sizeof(addr);
2331 	if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2332 	    &addrlen)) == -1) {
2333 		error("%s accept: %s", __func__, strerror(errno));
2334 		if (errno == EMFILE || errno == ENFILE)
2335 			c->notbefore = monotime() + 1;
2336 		return;
2337 	}
2338 
2339 	if (getpeereid(newsock, &euid, &egid) == -1) {
2340 		error("%s getpeereid failed: %s", __func__,
2341 		    strerror(errno));
2342 		close(newsock);
2343 		return;
2344 	}
2345 	if ((euid != 0) && (getuid() != euid)) {
2346 		error("multiplex uid mismatch: peer euid %u != uid %u",
2347 		    (u_int)euid, (u_int)getuid());
2348 		close(newsock);
2349 		return;
2350 	}
2351 	nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
2352 	    newsock, newsock, -1, c->local_window_max,
2353 	    c->local_maxpacket, 0, "mux-control", 1);
2354 	nc->mux_rcb = c->mux_rcb;
2355 	debug3("%s: new mux channel %d fd %d", __func__, nc->self, nc->sock);
2356 	/* establish state */
2357 	nc->mux_rcb(ssh, nc);
2358 	/* mux state transitions must not elicit protocol messages */
2359 	nc->flags |= CHAN_LOCAL;
2360 }
2361 
2362 static void
2363 channel_handler_init(struct ssh_channels *sc)
2364 {
2365 	chan_fn **pre, **post;
2366 
2367 	if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2368 	   (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2369 		fatal("%s: allocation failed", __func__);
2370 
2371 	pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
2372 	pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
2373 	pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
2374 	pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
2375 	pre[SSH_CHANNEL_UNIX_LISTENER] =	&channel_pre_listener;
2376 	pre[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_pre_listener;
2377 	pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
2378 	pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
2379 	pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
2380 	pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
2381 	pre[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_pre_connecting;
2382 	pre[SSH_CHANNEL_MUX_LISTENER] =		&channel_pre_listener;
2383 	pre[SSH_CHANNEL_MUX_CLIENT] =		&channel_pre_mux_client;
2384 
2385 	post[SSH_CHANNEL_OPEN] =		&channel_post_open;
2386 	post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
2387 	post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
2388 	post[SSH_CHANNEL_UNIX_LISTENER] =	&channel_post_port_listener;
2389 	post[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_post_port_listener;
2390 	post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
2391 	post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
2392 	post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
2393 	post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
2394 	post[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_post_connecting;
2395 	post[SSH_CHANNEL_MUX_LISTENER] =	&channel_post_mux_listener;
2396 	post[SSH_CHANNEL_MUX_CLIENT] =		&channel_post_mux_client;
2397 
2398 	sc->channel_pre = pre;
2399 	sc->channel_post = post;
2400 }
2401 
2402 /* gc dead channels */
2403 static void
2404 channel_garbage_collect(struct ssh *ssh, Channel *c)
2405 {
2406 	if (c == NULL)
2407 		return;
2408 	if (c->detach_user != NULL) {
2409 		if (!chan_is_dead(ssh, c, c->detach_close))
2410 			return;
2411 
2412 		debug2("channel %d: gc: notify user", c->self);
2413 		c->detach_user(ssh, c->self, NULL);
2414 		/* if we still have a callback */
2415 		if (c->detach_user != NULL)
2416 			return;
2417 		debug2("channel %d: gc: user detached", c->self);
2418 	}
2419 	if (!chan_is_dead(ssh, c, 1))
2420 		return;
2421 	debug2("channel %d: garbage collecting", c->self);
2422 	channel_free(ssh, c);
2423 }
2424 
2425 enum channel_table { CHAN_PRE, CHAN_POST };
2426 
2427 static void
2428 channel_handler(struct ssh *ssh, int table,
2429     fd_set *readset, fd_set *writeset, time_t *unpause_secs)
2430 {
2431 	struct ssh_channels *sc = ssh->chanctxt;
2432 	chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2433 	u_int i, oalloc;
2434 	Channel *c;
2435 	time_t now;
2436 
2437 	now = monotime();
2438 	if (unpause_secs != NULL)
2439 		*unpause_secs = 0;
2440 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2441 		c = sc->channels[i];
2442 		if (c == NULL)
2443 			continue;
2444 		if (c->delayed) {
2445 			if (table == CHAN_PRE)
2446 				c->delayed = 0;
2447 			else
2448 				continue;
2449 		}
2450 		if (ftab[c->type] != NULL) {
2451 			/*
2452 			 * Run handlers that are not paused.
2453 			 */
2454 			if (c->notbefore <= now)
2455 				(*ftab[c->type])(ssh, c, readset, writeset);
2456 			else if (unpause_secs != NULL) {
2457 				/*
2458 				 * Collect the time that the earliest
2459 				 * channel comes off pause.
2460 				 */
2461 				debug3("%s: chan %d: skip for %d more seconds",
2462 				    __func__, c->self,
2463 				    (int)(c->notbefore - now));
2464 				if (*unpause_secs == 0 ||
2465 				    (c->notbefore - now) < *unpause_secs)
2466 					*unpause_secs = c->notbefore - now;
2467 			}
2468 		}
2469 		channel_garbage_collect(ssh, c);
2470 	}
2471 	if (unpause_secs != NULL && *unpause_secs != 0)
2472 		debug3("%s: first channel unpauses in %d seconds",
2473 		    __func__, (int)*unpause_secs);
2474 }
2475 
2476 /*
2477  * Create sockets before allocating the select bitmasks.
2478  * This is necessary for things that need to happen after reading
2479  * the network-input but before channel_prepare_select().
2480  */
2481 static void
2482 channel_before_prepare_select(struct ssh *ssh)
2483 {
2484 	struct ssh_channels *sc = ssh->chanctxt;
2485 	Channel *c;
2486 	u_int i, oalloc;
2487 
2488 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2489 		c = sc->channels[i];
2490 		if (c == NULL)
2491 			continue;
2492 		if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2493 			channel_before_prepare_select_rdynamic(ssh, c);
2494 	}
2495 }
2496 
2497 /*
2498  * Allocate/update select bitmasks and add any bits relevant to channels in
2499  * select bitmasks.
2500  */
2501 void
2502 channel_prepare_select(struct ssh *ssh, fd_set **readsetp, fd_set **writesetp,
2503     int *maxfdp, u_int *nallocp, time_t *minwait_secs)
2504 {
2505 	u_int n, sz, nfdset;
2506 
2507 	channel_before_prepare_select(ssh); /* might update channel_max_fd */
2508 
2509 	n = MAXIMUM(*maxfdp, ssh->chanctxt->channel_max_fd);
2510 
2511 	nfdset = howmany(n+1, NFDBITS);
2512 	/* Explicitly test here, because xrealloc isn't always called */
2513 	if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2514 		fatal("channel_prepare_select: max_fd (%d) is too large", n);
2515 	sz = nfdset * sizeof(fd_mask);
2516 
2517 	/* perhaps check sz < nalloc/2 and shrink? */
2518 	if (*readsetp == NULL || sz > *nallocp) {
2519 		*readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2520 		*writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2521 		*nallocp = sz;
2522 	}
2523 	*maxfdp = n;
2524 	memset(*readsetp, 0, sz);
2525 	memset(*writesetp, 0, sz);
2526 
2527 	if (!ssh_packet_is_rekeying(ssh))
2528 		channel_handler(ssh, CHAN_PRE, *readsetp, *writesetp,
2529 		    minwait_secs);
2530 }
2531 
2532 /*
2533  * After select, perform any appropriate operations for channels which have
2534  * events pending.
2535  */
2536 void
2537 channel_after_select(struct ssh *ssh, fd_set *readset, fd_set *writeset)
2538 {
2539 	channel_handler(ssh, CHAN_POST, readset, writeset, NULL);
2540 }
2541 
2542 /*
2543  * Enqueue data for channels with open or draining c->input.
2544  */
2545 static void
2546 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2547 {
2548 	size_t len, plen;
2549 	const u_char *pkt;
2550 	int r;
2551 
2552 	if ((len = sshbuf_len(c->input)) == 0) {
2553 		if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2554 			/*
2555 			 * input-buffer is empty and read-socket shutdown:
2556 			 * tell peer, that we will not send more data:
2557 			 * send IEOF.
2558 			 * hack for extended data: delay EOF if EFD still
2559 			 * in use.
2560 			 */
2561 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
2562 				debug2("channel %d: "
2563 				    "ibuf_empty delayed efd %d/(%zu)",
2564 				    c->self, c->efd, sshbuf_len(c->extended));
2565 			else
2566 				chan_ibuf_empty(ssh, c);
2567 		}
2568 		return;
2569 	}
2570 
2571 	if (!c->have_remote_id)
2572 		fatal(":%s: channel %d: no remote id", __func__, c->self);
2573 
2574 	if (c->datagram) {
2575 		/* Check datagram will fit; drop if not */
2576 		if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2577 			fatal("%s: channel %d: get datagram: %s", __func__,
2578 			    c->self, ssh_err(r));
2579 		/*
2580 		 * XXX this does tail-drop on the datagram queue which is
2581 		 * usually suboptimal compared to head-drop. Better to have
2582 		 * backpressure at read time? (i.e. read + discard)
2583 		 */
2584 		if (plen > c->remote_window || plen > c->remote_maxpacket) {
2585 			debug("channel %d: datagram too big", c->self);
2586 			return;
2587 		}
2588 		/* Enqueue it */
2589 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2590 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2591 		    (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2592 		    (r = sshpkt_send(ssh)) != 0) {
2593 			fatal("%s: channel %i: datagram: %s", __func__,
2594 			    c->self, ssh_err(r));
2595 		}
2596 		c->remote_window -= plen;
2597 		return;
2598 	}
2599 
2600 	/* Enqueue packet for buffered data. */
2601 	if (len > c->remote_window)
2602 		len = c->remote_window;
2603 	if (len > c->remote_maxpacket)
2604 		len = c->remote_maxpacket;
2605 	if (len == 0)
2606 		return;
2607 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2608 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2609 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2610 	    (r = sshpkt_send(ssh)) != 0) {
2611 		fatal("%s: channel %i: data: %s", __func__,
2612 		    c->self, ssh_err(r));
2613 	}
2614 	if ((r = sshbuf_consume(c->input, len)) != 0)
2615 		fatal("%s: channel %i: consume: %s", __func__,
2616 		    c->self, ssh_err(r));
2617 	c->remote_window -= len;
2618 }
2619 
2620 /*
2621  * Enqueue data for channels with open c->extended in read mode.
2622  */
2623 static void
2624 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2625 {
2626 	size_t len;
2627 	int r;
2628 
2629 	if ((len = sshbuf_len(c->extended)) == 0)
2630 		return;
2631 
2632 	debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2633 	    c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2634 	if (len > c->remote_window)
2635 		len = c->remote_window;
2636 	if (len > c->remote_maxpacket)
2637 		len = c->remote_maxpacket;
2638 	if (len == 0)
2639 		return;
2640 	if (!c->have_remote_id)
2641 		fatal(":%s: channel %d: no remote id", __func__, c->self);
2642 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2643 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2644 	    (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2645 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2646 	    (r = sshpkt_send(ssh)) != 0) {
2647 		fatal("%s: channel %i: data: %s", __func__,
2648 		    c->self, ssh_err(r));
2649 	}
2650 	if ((r = sshbuf_consume(c->extended, len)) != 0)
2651 		fatal("%s: channel %i: consume: %s", __func__,
2652 		    c->self, ssh_err(r));
2653 	c->remote_window -= len;
2654 	debug2("channel %d: sent ext data %zu", c->self, len);
2655 }
2656 
2657 /* If there is data to send to the connection, enqueue some of it now. */
2658 void
2659 channel_output_poll(struct ssh *ssh)
2660 {
2661 	struct ssh_channels *sc = ssh->chanctxt;
2662 	Channel *c;
2663 	u_int i;
2664 
2665 	for (i = 0; i < sc->channels_alloc; i++) {
2666 		c = sc->channels[i];
2667 		if (c == NULL)
2668 			continue;
2669 
2670 		/*
2671 		 * We are only interested in channels that can have buffered
2672 		 * incoming data.
2673 		 */
2674 		if (c->type != SSH_CHANNEL_OPEN)
2675 			continue;
2676 		if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2677 			/* XXX is this true? */
2678 			debug3("channel %d: will not send data after close",
2679 			    c->self);
2680 			continue;
2681 		}
2682 
2683 		/* Get the amount of buffered data for this channel. */
2684 		if (c->istate == CHAN_INPUT_OPEN ||
2685 		    c->istate == CHAN_INPUT_WAIT_DRAIN)
2686 			channel_output_poll_input_open(ssh, c);
2687 		/* Send extended data, i.e. stderr */
2688 		if (!(c->flags & CHAN_EOF_SENT) &&
2689 		    c->extended_usage == CHAN_EXTENDED_READ)
2690 			channel_output_poll_extended_read(ssh, c);
2691 	}
2692 }
2693 
2694 /* -- mux proxy support  */
2695 
2696 /*
2697  * When multiplexing channel messages for mux clients we have to deal
2698  * with downstream messages from the mux client and upstream messages
2699  * from the ssh server:
2700  * 1) Handling downstream messages is straightforward and happens
2701  *    in channel_proxy_downstream():
2702  *    - We forward all messages (mostly) unmodified to the server.
2703  *    - However, in order to route messages from upstream to the correct
2704  *      downstream client, we have to replace the channel IDs used by the
2705  *      mux clients with a unique channel ID because the mux clients might
2706  *      use conflicting channel IDs.
2707  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2708  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2709  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2710  *      with the newly allocated channel ID.
2711  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2712  *    channels and processed by channel_proxy_upstream(). The local channel ID
2713  *    is then translated back to the original mux client ID.
2714  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2715  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2716  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2717  *    downstream mux client are removed.
2718  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2719  *    requires more work, because they are not addressed to a specific
2720  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
2721  *    out whether the request is addressed to the local client or a
2722  *    specific downstream client based on the listen-address/port.
2723  * 6) Agent and X11-Forwarding have a similar problem and are currently
2724  *    not supported as the matching session/channel cannot be identified
2725  *    easily.
2726  */
2727 
2728 /*
2729  * receive packets from downstream mux clients:
2730  * channel callback fired on read from mux client, creates
2731  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2732  * on channel creation.
2733  */
2734 int
2735 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2736 {
2737 	Channel *c = NULL;
2738 	struct sshbuf *original = NULL, *modified = NULL;
2739 	const u_char *cp;
2740 	char *ctype = NULL, *listen_host = NULL;
2741 	u_char type;
2742 	size_t have;
2743 	int ret = -1, r;
2744 	u_int id, remote_id, listen_port;
2745 
2746 	/* sshbuf_dump(downstream->input, stderr); */
2747 	if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2748 	    != 0) {
2749 		error("%s: malformed message: %s", __func__, ssh_err(r));
2750 		return -1;
2751 	}
2752 	if (have < 2) {
2753 		error("%s: short message", __func__);
2754 		return -1;
2755 	}
2756 	type = cp[1];
2757 	/* skip padlen + type */
2758 	cp += 2;
2759 	have -= 2;
2760 	if (ssh_packet_log_type(type))
2761 		debug3("%s: channel %u: down->up: type %u", __func__,
2762 		    downstream->self, type);
2763 
2764 	switch (type) {
2765 	case SSH2_MSG_CHANNEL_OPEN:
2766 		if ((original = sshbuf_from(cp, have)) == NULL ||
2767 		    (modified = sshbuf_new()) == NULL) {
2768 			error("%s: alloc", __func__);
2769 			goto out;
2770 		}
2771 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2772 		    (r = sshbuf_get_u32(original, &id)) != 0) {
2773 			error("%s: parse error %s", __func__, ssh_err(r));
2774 			goto out;
2775 		}
2776 		c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2777 		   -1, -1, -1, 0, 0, 0, ctype, 1);
2778 		c->mux_ctx = downstream;	/* point to mux client */
2779 		c->mux_downstream_id = id;	/* original downstream id */
2780 		if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2781 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2782 		    (r = sshbuf_putb(modified, original)) != 0) {
2783 			error("%s: compose error %s", __func__, ssh_err(r));
2784 			channel_free(ssh, c);
2785 			goto out;
2786 		}
2787 		break;
2788 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2789 		/*
2790 		 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2791 		 * need to parse 'remote_id' instead of 'ctype'.
2792 		 */
2793 		if ((original = sshbuf_from(cp, have)) == NULL ||
2794 		    (modified = sshbuf_new()) == NULL) {
2795 			error("%s: alloc", __func__);
2796 			goto out;
2797 		}
2798 		if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2799 		    (r = sshbuf_get_u32(original, &id)) != 0) {
2800 			error("%s: parse error %s", __func__, ssh_err(r));
2801 			goto out;
2802 		}
2803 		c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2804 		   -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
2805 		c->mux_ctx = downstream;	/* point to mux client */
2806 		c->mux_downstream_id = id;
2807 		c->remote_id = remote_id;
2808 		c->have_remote_id = 1;
2809 		if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
2810 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2811 		    (r = sshbuf_putb(modified, original)) != 0) {
2812 			error("%s: compose error %s", __func__, ssh_err(r));
2813 			channel_free(ssh, c);
2814 			goto out;
2815 		}
2816 		break;
2817 	case SSH2_MSG_GLOBAL_REQUEST:
2818 		if ((original = sshbuf_from(cp, have)) == NULL) {
2819 			error("%s: alloc", __func__);
2820 			goto out;
2821 		}
2822 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
2823 			error("%s: parse error %s", __func__, ssh_err(r));
2824 			goto out;
2825 		}
2826 		if (strcmp(ctype, "tcpip-forward") != 0) {
2827 			error("%s: unsupported request %s", __func__, ctype);
2828 			goto out;
2829 		}
2830 		if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
2831 		    (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
2832 		    (r = sshbuf_get_u32(original, &listen_port)) != 0) {
2833 			error("%s: parse error %s", __func__, ssh_err(r));
2834 			goto out;
2835 		}
2836 		if (listen_port > 65535) {
2837 			error("%s: tcpip-forward for %s: bad port %u",
2838 			    __func__, listen_host, listen_port);
2839 			goto out;
2840 		}
2841 		/* Record that connection to this host/port is permitted. */
2842 		<