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