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