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