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