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