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