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