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