xref: /openbsd-src/usr.bin/ssh/channels.c (revision ff0e7be1ebbcc809ea8ad2b6dafe215824da9e46)
1 /* $OpenBSD: channels.c,v 1.431 2023/06/05 13:24:36 millert 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 <sys/types.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/un.h>
46 #include <sys/socket.h>
47 #include <sys/time.h>
48 #include <sys/queue.h>
49 
50 #include <netinet/in.h>
51 #include <arpa/inet.h>
52 
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <limits.h>
56 #include <netdb.h>
57 #include <poll.h>
58 #include <stdarg.h>
59 #include <stdint.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <termios.h>
64 #include <unistd.h>
65 
66 #include "xmalloc.h"
67 #include "ssh.h"
68 #include "ssh2.h"
69 #include "ssherr.h"
70 #include "sshbuf.h"
71 #include "packet.h"
72 #include "log.h"
73 #include "misc.h"
74 #include "channels.h"
75 #include "compat.h"
76 #include "canohost.h"
77 #include "sshkey.h"
78 #include "authfd.h"
79 #include "pathnames.h"
80 #include "match.h"
81 
82 /* XXX remove once we're satisfied there's no lurking bugs */
83 /* #define DEBUG_CHANNEL_POLL 1 */
84 
85 /* -- agent forwarding */
86 #define	NUM_SOCKS	10
87 
88 /* -- tcp forwarding */
89 /* special-case port number meaning allow any port */
90 #define FWD_PERMIT_ANY_PORT	0
91 
92 /* special-case wildcard meaning allow any host */
93 #define FWD_PERMIT_ANY_HOST	"*"
94 
95 /* -- X11 forwarding */
96 /* Maximum number of fake X11 displays to try. */
97 #define MAX_DISPLAYS  1000
98 
99 /* Per-channel callback for pre/post IO actions */
100 typedef void chan_fn(struct ssh *, Channel *c);
101 
102 /*
103  * Data structure for storing which hosts are permitted for forward requests.
104  * The local sides of any remote forwards are stored in this array to prevent
105  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
106  * network (which might be behind a firewall).
107  */
108 /* XXX: streamlocal wants a path instead of host:port */
109 /*      Overload host_to_connect; we could just make this match Forward */
110 /*	XXX - can we use listen_host instead of listen_path? */
111 struct permission {
112 	char *host_to_connect;		/* Connect to 'host'. */
113 	int port_to_connect;		/* Connect to 'port'. */
114 	char *listen_host;		/* Remote side should listen address. */
115 	char *listen_path;		/* Remote side should listen path. */
116 	int listen_port;		/* Remote side should listen port. */
117 	Channel *downstream;		/* Downstream mux*/
118 };
119 
120 /*
121  * Stores the forwarding permission state for a single direction (local or
122  * remote).
123  */
124 struct permission_set {
125 	/*
126 	 * List of all local permitted host/port pairs to allow for the
127 	 * user.
128 	 */
129 	u_int num_permitted_user;
130 	struct permission *permitted_user;
131 
132 	/*
133 	 * List of all permitted host/port pairs to allow for the admin.
134 	 */
135 	u_int num_permitted_admin;
136 	struct permission *permitted_admin;
137 
138 	/*
139 	 * If this is true, all opens/listens are permitted.  This is the
140 	 * case on the server on which we have to trust the client anyway,
141 	 * and the user could do anything after logging in.
142 	 */
143 	int all_permitted;
144 };
145 
146 /* Used to record timeouts per channel type */
147 struct ssh_channel_timeout {
148 	char *type_pattern;
149 	int timeout_secs;
150 };
151 
152 /* Master structure for channels state */
153 struct ssh_channels {
154 	/*
155 	 * Pointer to an array containing all allocated channels.  The array
156 	 * is dynamically extended as needed.
157 	 */
158 	Channel **channels;
159 
160 	/*
161 	 * Size of the channel array.  All slots of the array must always be
162 	 * initialized (at least the type field); unused slots set to NULL
163 	 */
164 	u_int channels_alloc;
165 
166 	/*
167 	 * 'channel_pre*' are called just before IO to add any bits
168 	 * relevant to channels in the c->io_want bitmasks.
169 	 *
170 	 * 'channel_post*': perform any appropriate operations for
171 	 * channels which have c->io_ready events pending.
172 	 */
173 	chan_fn **channel_pre;
174 	chan_fn **channel_post;
175 
176 	/* -- tcp forwarding */
177 	struct permission_set local_perms;
178 	struct permission_set remote_perms;
179 
180 	/* -- X11 forwarding */
181 
182 	/* Saved X11 local (client) display. */
183 	char *x11_saved_display;
184 
185 	/* Saved X11 authentication protocol name. */
186 	char *x11_saved_proto;
187 
188 	/* Saved X11 authentication data.  This is the real data. */
189 	char *x11_saved_data;
190 	u_int x11_saved_data_len;
191 
192 	/* Deadline after which all X11 connections are refused */
193 	time_t x11_refuse_time;
194 
195 	/*
196 	 * Fake X11 authentication data.  This is what the server will be
197 	 * sending us; we should replace any occurrences of this by the
198 	 * real data.
199 	 */
200 	u_char *x11_fake_data;
201 	u_int x11_fake_data_len;
202 
203 	/* AF_UNSPEC or AF_INET or AF_INET6 */
204 	int IPv4or6;
205 
206 	/* Channel timeouts by type */
207 	struct ssh_channel_timeout *timeouts;
208 	size_t ntimeouts;
209 };
210 
211 /* helper */
212 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
213 static const char *channel_rfwd_bind_host(const char *listen_host);
214 
215 /* non-blocking connect helpers */
216 static int connect_next(struct channel_connect *);
217 static void channel_connect_ctx_free(struct channel_connect *);
218 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
219 static int rdynamic_connect_finish(struct ssh *, Channel *);
220 
221 /* Setup helper */
222 static void channel_handler_init(struct ssh_channels *sc);
223 
224 /* -- channel core */
225 
226 void
227 channel_init_channels(struct ssh *ssh)
228 {
229 	struct ssh_channels *sc;
230 
231 	if ((sc = calloc(1, sizeof(*sc))) == NULL)
232 		fatal_f("allocation failed");
233 	sc->channels_alloc = 10;
234 	sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
235 	sc->IPv4or6 = AF_UNSPEC;
236 	channel_handler_init(sc);
237 
238 	ssh->chanctxt = sc;
239 }
240 
241 Channel *
242 channel_by_id(struct ssh *ssh, int id)
243 {
244 	Channel *c;
245 
246 	if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
247 		logit_f("%d: bad id", id);
248 		return NULL;
249 	}
250 	c = ssh->chanctxt->channels[id];
251 	if (c == NULL) {
252 		logit_f("%d: bad id: channel free", id);
253 		return NULL;
254 	}
255 	return c;
256 }
257 
258 Channel *
259 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
260 {
261 	Channel *c;
262 	u_int i;
263 
264 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
265 		c = ssh->chanctxt->channels[i];
266 		if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
267 			return c;
268 	}
269 	return NULL;
270 }
271 
272 /*
273  * Returns the channel if it is allowed to receive protocol messages.
274  * Private channels, like listening sockets, may not receive messages.
275  */
276 Channel *
277 channel_lookup(struct ssh *ssh, int id)
278 {
279 	Channel *c;
280 
281 	if ((c = channel_by_id(ssh, id)) == NULL)
282 		return NULL;
283 
284 	switch (c->type) {
285 	case SSH_CHANNEL_X11_OPEN:
286 	case SSH_CHANNEL_LARVAL:
287 	case SSH_CHANNEL_CONNECTING:
288 	case SSH_CHANNEL_DYNAMIC:
289 	case SSH_CHANNEL_RDYNAMIC_OPEN:
290 	case SSH_CHANNEL_RDYNAMIC_FINISH:
291 	case SSH_CHANNEL_OPENING:
292 	case SSH_CHANNEL_OPEN:
293 	case SSH_CHANNEL_ABANDONED:
294 	case SSH_CHANNEL_MUX_PROXY:
295 		return c;
296 	}
297 	logit("Non-public channel %d, type %d.", id, c->type);
298 	return NULL;
299 }
300 
301 /*
302  * Add a timeout for open channels whose c->ctype (or c->xctype if it is set)
303  * match type_pattern.
304  */
305 void
306 channel_add_timeout(struct ssh *ssh, const char *type_pattern,
307     int timeout_secs)
308 {
309 	struct ssh_channels *sc = ssh->chanctxt;
310 
311 	debug2_f("channel type \"%s\" timeout %d seconds",
312 	    type_pattern, timeout_secs);
313 	sc->timeouts = xrecallocarray(sc->timeouts, sc->ntimeouts,
314 	    sc->ntimeouts + 1, sizeof(*sc->timeouts));
315 	sc->timeouts[sc->ntimeouts].type_pattern = xstrdup(type_pattern);
316 	sc->timeouts[sc->ntimeouts].timeout_secs = timeout_secs;
317 	sc->ntimeouts++;
318 }
319 
320 /* Clears all previously-added channel timeouts */
321 void
322 channel_clear_timeouts(struct ssh *ssh)
323 {
324 	struct ssh_channels *sc = ssh->chanctxt;
325 	size_t i;
326 
327 	debug3_f("clearing");
328 	for (i = 0; i < sc->ntimeouts; i++)
329 		free(sc->timeouts[i].type_pattern);
330 	free(sc->timeouts);
331 	sc->timeouts = NULL;
332 	sc->ntimeouts = 0;
333 }
334 
335 static int
336 lookup_timeout(struct ssh *ssh, const char *type)
337 {
338 	struct ssh_channels *sc = ssh->chanctxt;
339 	size_t i;
340 
341 	for (i = 0; i < sc->ntimeouts; i++) {
342 		if (match_pattern(type, sc->timeouts[i].type_pattern))
343 			return sc->timeouts[i].timeout_secs;
344 	}
345 
346 	return 0;
347 }
348 
349 /*
350  * Sets "extended type" of a channel; used by session layer to add additional
351  * information about channel types (e.g. shell, login, subsystem) that can then
352  * be used to select timeouts.
353  * Will reset c->inactive_deadline as a side-effect.
354  */
355 void
356 channel_set_xtype(struct ssh *ssh, int id, const char *xctype)
357 {
358 	Channel *c;
359 
360 	if ((c = channel_by_id(ssh, id)) == NULL)
361 		fatal_f("missing channel %d", id);
362 	if (c->xctype != NULL)
363 		free(c->xctype);
364 	c->xctype = xstrdup(xctype);
365 	/* Type has changed, so look up inactivity deadline again */
366 	c->inactive_deadline = lookup_timeout(ssh, c->xctype);
367 	debug2_f("labeled channel %d as %s (inactive timeout %u)", id, xctype,
368 	    c->inactive_deadline);
369 }
370 
371 /*
372  * Register filedescriptors for a channel, used when allocating a channel or
373  * when the channel consumer/producer is ready, e.g. shell exec'd
374  */
375 static void
376 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
377     int extusage, int nonblock, int is_tty)
378 {
379 	int val;
380 
381 	if (rfd != -1)
382 		(void)fcntl(rfd, F_SETFD, FD_CLOEXEC);
383 	if (wfd != -1 && wfd != rfd)
384 		(void)fcntl(wfd, F_SETFD, FD_CLOEXEC);
385 	if (efd != -1 && efd != rfd && efd != wfd)
386 		(void)fcntl(efd, F_SETFD, FD_CLOEXEC);
387 
388 	c->rfd = rfd;
389 	c->wfd = wfd;
390 	c->sock = (rfd == wfd) ? rfd : -1;
391 	c->efd = efd;
392 	c->extended_usage = extusage;
393 
394 	if ((c->isatty = is_tty) != 0)
395 		debug2("channel %d: rfd %d isatty", c->self, c->rfd);
396 
397 	/* enable nonblocking mode */
398 	c->restore_block = 0;
399 	if (nonblock == CHANNEL_NONBLOCK_STDIO) {
400 		/*
401 		 * Special handling for stdio file descriptors: do not set
402 		 * non-blocking mode if they are TTYs. Otherwise prepare to
403 		 * restore their blocking state on exit to avoid interfering
404 		 * with other programs that follow.
405 		 */
406 		if (rfd != -1 && !isatty(rfd) &&
407 		    (val = fcntl(rfd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
408 			c->restore_flags[0] = val;
409 			c->restore_block |= CHANNEL_RESTORE_RFD;
410 			set_nonblock(rfd);
411 		}
412 		if (wfd != -1 && !isatty(wfd) &&
413 		    (val = fcntl(wfd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
414 			c->restore_flags[1] = val;
415 			c->restore_block |= CHANNEL_RESTORE_WFD;
416 			set_nonblock(wfd);
417 		}
418 		if (efd != -1 && !isatty(efd) &&
419 		    (val = fcntl(efd, F_GETFL)) != -1 && !(val & O_NONBLOCK)) {
420 			c->restore_flags[2] = val;
421 			c->restore_block |= CHANNEL_RESTORE_EFD;
422 			set_nonblock(efd);
423 		}
424 	} else if (nonblock) {
425 		if (rfd != -1)
426 			set_nonblock(rfd);
427 		if (wfd != -1)
428 			set_nonblock(wfd);
429 		if (efd != -1)
430 			set_nonblock(efd);
431 	}
432 }
433 
434 /*
435  * Allocate a new channel object and set its type and socket.
436  */
437 Channel *
438 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
439     u_int window, u_int maxpack, int extusage, const char *remote_name,
440     int nonblock)
441 {
442 	struct ssh_channels *sc = ssh->chanctxt;
443 	u_int i, found;
444 	Channel *c;
445 	int r;
446 
447 	/* Try to find a free slot where to put the new channel. */
448 	for (i = 0; i < sc->channels_alloc; i++) {
449 		if (sc->channels[i] == NULL) {
450 			/* Found a free slot. */
451 			found = i;
452 			break;
453 		}
454 	}
455 	if (i >= sc->channels_alloc) {
456 		/*
457 		 * There are no free slots. Take last+1 slot and expand
458 		 * the array.
459 		 */
460 		found = sc->channels_alloc;
461 		if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
462 			fatal_f("internal error: channels_alloc %d too big",
463 			    sc->channels_alloc);
464 		sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
465 		    sc->channels_alloc + 10, sizeof(*sc->channels));
466 		sc->channels_alloc += 10;
467 		debug2("channel: expanding %d", sc->channels_alloc);
468 	}
469 	/* Initialize and return new channel. */
470 	c = sc->channels[found] = xcalloc(1, sizeof(Channel));
471 	if ((c->input = sshbuf_new()) == NULL ||
472 	    (c->output = sshbuf_new()) == NULL ||
473 	    (c->extended = sshbuf_new()) == NULL)
474 		fatal_f("sshbuf_new failed");
475 	if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
476 		fatal_fr(r, "sshbuf_set_max_size");
477 	c->ostate = CHAN_OUTPUT_OPEN;
478 	c->istate = CHAN_INPUT_OPEN;
479 	channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
480 	c->self = found;
481 	c->type = type;
482 	c->ctype = ctype;
483 	c->local_window = window;
484 	c->local_window_max = window;
485 	c->local_maxpacket = maxpack;
486 	c->remote_name = xstrdup(remote_name);
487 	c->ctl_chan = -1;
488 	c->delayed = 1;		/* prevent call to channel_post handler */
489 	c->inactive_deadline = lookup_timeout(ssh, c->ctype);
490 	TAILQ_INIT(&c->status_confirms);
491 	debug("channel %d: new %s [%s] (inactive timeout: %u)",
492 	    found, c->ctype, remote_name, c->inactive_deadline);
493 	return c;
494 }
495 
496 int
497 channel_close_fd(struct ssh *ssh, Channel *c, int *fdp)
498 {
499 	int ret, fd = *fdp;
500 
501 	if (fd == -1)
502 		return 0;
503 
504 	/* restore blocking */
505 	if (*fdp == c->rfd &&
506 	    (c->restore_block & CHANNEL_RESTORE_RFD) != 0)
507 		(void)fcntl(*fdp, F_SETFL, c->restore_flags[0]);
508 	else if (*fdp == c->wfd &&
509 	    (c->restore_block & CHANNEL_RESTORE_WFD) != 0)
510 		(void)fcntl(*fdp, F_SETFL, c->restore_flags[1]);
511 	else if (*fdp == c->efd &&
512 	    (c->restore_block & CHANNEL_RESTORE_EFD) != 0)
513 		(void)fcntl(*fdp, F_SETFL, c->restore_flags[2]);
514 
515 	if (*fdp == c->rfd) {
516 		c->io_want &= ~SSH_CHAN_IO_RFD;
517 		c->io_ready &= ~SSH_CHAN_IO_RFD;
518 		c->rfd = -1;
519 		c->pfds[0] = -1;
520 	}
521 	if (*fdp == c->wfd) {
522 		c->io_want &= ~SSH_CHAN_IO_WFD;
523 		c->io_ready &= ~SSH_CHAN_IO_WFD;
524 		c->wfd = -1;
525 		c->pfds[1] = -1;
526 	}
527 	if (*fdp == c->efd) {
528 		c->io_want &= ~SSH_CHAN_IO_EFD;
529 		c->io_ready &= ~SSH_CHAN_IO_EFD;
530 		c->efd = -1;
531 		c->pfds[2] = -1;
532 	}
533 	if (*fdp == c->sock) {
534 		c->io_want &= ~SSH_CHAN_IO_SOCK;
535 		c->io_ready &= ~SSH_CHAN_IO_SOCK;
536 		c->sock = -1;
537 		c->pfds[3] = -1;
538 	}
539 
540 	ret = close(fd);
541 	*fdp = -1; /* probably redundant */
542 	return ret;
543 }
544 
545 /* Close all channel fd/socket. */
546 static void
547 channel_close_fds(struct ssh *ssh, Channel *c)
548 {
549 	int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
550 
551 	channel_close_fd(ssh, c, &c->sock);
552 	if (rfd != sock)
553 		channel_close_fd(ssh, c, &c->rfd);
554 	if (wfd != sock && wfd != rfd)
555 		channel_close_fd(ssh, c, &c->wfd);
556 	if (efd != sock && efd != rfd && efd != wfd)
557 		channel_close_fd(ssh, c, &c->efd);
558 }
559 
560 static void
561 fwd_perm_clear(struct permission *perm)
562 {
563 	free(perm->host_to_connect);
564 	free(perm->listen_host);
565 	free(perm->listen_path);
566 	memset(perm, 0, sizeof(*perm));
567 }
568 
569 /* Returns an printable name for the specified forwarding permission list */
570 static const char *
571 fwd_ident(int who, int where)
572 {
573 	if (who == FORWARD_ADM) {
574 		if (where == FORWARD_LOCAL)
575 			return "admin local";
576 		else if (where == FORWARD_REMOTE)
577 			return "admin remote";
578 	} else if (who == FORWARD_USER) {
579 		if (where == FORWARD_LOCAL)
580 			return "user local";
581 		else if (where == FORWARD_REMOTE)
582 			return "user remote";
583 	}
584 	fatal("Unknown forward permission list %d/%d", who, where);
585 }
586 
587 /* Returns the forwarding permission list for the specified direction */
588 static struct permission_set *
589 permission_set_get(struct ssh *ssh, int where)
590 {
591 	struct ssh_channels *sc = ssh->chanctxt;
592 
593 	switch (where) {
594 	case FORWARD_LOCAL:
595 		return &sc->local_perms;
596 		break;
597 	case FORWARD_REMOTE:
598 		return &sc->remote_perms;
599 		break;
600 	default:
601 		fatal_f("invalid forwarding direction %d", where);
602 	}
603 }
604 
605 /* Returns pointers to the specified forwarding list and its element count */
606 static void
607 permission_set_get_array(struct ssh *ssh, int who, int where,
608     struct permission ***permpp, u_int **npermpp)
609 {
610 	struct permission_set *pset = permission_set_get(ssh, where);
611 
612 	switch (who) {
613 	case FORWARD_USER:
614 		*permpp = &pset->permitted_user;
615 		*npermpp = &pset->num_permitted_user;
616 		break;
617 	case FORWARD_ADM:
618 		*permpp = &pset->permitted_admin;
619 		*npermpp = &pset->num_permitted_admin;
620 		break;
621 	default:
622 		fatal_f("invalid forwarding client %d", who);
623 	}
624 }
625 
626 /* Adds an entry to the specified forwarding list */
627 static int
628 permission_set_add(struct ssh *ssh, int who, int where,
629     const char *host_to_connect, int port_to_connect,
630     const char *listen_host, const char *listen_path, int listen_port,
631     Channel *downstream)
632 {
633 	struct permission **permp;
634 	u_int n, *npermp;
635 
636 	permission_set_get_array(ssh, who, where, &permp, &npermp);
637 
638 	if (*npermp >= INT_MAX)
639 		fatal_f("%s overflow", fwd_ident(who, where));
640 
641 	*permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
642 	n = (*npermp)++;
643 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
644 	(*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
645 	(*permp)[n].port_to_connect = port_to_connect;
646 	(*permp)[n].listen_host = MAYBE_DUP(listen_host);
647 	(*permp)[n].listen_path = MAYBE_DUP(listen_path);
648 	(*permp)[n].listen_port = listen_port;
649 	(*permp)[n].downstream = downstream;
650 #undef MAYBE_DUP
651 	return (int)n;
652 }
653 
654 static void
655 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
656 {
657 	struct ssh_channels *sc = ssh->chanctxt;
658 	struct permission_set *pset = &sc->local_perms;
659 	struct permission *perm;
660 	int r;
661 	u_int i;
662 
663 	for (i = 0; i < pset->num_permitted_user; i++) {
664 		perm = &pset->permitted_user[i];
665 		if (perm->downstream != c)
666 			continue;
667 
668 		/* cancel on the server, since mux client is gone */
669 		debug("channel %d: cleanup remote forward for %s:%u",
670 		    c->self, perm->listen_host, perm->listen_port);
671 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
672 		    (r = sshpkt_put_cstring(ssh,
673 		    "cancel-tcpip-forward")) != 0 ||
674 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
675 		    (r = sshpkt_put_cstring(ssh,
676 		    channel_rfwd_bind_host(perm->listen_host))) != 0 ||
677 		    (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
678 		    (r = sshpkt_send(ssh)) != 0) {
679 			fatal_fr(r, "channel %i", c->self);
680 		}
681 		fwd_perm_clear(perm); /* unregister */
682 	}
683 }
684 
685 /* Free the channel and close its fd/socket. */
686 void
687 channel_free(struct ssh *ssh, Channel *c)
688 {
689 	struct ssh_channels *sc = ssh->chanctxt;
690 	char *s;
691 	u_int i, n;
692 	Channel *other;
693 	struct channel_confirm *cc;
694 
695 	for (n = 0, i = 0; i < sc->channels_alloc; i++) {
696 		if ((other = sc->channels[i]) == NULL)
697 			continue;
698 		n++;
699 		/* detach from mux client and prepare for closing */
700 		if (c->type == SSH_CHANNEL_MUX_CLIENT &&
701 		    other->type == SSH_CHANNEL_MUX_PROXY &&
702 		    other->mux_ctx == c) {
703 			other->mux_ctx = NULL;
704 			other->type = SSH_CHANNEL_OPEN;
705 			other->istate = CHAN_INPUT_CLOSED;
706 			other->ostate = CHAN_OUTPUT_CLOSED;
707 		}
708 	}
709 	debug("channel %d: free: %s, nchannels %u", c->self,
710 	    c->remote_name ? c->remote_name : "???", n);
711 
712 	if (c->type == SSH_CHANNEL_MUX_CLIENT) {
713 		mux_remove_remote_forwardings(ssh, c);
714 		free(c->mux_ctx);
715 		c->mux_ctx = NULL;
716 	} else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
717 		free(c->mux_ctx);
718 		c->mux_ctx = NULL;
719 	}
720 
721 	if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
722 		s = channel_open_message(ssh);
723 		debug3("channel %d: status: %s", c->self, s);
724 		free(s);
725 	}
726 
727 	channel_close_fds(ssh, c);
728 	sshbuf_free(c->input);
729 	sshbuf_free(c->output);
730 	sshbuf_free(c->extended);
731 	c->input = c->output = c->extended = NULL;
732 	free(c->remote_name);
733 	c->remote_name = NULL;
734 	free(c->path);
735 	c->path = NULL;
736 	free(c->listening_addr);
737 	c->listening_addr = NULL;
738 	free(c->xctype);
739 	c->xctype = NULL;
740 	while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
741 		if (cc->abandon_cb != NULL)
742 			cc->abandon_cb(ssh, c, cc->ctx);
743 		TAILQ_REMOVE(&c->status_confirms, cc, entry);
744 		freezero(cc, sizeof(*cc));
745 	}
746 	if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
747 		c->filter_cleanup(ssh, c->self, c->filter_ctx);
748 	sc->channels[c->self] = NULL;
749 	freezero(c, sizeof(*c));
750 }
751 
752 void
753 channel_free_all(struct ssh *ssh)
754 {
755 	u_int i;
756 	struct ssh_channels *sc = ssh->chanctxt;
757 
758 	for (i = 0; i < sc->channels_alloc; i++)
759 		if (sc->channels[i] != NULL)
760 			channel_free(ssh, sc->channels[i]);
761 
762 	free(sc->channels);
763 	sc->channels = NULL;
764 	sc->channels_alloc = 0;
765 
766 	free(sc->x11_saved_display);
767 	sc->x11_saved_display = NULL;
768 
769 	free(sc->x11_saved_proto);
770 	sc->x11_saved_proto = NULL;
771 
772 	free(sc->x11_saved_data);
773 	sc->x11_saved_data = NULL;
774 	sc->x11_saved_data_len = 0;
775 
776 	free(sc->x11_fake_data);
777 	sc->x11_fake_data = NULL;
778 	sc->x11_fake_data_len = 0;
779 }
780 
781 /*
782  * Closes the sockets/fds of all channels.  This is used to close extra file
783  * descriptors after a fork.
784  */
785 void
786 channel_close_all(struct ssh *ssh)
787 {
788 	u_int i;
789 
790 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
791 		if (ssh->chanctxt->channels[i] != NULL)
792 			channel_close_fds(ssh, ssh->chanctxt->channels[i]);
793 }
794 
795 /*
796  * Stop listening to channels.
797  */
798 void
799 channel_stop_listening(struct ssh *ssh)
800 {
801 	u_int i;
802 	Channel *c;
803 
804 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
805 		c = ssh->chanctxt->channels[i];
806 		if (c != NULL) {
807 			switch (c->type) {
808 			case SSH_CHANNEL_AUTH_SOCKET:
809 			case SSH_CHANNEL_PORT_LISTENER:
810 			case SSH_CHANNEL_RPORT_LISTENER:
811 			case SSH_CHANNEL_X11_LISTENER:
812 			case SSH_CHANNEL_UNIX_LISTENER:
813 			case SSH_CHANNEL_RUNIX_LISTENER:
814 				channel_close_fd(ssh, c, &c->sock);
815 				channel_free(ssh, c);
816 				break;
817 			}
818 		}
819 	}
820 }
821 
822 /*
823  * Returns true if no channel has too much buffered data, and false if one or
824  * more channel is overfull.
825  */
826 int
827 channel_not_very_much_buffered_data(struct ssh *ssh)
828 {
829 	u_int i;
830 	u_int maxsize = ssh_packet_get_maxsize(ssh);
831 	Channel *c;
832 
833 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
834 		c = ssh->chanctxt->channels[i];
835 		if (c == NULL || c->type != SSH_CHANNEL_OPEN)
836 			continue;
837 		if (sshbuf_len(c->output) > maxsize) {
838 			debug2("channel %d: big output buffer %zu > %u",
839 			    c->self, sshbuf_len(c->output), maxsize);
840 			return 0;
841 		}
842 	}
843 	return 1;
844 }
845 
846 /* Returns true if any channel is still open. */
847 int
848 channel_still_open(struct ssh *ssh)
849 {
850 	u_int i;
851 	Channel *c;
852 
853 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
854 		c = ssh->chanctxt->channels[i];
855 		if (c == NULL)
856 			continue;
857 		switch (c->type) {
858 		case SSH_CHANNEL_X11_LISTENER:
859 		case SSH_CHANNEL_PORT_LISTENER:
860 		case SSH_CHANNEL_RPORT_LISTENER:
861 		case SSH_CHANNEL_MUX_LISTENER:
862 		case SSH_CHANNEL_CLOSED:
863 		case SSH_CHANNEL_AUTH_SOCKET:
864 		case SSH_CHANNEL_DYNAMIC:
865 		case SSH_CHANNEL_RDYNAMIC_OPEN:
866 		case SSH_CHANNEL_CONNECTING:
867 		case SSH_CHANNEL_ZOMBIE:
868 		case SSH_CHANNEL_ABANDONED:
869 		case SSH_CHANNEL_UNIX_LISTENER:
870 		case SSH_CHANNEL_RUNIX_LISTENER:
871 			continue;
872 		case SSH_CHANNEL_LARVAL:
873 			continue;
874 		case SSH_CHANNEL_OPENING:
875 		case SSH_CHANNEL_OPEN:
876 		case SSH_CHANNEL_RDYNAMIC_FINISH:
877 		case SSH_CHANNEL_X11_OPEN:
878 		case SSH_CHANNEL_MUX_CLIENT:
879 		case SSH_CHANNEL_MUX_PROXY:
880 			return 1;
881 		default:
882 			fatal_f("bad channel type %d", c->type);
883 			/* NOTREACHED */
884 		}
885 	}
886 	return 0;
887 }
888 
889 /* Returns the id of an open channel suitable for keepaliving */
890 int
891 channel_find_open(struct ssh *ssh)
892 {
893 	u_int i;
894 	Channel *c;
895 
896 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
897 		c = ssh->chanctxt->channels[i];
898 		if (c == NULL || !c->have_remote_id)
899 			continue;
900 		switch (c->type) {
901 		case SSH_CHANNEL_CLOSED:
902 		case SSH_CHANNEL_DYNAMIC:
903 		case SSH_CHANNEL_RDYNAMIC_OPEN:
904 		case SSH_CHANNEL_RDYNAMIC_FINISH:
905 		case SSH_CHANNEL_X11_LISTENER:
906 		case SSH_CHANNEL_PORT_LISTENER:
907 		case SSH_CHANNEL_RPORT_LISTENER:
908 		case SSH_CHANNEL_MUX_LISTENER:
909 		case SSH_CHANNEL_MUX_CLIENT:
910 		case SSH_CHANNEL_MUX_PROXY:
911 		case SSH_CHANNEL_OPENING:
912 		case SSH_CHANNEL_CONNECTING:
913 		case SSH_CHANNEL_ZOMBIE:
914 		case SSH_CHANNEL_ABANDONED:
915 		case SSH_CHANNEL_UNIX_LISTENER:
916 		case SSH_CHANNEL_RUNIX_LISTENER:
917 			continue;
918 		case SSH_CHANNEL_LARVAL:
919 		case SSH_CHANNEL_AUTH_SOCKET:
920 		case SSH_CHANNEL_OPEN:
921 		case SSH_CHANNEL_X11_OPEN:
922 			return i;
923 		default:
924 			fatal_f("bad channel type %d", c->type);
925 			/* NOTREACHED */
926 		}
927 	}
928 	return -1;
929 }
930 
931 /* Returns the state of the channel's extended usage flag */
932 const char *
933 channel_format_extended_usage(const Channel *c)
934 {
935 	if (c->efd == -1)
936 		return "closed";
937 
938 	switch (c->extended_usage) {
939 	case CHAN_EXTENDED_WRITE:
940 		return "write";
941 	case CHAN_EXTENDED_READ:
942 		return "read";
943 	case CHAN_EXTENDED_IGNORE:
944 		return "ignore";
945 	default:
946 		return "UNKNOWN";
947 	}
948 }
949 
950 static char *
951 channel_format_status(const Channel *c)
952 {
953 	char *ret = NULL;
954 
955 	xasprintf(&ret, "t%d [%s] %s%u i%u/%zu o%u/%zu e[%s]/%zu "
956 	    "fd %d/%d/%d sock %d cc %d io 0x%02x/0x%02x",
957 	    c->type, c->xctype != NULL ? c->xctype : c->ctype,
958 	    c->have_remote_id ? "r" : "nr", c->remote_id,
959 	    c->istate, sshbuf_len(c->input),
960 	    c->ostate, sshbuf_len(c->output),
961 	    channel_format_extended_usage(c), sshbuf_len(c->extended),
962 	    c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan,
963 	    c->io_want, c->io_ready);
964 	return ret;
965 }
966 
967 /*
968  * Returns a message describing the currently open forwarded connections,
969  * suitable for sending to the client.  The message contains crlf pairs for
970  * newlines.
971  */
972 char *
973 channel_open_message(struct ssh *ssh)
974 {
975 	struct sshbuf *buf;
976 	Channel *c;
977 	u_int i;
978 	int r;
979 	char *cp, *ret;
980 
981 	if ((buf = sshbuf_new()) == NULL)
982 		fatal_f("sshbuf_new");
983 	if ((r = sshbuf_putf(buf,
984 	    "The following connections are open:\r\n")) != 0)
985 		fatal_fr(r, "sshbuf_putf");
986 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
987 		c = ssh->chanctxt->channels[i];
988 		if (c == NULL)
989 			continue;
990 		switch (c->type) {
991 		case SSH_CHANNEL_X11_LISTENER:
992 		case SSH_CHANNEL_PORT_LISTENER:
993 		case SSH_CHANNEL_RPORT_LISTENER:
994 		case SSH_CHANNEL_CLOSED:
995 		case SSH_CHANNEL_AUTH_SOCKET:
996 		case SSH_CHANNEL_ZOMBIE:
997 		case SSH_CHANNEL_ABANDONED:
998 		case SSH_CHANNEL_MUX_LISTENER:
999 		case SSH_CHANNEL_UNIX_LISTENER:
1000 		case SSH_CHANNEL_RUNIX_LISTENER:
1001 			continue;
1002 		case SSH_CHANNEL_LARVAL:
1003 		case SSH_CHANNEL_OPENING:
1004 		case SSH_CHANNEL_CONNECTING:
1005 		case SSH_CHANNEL_DYNAMIC:
1006 		case SSH_CHANNEL_RDYNAMIC_OPEN:
1007 		case SSH_CHANNEL_RDYNAMIC_FINISH:
1008 		case SSH_CHANNEL_OPEN:
1009 		case SSH_CHANNEL_X11_OPEN:
1010 		case SSH_CHANNEL_MUX_PROXY:
1011 		case SSH_CHANNEL_MUX_CLIENT:
1012 			cp = channel_format_status(c);
1013 			if ((r = sshbuf_putf(buf, "  #%d %.300s (%s)\r\n",
1014 			    c->self, c->remote_name, cp)) != 0) {
1015 				free(cp);
1016 				fatal_fr(r, "sshbuf_putf");
1017 			}
1018 			free(cp);
1019 			continue;
1020 		default:
1021 			fatal_f("bad channel type %d", c->type);
1022 			/* NOTREACHED */
1023 		}
1024 	}
1025 	if ((ret = sshbuf_dup_string(buf)) == NULL)
1026 		fatal_f("sshbuf_dup_string");
1027 	sshbuf_free(buf);
1028 	return ret;
1029 }
1030 
1031 static void
1032 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
1033 {
1034 	int r;
1035 
1036 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
1037 	    (r = sshpkt_put_cstring(ssh, type)) != 0 ||
1038 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1039 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1040 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
1041 		fatal_r(r, "%s: channel %i: open", where, c->self);
1042 	}
1043 }
1044 
1045 void
1046 channel_send_open(struct ssh *ssh, int id)
1047 {
1048 	Channel *c = channel_lookup(ssh, id);
1049 	int r;
1050 
1051 	if (c == NULL) {
1052 		logit("channel_send_open: %d: bad id", id);
1053 		return;
1054 	}
1055 	debug2("channel %d: send open", id);
1056 	open_preamble(ssh, __func__, c, c->ctype);
1057 	if ((r = sshpkt_send(ssh)) != 0)
1058 		fatal_fr(r, "channel %i", c->self);
1059 }
1060 
1061 void
1062 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
1063 {
1064 	Channel *c = channel_lookup(ssh, id);
1065 	int r;
1066 
1067 	if (c == NULL) {
1068 		logit_f("%d: unknown channel id", id);
1069 		return;
1070 	}
1071 	if (!c->have_remote_id)
1072 		fatal_f("channel %d: no remote id", c->self);
1073 
1074 	debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
1075 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
1076 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1077 	    (r = sshpkt_put_cstring(ssh, service)) != 0 ||
1078 	    (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
1079 		fatal_fr(r, "channel %i", c->self);
1080 	}
1081 }
1082 
1083 void
1084 channel_register_status_confirm(struct ssh *ssh, int id,
1085     channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
1086 {
1087 	struct channel_confirm *cc;
1088 	Channel *c;
1089 
1090 	if ((c = channel_lookup(ssh, id)) == NULL)
1091 		fatal_f("%d: bad id", id);
1092 
1093 	cc = xcalloc(1, sizeof(*cc));
1094 	cc->cb = cb;
1095 	cc->abandon_cb = abandon_cb;
1096 	cc->ctx = ctx;
1097 	TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
1098 }
1099 
1100 void
1101 channel_register_open_confirm(struct ssh *ssh, int id,
1102     channel_open_fn *fn, void *ctx)
1103 {
1104 	Channel *c = channel_lookup(ssh, id);
1105 
1106 	if (c == NULL) {
1107 		logit_f("%d: bad id", id);
1108 		return;
1109 	}
1110 	c->open_confirm = fn;
1111 	c->open_confirm_ctx = ctx;
1112 }
1113 
1114 void
1115 channel_register_cleanup(struct ssh *ssh, int id,
1116     channel_callback_fn *fn, int do_close)
1117 {
1118 	Channel *c = channel_by_id(ssh, id);
1119 
1120 	if (c == NULL) {
1121 		logit_f("%d: bad id", id);
1122 		return;
1123 	}
1124 	c->detach_user = fn;
1125 	c->detach_close = do_close;
1126 }
1127 
1128 void
1129 channel_cancel_cleanup(struct ssh *ssh, int id)
1130 {
1131 	Channel *c = channel_by_id(ssh, id);
1132 
1133 	if (c == NULL) {
1134 		logit_f("%d: bad id", id);
1135 		return;
1136 	}
1137 	c->detach_user = NULL;
1138 	c->detach_close = 0;
1139 }
1140 
1141 void
1142 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1143     channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1144 {
1145 	Channel *c = channel_lookup(ssh, id);
1146 
1147 	if (c == NULL) {
1148 		logit_f("%d: bad id", id);
1149 		return;
1150 	}
1151 	c->input_filter = ifn;
1152 	c->output_filter = ofn;
1153 	c->filter_ctx = ctx;
1154 	c->filter_cleanup = cfn;
1155 }
1156 
1157 void
1158 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1159     int extusage, int nonblock, int is_tty, u_int window_max)
1160 {
1161 	Channel *c = channel_lookup(ssh, id);
1162 	int r;
1163 
1164 	if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1165 		fatal("channel_activate for non-larval channel %d.", id);
1166 	if (!c->have_remote_id)
1167 		fatal_f("channel %d: no remote id", c->self);
1168 
1169 	channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1170 	c->type = SSH_CHANNEL_OPEN;
1171 	c->lastused = monotime();
1172 	c->local_window = c->local_window_max = window_max;
1173 
1174 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1175 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1176 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1177 	    (r = sshpkt_send(ssh)) != 0)
1178 		fatal_fr(r, "channel %i", c->self);
1179 }
1180 
1181 static void
1182 channel_pre_listener(struct ssh *ssh, Channel *c)
1183 {
1184 	c->io_want = SSH_CHAN_IO_SOCK_R;
1185 }
1186 
1187 static void
1188 channel_pre_connecting(struct ssh *ssh, Channel *c)
1189 {
1190 	debug3("channel %d: waiting for connection", c->self);
1191 	c->io_want = SSH_CHAN_IO_SOCK_W;
1192 }
1193 
1194 static void
1195 channel_pre_open(struct ssh *ssh, Channel *c)
1196 {
1197 	c->io_want = 0;
1198 	if (c->istate == CHAN_INPUT_OPEN &&
1199 	    c->remote_window > 0 &&
1200 	    sshbuf_len(c->input) < c->remote_window &&
1201 	    sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1202 		c->io_want |= SSH_CHAN_IO_RFD;
1203 	if (c->ostate == CHAN_OUTPUT_OPEN ||
1204 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1205 		if (sshbuf_len(c->output) > 0) {
1206 			c->io_want |= SSH_CHAN_IO_WFD;
1207 		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1208 			if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1209 				debug2("channel %d: "
1210 				    "obuf_empty delayed efd %d/(%zu)", c->self,
1211 				    c->efd, sshbuf_len(c->extended));
1212 			else
1213 				chan_obuf_empty(ssh, c);
1214 		}
1215 	}
1216 	/** XXX check close conditions, too */
1217 	if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1218 	    c->ostate == CHAN_OUTPUT_CLOSED)) {
1219 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1220 		    sshbuf_len(c->extended) > 0)
1221 			c->io_want |= SSH_CHAN_IO_EFD_W;
1222 		else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1223 		    (c->extended_usage == CHAN_EXTENDED_READ ||
1224 		    c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1225 		    sshbuf_len(c->extended) < c->remote_window)
1226 			c->io_want |= SSH_CHAN_IO_EFD_R;
1227 	}
1228 	/* XXX: What about efd? races? */
1229 }
1230 
1231 /*
1232  * This is a special state for X11 authentication spoofing.  An opened X11
1233  * connection (when authentication spoofing is being done) remains in this
1234  * state until the first packet has been completely read.  The authentication
1235  * data in that packet is then substituted by the real data if it matches the
1236  * fake data, and the channel is put into normal mode.
1237  * XXX All this happens at the client side.
1238  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1239  */
1240 static int
1241 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1242 {
1243 	struct ssh_channels *sc = ssh->chanctxt;
1244 	u_char *ucp;
1245 	u_int proto_len, data_len;
1246 
1247 	/* Is this being called after the refusal deadline? */
1248 	if (sc->x11_refuse_time != 0 &&
1249 	    monotime() >= sc->x11_refuse_time) {
1250 		verbose("Rejected X11 connection after ForwardX11Timeout "
1251 		    "expired");
1252 		return -1;
1253 	}
1254 
1255 	/* Check if the fixed size part of the packet is in buffer. */
1256 	if (sshbuf_len(b) < 12)
1257 		return 0;
1258 
1259 	/* Parse the lengths of variable-length fields. */
1260 	ucp = sshbuf_mutable_ptr(b);
1261 	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
1262 		proto_len = 256 * ucp[6] + ucp[7];
1263 		data_len = 256 * ucp[8] + ucp[9];
1264 	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
1265 		proto_len = ucp[6] + 256 * ucp[7];
1266 		data_len = ucp[8] + 256 * ucp[9];
1267 	} else {
1268 		debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1269 		    ucp[0]);
1270 		return -1;
1271 	}
1272 
1273 	/* Check if the whole packet is in buffer. */
1274 	if (sshbuf_len(b) <
1275 	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1276 		return 0;
1277 
1278 	/* Check if authentication protocol matches. */
1279 	if (proto_len != strlen(sc->x11_saved_proto) ||
1280 	    memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1281 		debug2("X11 connection uses different authentication protocol.");
1282 		return -1;
1283 	}
1284 	/* Check if authentication data matches our fake data. */
1285 	if (data_len != sc->x11_fake_data_len ||
1286 	    timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1287 		sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1288 		debug2("X11 auth data does not match fake data.");
1289 		return -1;
1290 	}
1291 	/* Check fake data length */
1292 	if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1293 		error("X11 fake_data_len %d != saved_data_len %d",
1294 		    sc->x11_fake_data_len, sc->x11_saved_data_len);
1295 		return -1;
1296 	}
1297 	/*
1298 	 * Received authentication protocol and data match
1299 	 * our fake data. Substitute the fake data with real
1300 	 * data.
1301 	 */
1302 	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1303 	    sc->x11_saved_data, sc->x11_saved_data_len);
1304 	return 1;
1305 }
1306 
1307 void
1308 channel_force_close(struct ssh *ssh, Channel *c, int abandon)
1309 {
1310 	debug3_f("channel %d: forcibly closing", c->self);
1311 	if (c->istate == CHAN_INPUT_OPEN)
1312 		chan_read_failed(ssh, c);
1313 	if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1314 		sshbuf_reset(c->input);
1315 		chan_ibuf_empty(ssh, c);
1316 	}
1317 	if (c->ostate == CHAN_OUTPUT_OPEN ||
1318 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1319 		sshbuf_reset(c->output);
1320 		chan_write_failed(ssh, c);
1321 	}
1322 	if (c->detach_user)
1323 		c->detach_user(ssh, c->self, 1, NULL);
1324 	if (c->efd != -1)
1325 		channel_close_fd(ssh, c, &c->efd);
1326 	if (abandon)
1327 		c->type = SSH_CHANNEL_ABANDONED;
1328 	/* exempt from inactivity timeouts */
1329 	c->inactive_deadline = 0;
1330 	c->lastused = 0;
1331 }
1332 
1333 static void
1334 channel_pre_x11_open(struct ssh *ssh, Channel *c)
1335 {
1336 	int ret = x11_open_helper(ssh, c->output);
1337 
1338 	/* c->force_drain = 1; */
1339 
1340 	if (ret == 1) {
1341 		c->type = SSH_CHANNEL_OPEN;
1342 		c->lastused = monotime();
1343 		channel_pre_open(ssh, c);
1344 	} else if (ret == -1) {
1345 		logit("X11 connection rejected because of wrong "
1346 		    "authentication.");
1347 		debug2("X11 rejected %d i%d/o%d",
1348 		    c->self, c->istate, c->ostate);
1349 		channel_force_close(ssh, c, 0);
1350 	}
1351 }
1352 
1353 static void
1354 channel_pre_mux_client(struct ssh *ssh, Channel *c)
1355 {
1356 	c->io_want = 0;
1357 	if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1358 	    sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1359 		c->io_want |= SSH_CHAN_IO_RFD;
1360 	if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1361 		/* clear buffer immediately (discard any partial packet) */
1362 		sshbuf_reset(c->input);
1363 		chan_ibuf_empty(ssh, c);
1364 		/* Start output drain. XXX just kill chan? */
1365 		chan_rcvd_oclose(ssh, c);
1366 	}
1367 	if (c->ostate == CHAN_OUTPUT_OPEN ||
1368 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1369 		if (sshbuf_len(c->output) > 0)
1370 			c->io_want |= SSH_CHAN_IO_WFD;
1371 		else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1372 			chan_obuf_empty(ssh, c);
1373 	}
1374 }
1375 
1376 /* try to decode a socks4 header */
1377 static int
1378 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1379 {
1380 	const u_char *p;
1381 	char *host;
1382 	u_int len, have, i, found, need;
1383 	char username[256];
1384 	struct {
1385 		u_int8_t version;
1386 		u_int8_t command;
1387 		u_int16_t dest_port;
1388 		struct in_addr dest_addr;
1389 	} s4_req, s4_rsp;
1390 	int r;
1391 
1392 	debug2("channel %d: decode socks4", c->self);
1393 
1394 	have = sshbuf_len(input);
1395 	len = sizeof(s4_req);
1396 	if (have < len)
1397 		return 0;
1398 	p = sshbuf_ptr(input);
1399 
1400 	need = 1;
1401 	/* SOCKS4A uses an invalid IP address 0.0.0.x */
1402 	if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1403 		debug2("channel %d: socks4a request", c->self);
1404 		/* ... and needs an extra string (the hostname) */
1405 		need = 2;
1406 	}
1407 	/* Check for terminating NUL on the string(s) */
1408 	for (found = 0, i = len; i < have; i++) {
1409 		if (p[i] == '\0') {
1410 			found++;
1411 			if (found == need)
1412 				break;
1413 		}
1414 		if (i > 1024) {
1415 			/* the peer is probably sending garbage */
1416 			debug("channel %d: decode socks4: too long",
1417 			    c->self);
1418 			return -1;
1419 		}
1420 	}
1421 	if (found < need)
1422 		return 0;
1423 	if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1424 	    (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1425 	    (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1426 	    (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1427 		debug_r(r, "channels %d: decode socks4", c->self);
1428 		return -1;
1429 	}
1430 	have = sshbuf_len(input);
1431 	p = sshbuf_ptr(input);
1432 	if (memchr(p, '\0', have) == NULL) {
1433 		error("channel %d: decode socks4: unterminated user", c->self);
1434 		return -1;
1435 	}
1436 	len = strlen(p);
1437 	debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1438 	len++; /* trailing '\0' */
1439 	strlcpy(username, p, sizeof(username));
1440 	if ((r = sshbuf_consume(input, len)) != 0)
1441 		fatal_fr(r, "channel %d: consume", c->self);
1442 	free(c->path);
1443 	c->path = NULL;
1444 	if (need == 1) {			/* SOCKS4: one string */
1445 		host = inet_ntoa(s4_req.dest_addr);
1446 		c->path = xstrdup(host);
1447 	} else {				/* SOCKS4A: two strings */
1448 		have = sshbuf_len(input);
1449 		p = sshbuf_ptr(input);
1450 		if (memchr(p, '\0', have) == NULL) {
1451 			error("channel %d: decode socks4a: host not nul "
1452 			    "terminated", c->self);
1453 			return -1;
1454 		}
1455 		len = strlen(p);
1456 		debug2("channel %d: decode socks4a: host %s/%d",
1457 		    c->self, p, len);
1458 		len++;				/* trailing '\0' */
1459 		if (len > NI_MAXHOST) {
1460 			error("channel %d: hostname \"%.100s\" too long",
1461 			    c->self, p);
1462 			return -1;
1463 		}
1464 		c->path = xstrdup(p);
1465 		if ((r = sshbuf_consume(input, len)) != 0)
1466 			fatal_fr(r, "channel %d: consume", c->self);
1467 	}
1468 	c->host_port = ntohs(s4_req.dest_port);
1469 
1470 	debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1471 	    c->self, c->path, c->host_port, s4_req.command);
1472 
1473 	if (s4_req.command != 1) {
1474 		debug("channel %d: cannot handle: %s cn %d",
1475 		    c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1476 		return -1;
1477 	}
1478 	s4_rsp.version = 0;			/* vn: 0 for reply */
1479 	s4_rsp.command = 90;			/* cd: req granted */
1480 	s4_rsp.dest_port = 0;			/* ignored */
1481 	s4_rsp.dest_addr.s_addr = INADDR_ANY;	/* ignored */
1482 	if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0)
1483 		fatal_fr(r, "channel %d: append reply", c->self);
1484 	return 1;
1485 }
1486 
1487 /* try to decode a socks5 header */
1488 #define SSH_SOCKS5_AUTHDONE	0x1000
1489 #define SSH_SOCKS5_NOAUTH	0x00
1490 #define SSH_SOCKS5_IPV4		0x01
1491 #define SSH_SOCKS5_DOMAIN	0x03
1492 #define SSH_SOCKS5_IPV6		0x04
1493 #define SSH_SOCKS5_CONNECT	0x01
1494 #define SSH_SOCKS5_SUCCESS	0x00
1495 
1496 static int
1497 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1498 {
1499 	/* XXX use get/put_u8 instead of trusting struct padding */
1500 	struct {
1501 		u_int8_t version;
1502 		u_int8_t command;
1503 		u_int8_t reserved;
1504 		u_int8_t atyp;
1505 	} s5_req, s5_rsp;
1506 	u_int16_t dest_port;
1507 	char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1508 	const u_char *p;
1509 	u_int have, need, i, found, nmethods, addrlen, af;
1510 	int r;
1511 
1512 	debug2("channel %d: decode socks5", c->self);
1513 	p = sshbuf_ptr(input);
1514 	if (p[0] != 0x05)
1515 		return -1;
1516 	have = sshbuf_len(input);
1517 	if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1518 		/* format: ver | nmethods | methods */
1519 		if (have < 2)
1520 			return 0;
1521 		nmethods = p[1];
1522 		if (have < nmethods + 2)
1523 			return 0;
1524 		/* look for method: "NO AUTHENTICATION REQUIRED" */
1525 		for (found = 0, i = 2; i < nmethods + 2; i++) {
1526 			if (p[i] == SSH_SOCKS5_NOAUTH) {
1527 				found = 1;
1528 				break;
1529 			}
1530 		}
1531 		if (!found) {
1532 			debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1533 			    c->self);
1534 			return -1;
1535 		}
1536 		if ((r = sshbuf_consume(input, nmethods + 2)) != 0)
1537 			fatal_fr(r, "channel %d: consume", c->self);
1538 		/* version, method */
1539 		if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1540 		    (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
1541 			fatal_fr(r, "channel %d: append reply", c->self);
1542 		c->flags |= SSH_SOCKS5_AUTHDONE;
1543 		debug2("channel %d: socks5 auth done", c->self);
1544 		return 0;				/* need more */
1545 	}
1546 	debug2("channel %d: socks5 post auth", c->self);
1547 	if (have < sizeof(s5_req)+1)
1548 		return 0;			/* need more */
1549 	memcpy(&s5_req, p, sizeof(s5_req));
1550 	if (s5_req.version != 0x05 ||
1551 	    s5_req.command != SSH_SOCKS5_CONNECT ||
1552 	    s5_req.reserved != 0x00) {
1553 		debug2("channel %d: only socks5 connect supported", c->self);
1554 		return -1;
1555 	}
1556 	switch (s5_req.atyp){
1557 	case SSH_SOCKS5_IPV4:
1558 		addrlen = 4;
1559 		af = AF_INET;
1560 		break;
1561 	case SSH_SOCKS5_DOMAIN:
1562 		addrlen = p[sizeof(s5_req)];
1563 		af = -1;
1564 		break;
1565 	case SSH_SOCKS5_IPV6:
1566 		addrlen = 16;
1567 		af = AF_INET6;
1568 		break;
1569 	default:
1570 		debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1571 		return -1;
1572 	}
1573 	need = sizeof(s5_req) + addrlen + 2;
1574 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1575 		need++;
1576 	if (have < need)
1577 		return 0;
1578 	if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0)
1579 		fatal_fr(r, "channel %d: consume", c->self);
1580 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1581 		/* host string length */
1582 		if ((r = sshbuf_consume(input, 1)) != 0)
1583 			fatal_fr(r, "channel %d: consume", c->self);
1584 	}
1585 	if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1586 	    (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1587 		debug_r(r, "channel %d: parse addr/port", c->self);
1588 		return -1;
1589 	}
1590 	dest_addr[addrlen] = '\0';
1591 	free(c->path);
1592 	c->path = NULL;
1593 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1594 		if (addrlen >= NI_MAXHOST) {
1595 			error("channel %d: dynamic request: socks5 hostname "
1596 			    "\"%.100s\" too long", c->self, dest_addr);
1597 			return -1;
1598 		}
1599 		c->path = xstrdup(dest_addr);
1600 	} else {
1601 		if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1602 			return -1;
1603 		c->path = xstrdup(ntop);
1604 	}
1605 	c->host_port = ntohs(dest_port);
1606 
1607 	debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1608 	    c->self, c->path, c->host_port, s5_req.command);
1609 
1610 	s5_rsp.version = 0x05;
1611 	s5_rsp.command = SSH_SOCKS5_SUCCESS;
1612 	s5_rsp.reserved = 0;			/* ignored */
1613 	s5_rsp.atyp = SSH_SOCKS5_IPV4;
1614 	dest_port = 0;				/* ignored */
1615 
1616 	if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1617 	    (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1618 	    (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1619 		fatal_fr(r, "channel %d: append reply", c->self);
1620 	return 1;
1621 }
1622 
1623 Channel *
1624 channel_connect_stdio_fwd(struct ssh *ssh,
1625     const char *host_to_connect, u_short port_to_connect,
1626     int in, int out, int nonblock)
1627 {
1628 	Channel *c;
1629 
1630 	debug_f("%s:%d", host_to_connect, port_to_connect);
1631 
1632 	c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1633 	    -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1634 	    0, "stdio-forward", nonblock);
1635 
1636 	c->path = xstrdup(host_to_connect);
1637 	c->host_port = port_to_connect;
1638 	c->listening_port = 0;
1639 	c->force_drain = 1;
1640 
1641 	channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1642 	port_open_helper(ssh, c, "direct-tcpip");
1643 
1644 	return c;
1645 }
1646 
1647 /* dynamic port forwarding */
1648 static void
1649 channel_pre_dynamic(struct ssh *ssh, Channel *c)
1650 {
1651 	const u_char *p;
1652 	u_int have;
1653 	int ret;
1654 
1655 	c->io_want = 0;
1656 	have = sshbuf_len(c->input);
1657 	debug2("channel %d: pre_dynamic: have %d", c->self, have);
1658 	/* sshbuf_dump(c->input, stderr); */
1659 	/* check if the fixed size part of the packet is in buffer. */
1660 	if (have < 3) {
1661 		/* need more */
1662 		c->io_want |= SSH_CHAN_IO_RFD;
1663 		return;
1664 	}
1665 	/* try to guess the protocol */
1666 	p = sshbuf_ptr(c->input);
1667 	/* XXX sshbuf_peek_u8? */
1668 	switch (p[0]) {
1669 	case 0x04:
1670 		ret = channel_decode_socks4(c, c->input, c->output);
1671 		break;
1672 	case 0x05:
1673 		ret = channel_decode_socks5(c, c->input, c->output);
1674 		break;
1675 	default:
1676 		ret = -1;
1677 		break;
1678 	}
1679 	if (ret < 0) {
1680 		chan_mark_dead(ssh, c);
1681 	} else if (ret == 0) {
1682 		debug2("channel %d: pre_dynamic: need more", c->self);
1683 		/* need more */
1684 		c->io_want |= SSH_CHAN_IO_RFD;
1685 		if (sshbuf_len(c->output))
1686 			c->io_want |= SSH_CHAN_IO_WFD;
1687 	} else {
1688 		/* switch to the next state */
1689 		c->type = SSH_CHANNEL_OPENING;
1690 		port_open_helper(ssh, c, "direct-tcpip");
1691 	}
1692 }
1693 
1694 /* simulate read-error */
1695 static void
1696 rdynamic_close(struct ssh *ssh, Channel *c)
1697 {
1698 	c->type = SSH_CHANNEL_OPEN;
1699 	channel_force_close(ssh, c, 0);
1700 }
1701 
1702 /* reverse dynamic port forwarding */
1703 static void
1704 channel_before_prepare_io_rdynamic(struct ssh *ssh, Channel *c)
1705 {
1706 	const u_char *p;
1707 	u_int have, len;
1708 	int r, ret;
1709 
1710 	have = sshbuf_len(c->output);
1711 	debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1712 	/* sshbuf_dump(c->output, stderr); */
1713 	/* EOF received */
1714 	if (c->flags & CHAN_EOF_RCVD) {
1715 		if ((r = sshbuf_consume(c->output, have)) != 0)
1716 			fatal_fr(r, "channel %d: consume", c->self);
1717 		rdynamic_close(ssh, c);
1718 		return;
1719 	}
1720 	/* check if the fixed size part of the packet is in buffer. */
1721 	if (have < 3)
1722 		return;
1723 	/* try to guess the protocol */
1724 	p = sshbuf_ptr(c->output);
1725 	switch (p[0]) {
1726 	case 0x04:
1727 		/* switch input/output for reverse forwarding */
1728 		ret = channel_decode_socks4(c, c->output, c->input);
1729 		break;
1730 	case 0x05:
1731 		ret = channel_decode_socks5(c, c->output, c->input);
1732 		break;
1733 	default:
1734 		ret = -1;
1735 		break;
1736 	}
1737 	if (ret < 0) {
1738 		rdynamic_close(ssh, c);
1739 	} else if (ret == 0) {
1740 		debug2("channel %d: pre_rdynamic: need more", c->self);
1741 		/* send socks request to peer */
1742 		len = sshbuf_len(c->input);
1743 		if (len > 0 && len < c->remote_window) {
1744 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1745 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1746 			    (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1747 			    (r = sshpkt_send(ssh)) != 0) {
1748 				fatal_fr(r, "channel %i: rdynamic", c->self);
1749 			}
1750 			if ((r = sshbuf_consume(c->input, len)) != 0)
1751 				fatal_fr(r, "channel %d: consume", c->self);
1752 			c->remote_window -= len;
1753 		}
1754 	} else if (rdynamic_connect_finish(ssh, c) < 0) {
1755 		/* the connect failed */
1756 		rdynamic_close(ssh, c);
1757 	}
1758 }
1759 
1760 /* This is our fake X11 server socket. */
1761 static void
1762 channel_post_x11_listener(struct ssh *ssh, Channel *c)
1763 {
1764 	Channel *nc;
1765 	struct sockaddr_storage addr;
1766 	int r, newsock, oerrno, remote_port;
1767 	socklen_t addrlen;
1768 	char buf[16384], *remote_ipaddr;
1769 
1770 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1771 		return;
1772 
1773 	debug("X11 connection requested.");
1774 	addrlen = sizeof(addr);
1775 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1776 	if (c->single_connection) {
1777 		oerrno = errno;
1778 		debug2("single_connection: closing X11 listener.");
1779 		channel_close_fd(ssh, c, &c->sock);
1780 		chan_mark_dead(ssh, c);
1781 		errno = oerrno;
1782 	}
1783 	if (newsock == -1) {
1784 		if (errno != EINTR && errno != EWOULDBLOCK &&
1785 		    errno != ECONNABORTED)
1786 			error("accept: %.100s", strerror(errno));
1787 		if (errno == EMFILE || errno == ENFILE)
1788 			c->notbefore = monotime() + 1;
1789 		return;
1790 	}
1791 	set_nodelay(newsock);
1792 	remote_ipaddr = get_peer_ipaddr(newsock);
1793 	remote_port = get_peer_port(newsock);
1794 	snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1795 	    remote_ipaddr, remote_port);
1796 
1797 	nc = channel_new(ssh, "x11-connection",
1798 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1799 	    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1800 	open_preamble(ssh, __func__, nc, "x11");
1801 	if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1802 	    (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1803 		fatal_fr(r, "channel %i: reply", c->self);
1804 	}
1805 	if ((r = sshpkt_send(ssh)) != 0)
1806 		fatal_fr(r, "channel %i: send", c->self);
1807 	free(remote_ipaddr);
1808 }
1809 
1810 static void
1811 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1812 {
1813 	char *local_ipaddr = get_local_ipaddr(c->sock);
1814 	int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1815 	char *remote_ipaddr = get_peer_ipaddr(c->sock);
1816 	int remote_port = get_peer_port(c->sock);
1817 	int r;
1818 
1819 	if (remote_port == -1) {
1820 		/* Fake addr/port to appease peers that validate it (Tectia) */
1821 		free(remote_ipaddr);
1822 		remote_ipaddr = xstrdup("127.0.0.1");
1823 		remote_port = 65535;
1824 	}
1825 
1826 	free(c->remote_name);
1827 	xasprintf(&c->remote_name,
1828 	    "%s: listening port %d for %.100s port %d, "
1829 	    "connect from %.200s port %d to %.100s port %d",
1830 	    rtype, c->listening_port, c->path, c->host_port,
1831 	    remote_ipaddr, remote_port, local_ipaddr, local_port);
1832 
1833 	open_preamble(ssh, __func__, c, rtype);
1834 	if (strcmp(rtype, "direct-tcpip") == 0) {
1835 		/* target host, port */
1836 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1837 		    (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1838 			fatal_fr(r, "channel %i: reply", c->self);
1839 	} else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1840 		/* target path */
1841 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1842 			fatal_fr(r, "channel %i: reply", c->self);
1843 	} else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1844 		/* listen path */
1845 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1846 			fatal_fr(r, "channel %i: reply", c->self);
1847 	} else {
1848 		/* listen address, port */
1849 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1850 		    (r = sshpkt_put_u32(ssh, local_port)) != 0)
1851 			fatal_fr(r, "channel %i: reply", c->self);
1852 	}
1853 	if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1854 		/* reserved for future owner/mode info */
1855 		if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1856 			fatal_fr(r, "channel %i: reply", c->self);
1857 	} else {
1858 		/* originator host and port */
1859 		if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1860 		    (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1861 			fatal_fr(r, "channel %i: reply", c->self);
1862 	}
1863 	if ((r = sshpkt_send(ssh)) != 0)
1864 		fatal_fr(r, "channel %i: send", c->self);
1865 	free(remote_ipaddr);
1866 	free(local_ipaddr);
1867 }
1868 
1869 void
1870 channel_set_x11_refuse_time(struct ssh *ssh, time_t refuse_time)
1871 {
1872 	ssh->chanctxt->x11_refuse_time = refuse_time;
1873 }
1874 
1875 /*
1876  * This socket is listening for connections to a forwarded TCP/IP port.
1877  */
1878 static void
1879 channel_post_port_listener(struct ssh *ssh, Channel *c)
1880 {
1881 	Channel *nc;
1882 	struct sockaddr_storage addr;
1883 	int newsock, nextstate;
1884 	socklen_t addrlen;
1885 	char *rtype;
1886 
1887 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1888 		return;
1889 
1890 	debug("Connection to port %d forwarding to %.100s port %d requested.",
1891 	    c->listening_port, c->path, c->host_port);
1892 
1893 	if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1894 		nextstate = SSH_CHANNEL_OPENING;
1895 		rtype = "forwarded-tcpip";
1896 	} else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1897 		nextstate = SSH_CHANNEL_OPENING;
1898 		rtype = "forwarded-streamlocal@openssh.com";
1899 	} else if (c->host_port == PORT_STREAMLOCAL) {
1900 		nextstate = SSH_CHANNEL_OPENING;
1901 		rtype = "direct-streamlocal@openssh.com";
1902 	} else if (c->host_port == 0) {
1903 		nextstate = SSH_CHANNEL_DYNAMIC;
1904 		rtype = "dynamic-tcpip";
1905 	} else {
1906 		nextstate = SSH_CHANNEL_OPENING;
1907 		rtype = "direct-tcpip";
1908 	}
1909 
1910 	addrlen = sizeof(addr);
1911 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1912 	if (newsock == -1) {
1913 		if (errno != EINTR && errno != EWOULDBLOCK &&
1914 		    errno != ECONNABORTED)
1915 			error("accept: %.100s", strerror(errno));
1916 		if (errno == EMFILE || errno == ENFILE)
1917 			c->notbefore = monotime() + 1;
1918 		return;
1919 	}
1920 	if (c->host_port != PORT_STREAMLOCAL)
1921 		set_nodelay(newsock);
1922 	nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1923 	    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1924 	nc->listening_port = c->listening_port;
1925 	nc->host_port = c->host_port;
1926 	if (c->path != NULL)
1927 		nc->path = xstrdup(c->path);
1928 
1929 	if (nextstate != SSH_CHANNEL_DYNAMIC)
1930 		port_open_helper(ssh, nc, rtype);
1931 }
1932 
1933 /*
1934  * This is the authentication agent socket listening for connections from
1935  * clients.
1936  */
1937 static void
1938 channel_post_auth_listener(struct ssh *ssh, Channel *c)
1939 {
1940 	Channel *nc;
1941 	int r, newsock;
1942 	struct sockaddr_storage addr;
1943 	socklen_t addrlen;
1944 
1945 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1946 		return;
1947 
1948 	addrlen = sizeof(addr);
1949 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1950 	if (newsock == -1) {
1951 		error("accept from auth socket: %.100s", strerror(errno));
1952 		if (errno == EMFILE || errno == ENFILE)
1953 			c->notbefore = monotime() + 1;
1954 		return;
1955 	}
1956 	nc = channel_new(ssh, "agent-connection",
1957 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1958 	    c->local_window_max, c->local_maxpacket,
1959 	    0, "accepted auth socket", 1);
1960 	open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1961 	if ((r = sshpkt_send(ssh)) != 0)
1962 		fatal_fr(r, "channel %i", c->self);
1963 }
1964 
1965 static void
1966 channel_post_connecting(struct ssh *ssh, Channel *c)
1967 {
1968 	int err = 0, sock, isopen, r;
1969 	socklen_t sz = sizeof(err);
1970 
1971 	if ((c->io_ready & SSH_CHAN_IO_SOCK_W) == 0)
1972 		return;
1973 	if (!c->have_remote_id)
1974 		fatal_f("channel %d: no remote id", c->self);
1975 	/* for rdynamic the OPEN_CONFIRMATION has been sent already */
1976 	isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1977 
1978 	if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1979 		err = errno;
1980 		error("getsockopt SO_ERROR failed");
1981 	}
1982 
1983 	if (err == 0) {
1984 		/* Non-blocking connection completed */
1985 		debug("channel %d: connected to %s port %d",
1986 		    c->self, c->connect_ctx.host, c->connect_ctx.port);
1987 		channel_connect_ctx_free(&c->connect_ctx);
1988 		c->type = SSH_CHANNEL_OPEN;
1989 		c->lastused = monotime();
1990 		if (isopen) {
1991 			/* no message necessary */
1992 		} else {
1993 			if ((r = sshpkt_start(ssh,
1994 			    SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1995 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1996 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1997 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1998 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1999 			    (r = sshpkt_send(ssh)) != 0)
2000 				fatal_fr(r, "channel %i open confirm", c->self);
2001 		}
2002 		return;
2003 	}
2004 	if (err == EINTR || err == EAGAIN || err == EINPROGRESS)
2005 		return;
2006 
2007 	/* Non-blocking connection failed */
2008 	debug("channel %d: connection failed: %s", c->self, strerror(err));
2009 
2010 	/* Try next address, if any */
2011 	if ((sock = connect_next(&c->connect_ctx)) == -1) {
2012 		/* Exhausted all addresses for this destination */
2013 		error("connect_to %.100s port %d: failed.",
2014 		    c->connect_ctx.host, c->connect_ctx.port);
2015 		channel_connect_ctx_free(&c->connect_ctx);
2016 		if (isopen) {
2017 			rdynamic_close(ssh, c);
2018 		} else {
2019 			if ((r = sshpkt_start(ssh,
2020 			    SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
2021 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2022 			    (r = sshpkt_put_u32(ssh,
2023 			    SSH2_OPEN_CONNECT_FAILED)) != 0 ||
2024 			    (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
2025 			    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2026 			    (r = sshpkt_send(ssh)) != 0)
2027 				fatal_fr(r, "channel %i: failure", c->self);
2028 			chan_mark_dead(ssh, c);
2029 		}
2030 	}
2031 
2032 	/* New non-blocking connection in progress */
2033 	close(c->sock);
2034 	c->sock = c->rfd = c->wfd = sock;
2035 }
2036 
2037 static int
2038 channel_handle_rfd(struct ssh *ssh, Channel *c)
2039 {
2040 	char buf[CHAN_RBUF];
2041 	ssize_t len;
2042 	int r;
2043 	size_t nr = 0, have, avail, maxlen = CHANNEL_MAX_READ;
2044 
2045 	if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2046 		return 1; /* Shouldn't happen */
2047 	if ((avail = sshbuf_avail(c->input)) == 0)
2048 		return 1; /* Shouldn't happen */
2049 
2050 	/*
2051 	 * For "simple" channels (i.e. not datagram or filtered), we can
2052 	 * read directly to the channel buffer.
2053 	 */
2054 	if (c->input_filter == NULL && !c->datagram) {
2055 		/* Only OPEN channels have valid rwin */
2056 		if (c->type == SSH_CHANNEL_OPEN) {
2057 			if ((have = sshbuf_len(c->input)) >= c->remote_window)
2058 				return 1; /* shouldn't happen */
2059 			if (maxlen > c->remote_window - have)
2060 				maxlen = c->remote_window - have;
2061 		}
2062 		if (maxlen > avail)
2063 			maxlen = avail;
2064 		if ((r = sshbuf_read(c->rfd, c->input, maxlen, &nr)) != 0) {
2065 			if (errno == EINTR || errno == EAGAIN)
2066 				return 1;
2067 			debug2("channel %d: read failed rfd %d maxlen %zu: %s",
2068 			    c->self, c->rfd, maxlen, ssh_err(r));
2069 			goto rfail;
2070 		}
2071 		if (nr != 0)
2072 			c->lastused = monotime();
2073 		return 1;
2074 	}
2075 
2076 	len = read(c->rfd, buf, sizeof(buf));
2077 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2078 		return 1;
2079 	if (len <= 0) {
2080 		debug2("channel %d: read<=0 rfd %d len %zd: %s",
2081 		    c->self, c->rfd, len,
2082 		    len == 0 ? "closed" : strerror(errno));
2083  rfail:
2084 		if (c->type != SSH_CHANNEL_OPEN) {
2085 			debug2("channel %d: not open", c->self);
2086 			chan_mark_dead(ssh, c);
2087 			return -1;
2088 		} else {
2089 			chan_read_failed(ssh, c);
2090 		}
2091 		return -1;
2092 	}
2093 	c->lastused = monotime();
2094 	if (c->input_filter != NULL) {
2095 		if (c->input_filter(ssh, c, buf, len) == -1) {
2096 			debug2("channel %d: filter stops", c->self);
2097 			chan_read_failed(ssh, c);
2098 		}
2099 	} else if (c->datagram) {
2100 		if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
2101 			fatal_fr(r, "channel %i: put datagram", c->self);
2102 	}
2103 	return 1;
2104 }
2105 
2106 static int
2107 channel_handle_wfd(struct ssh *ssh, Channel *c)
2108 {
2109 	struct termios tio;
2110 	u_char *data = NULL, *buf; /* XXX const; need filter API change */
2111 	size_t dlen, olen = 0;
2112 	int r, len;
2113 
2114 	if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2115 		return 1;
2116 	if (sshbuf_len(c->output) == 0)
2117 		return 1;
2118 
2119 	/* Send buffered output data to the socket. */
2120 	olen = sshbuf_len(c->output);
2121 	if (c->output_filter != NULL) {
2122 		if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
2123 			debug2("channel %d: filter stops", c->self);
2124 			if (c->type != SSH_CHANNEL_OPEN)
2125 				chan_mark_dead(ssh, c);
2126 			else
2127 				chan_write_failed(ssh, c);
2128 			return -1;
2129 		}
2130 	} else if (c->datagram) {
2131 		if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2132 			fatal_fr(r, "channel %i: get datagram", c->self);
2133 		buf = data;
2134 	} else {
2135 		buf = data = sshbuf_mutable_ptr(c->output);
2136 		dlen = sshbuf_len(c->output);
2137 	}
2138 
2139 	if (c->datagram) {
2140 		/* ignore truncated writes, datagrams might get lost */
2141 		len = write(c->wfd, buf, dlen);
2142 		free(data);
2143 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
2144 			return 1;
2145 		if (len <= 0)
2146 			goto write_fail;
2147 		goto out;
2148 	}
2149 
2150 	len = write(c->wfd, buf, dlen);
2151 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2152 		return 1;
2153 	if (len <= 0) {
2154  write_fail:
2155 		if (c->type != SSH_CHANNEL_OPEN) {
2156 			debug2("channel %d: not open", c->self);
2157 			chan_mark_dead(ssh, c);
2158 			return -1;
2159 		} else {
2160 			chan_write_failed(ssh, c);
2161 		}
2162 		return -1;
2163 	}
2164 	c->lastused = monotime();
2165 	if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2166 		if (tcgetattr(c->wfd, &tio) == 0 &&
2167 		    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2168 			/*
2169 			 * Simulate echo to reduce the impact of
2170 			 * traffic analysis. We need to match the
2171 			 * size of a SSH2_MSG_CHANNEL_DATA message
2172 			 * (4 byte channel id + buf)
2173 			 */
2174 			if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2175 			    (r = sshpkt_send(ssh)) != 0)
2176 				fatal_fr(r, "channel %i: ignore", c->self);
2177 		}
2178 	}
2179 	if ((r = sshbuf_consume(c->output, len)) != 0)
2180 		fatal_fr(r, "channel %i: consume", c->self);
2181  out:
2182 	c->local_consumed += olen - sshbuf_len(c->output);
2183 
2184 	return 1;
2185 }
2186 
2187 static int
2188 channel_handle_efd_write(struct ssh *ssh, Channel *c)
2189 {
2190 	int r;
2191 	ssize_t len;
2192 
2193 	if ((c->io_ready & SSH_CHAN_IO_EFD_W) == 0)
2194 		return 1;
2195 	if (sshbuf_len(c->extended) == 0)
2196 		return 1;
2197 
2198 	len = write(c->efd, sshbuf_ptr(c->extended),
2199 	    sshbuf_len(c->extended));
2200 	debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2201 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2202 		return 1;
2203 	if (len <= 0) {
2204 		debug2("channel %d: closing write-efd %d", c->self, c->efd);
2205 		channel_close_fd(ssh, c, &c->efd);
2206 	} else {
2207 		if ((r = sshbuf_consume(c->extended, len)) != 0)
2208 			fatal_fr(r, "channel %i: consume", c->self);
2209 		c->local_consumed += len;
2210 		c->lastused = monotime();
2211 	}
2212 	return 1;
2213 }
2214 
2215 static int
2216 channel_handle_efd_read(struct ssh *ssh, Channel *c)
2217 {
2218 	char buf[CHAN_RBUF];
2219 	int r;
2220 	ssize_t len;
2221 
2222 	if ((c->io_ready & SSH_CHAN_IO_EFD_R) == 0)
2223 		return 1;
2224 
2225 	len = read(c->efd, buf, sizeof(buf));
2226 	debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2227 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2228 		return 1;
2229 	if (len <= 0) {
2230 		debug2("channel %d: closing read-efd %d", c->self, c->efd);
2231 		channel_close_fd(ssh, c, &c->efd);
2232 		return 1;
2233 	}
2234 	c->lastused = monotime();
2235 	if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2236 		debug3("channel %d: discard efd", c->self);
2237 	else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2238 		fatal_fr(r, "channel %i: append", c->self);
2239 	return 1;
2240 }
2241 
2242 static int
2243 channel_handle_efd(struct ssh *ssh, Channel *c)
2244 {
2245 	if (c->efd == -1)
2246 		return 1;
2247 
2248 	/** XXX handle drain efd, too */
2249 
2250 	if (c->extended_usage == CHAN_EXTENDED_WRITE)
2251 		return channel_handle_efd_write(ssh, c);
2252 	else if (c->extended_usage == CHAN_EXTENDED_READ ||
2253 	    c->extended_usage == CHAN_EXTENDED_IGNORE)
2254 		return channel_handle_efd_read(ssh, c);
2255 
2256 	return 1;
2257 }
2258 
2259 static int
2260 channel_check_window(struct ssh *ssh, Channel *c)
2261 {
2262 	int r;
2263 
2264 	if (c->type == SSH_CHANNEL_OPEN &&
2265 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2266 	    ((c->local_window_max - c->local_window >
2267 	    c->local_maxpacket*3) ||
2268 	    c->local_window < c->local_window_max/2) &&
2269 	    c->local_consumed > 0) {
2270 		if (!c->have_remote_id)
2271 			fatal_f("channel %d: no remote id", c->self);
2272 		if ((r = sshpkt_start(ssh,
2273 		    SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2274 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2275 		    (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2276 		    (r = sshpkt_send(ssh)) != 0) {
2277 			fatal_fr(r, "channel %i", c->self);
2278 		}
2279 		debug2("channel %d: window %d sent adjust %d", c->self,
2280 		    c->local_window, c->local_consumed);
2281 		c->local_window += c->local_consumed;
2282 		c->local_consumed = 0;
2283 	}
2284 	return 1;
2285 }
2286 
2287 static void
2288 channel_post_open(struct ssh *ssh, Channel *c)
2289 {
2290 	channel_handle_rfd(ssh, c);
2291 	channel_handle_wfd(ssh, c);
2292 	channel_handle_efd(ssh, c);
2293 	channel_check_window(ssh, c);
2294 }
2295 
2296 static u_int
2297 read_mux(struct ssh *ssh, Channel *c, u_int need)
2298 {
2299 	char buf[CHAN_RBUF];
2300 	ssize_t len;
2301 	u_int rlen;
2302 	int r;
2303 
2304 	if (sshbuf_len(c->input) < need) {
2305 		rlen = need - sshbuf_len(c->input);
2306 		len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2307 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
2308 			return sshbuf_len(c->input);
2309 		if (len <= 0) {
2310 			debug2("channel %d: ctl read<=0 rfd %d len %zd",
2311 			    c->self, c->rfd, len);
2312 			chan_read_failed(ssh, c);
2313 			return 0;
2314 		} else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2315 			fatal_fr(r, "channel %i: append", c->self);
2316 	}
2317 	return sshbuf_len(c->input);
2318 }
2319 
2320 static void
2321 channel_post_mux_client_read(struct ssh *ssh, Channel *c)
2322 {
2323 	u_int need;
2324 
2325 	if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2326 		return;
2327 	if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2328 		return;
2329 	if (c->mux_pause)
2330 		return;
2331 
2332 	/*
2333 	 * Don't not read past the precise end of packets to
2334 	 * avoid disrupting fd passing.
2335 	 */
2336 	if (read_mux(ssh, c, 4) < 4) /* read header */
2337 		return;
2338 	/* XXX sshbuf_peek_u32 */
2339 	need = PEEK_U32(sshbuf_ptr(c->input));
2340 #define CHANNEL_MUX_MAX_PACKET	(256 * 1024)
2341 	if (need > CHANNEL_MUX_MAX_PACKET) {
2342 		debug2("channel %d: packet too big %u > %u",
2343 		    c->self, CHANNEL_MUX_MAX_PACKET, need);
2344 		chan_rcvd_oclose(ssh, c);
2345 		return;
2346 	}
2347 	if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2348 		return;
2349 	if (c->mux_rcb(ssh, c) != 0) {
2350 		debug("channel %d: mux_rcb failed", c->self);
2351 		chan_mark_dead(ssh, c);
2352 		return;
2353 	}
2354 }
2355 
2356 static void
2357 channel_post_mux_client_write(struct ssh *ssh, Channel *c)
2358 {
2359 	ssize_t len;
2360 	int r;
2361 
2362 	if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2363 		return;
2364 	if (sshbuf_len(c->output) == 0)
2365 		return;
2366 
2367 	len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2368 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2369 		return;
2370 	if (len <= 0) {
2371 		chan_mark_dead(ssh, c);
2372 		return;
2373 	}
2374 	if ((r = sshbuf_consume(c->output, len)) != 0)
2375 		fatal_fr(r, "channel %i: consume", c->self);
2376 }
2377 
2378 static void
2379 channel_post_mux_client(struct ssh *ssh, Channel *c)
2380 {
2381 	channel_post_mux_client_read(ssh, c);
2382 	channel_post_mux_client_write(ssh, c);
2383 }
2384 
2385 static void
2386 channel_post_mux_listener(struct ssh *ssh, Channel *c)
2387 {
2388 	Channel *nc;
2389 	struct sockaddr_storage addr;
2390 	socklen_t addrlen;
2391 	int newsock;
2392 	uid_t euid;
2393 	gid_t egid;
2394 
2395 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
2396 		return;
2397 
2398 	debug("multiplexing control connection");
2399 
2400 	/*
2401 	 * Accept connection on control socket
2402 	 */
2403 	memset(&addr, 0, sizeof(addr));
2404 	addrlen = sizeof(addr);
2405 	if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2406 	    &addrlen)) == -1) {
2407 		error_f("accept: %s", strerror(errno));
2408 		if (errno == EMFILE || errno == ENFILE)
2409 			c->notbefore = monotime() + 1;
2410 		return;
2411 	}
2412 
2413 	if (getpeereid(newsock, &euid, &egid) == -1) {
2414 		error_f("getpeereid failed: %s", strerror(errno));
2415 		close(newsock);
2416 		return;
2417 	}
2418 	if ((euid != 0) && (getuid() != euid)) {
2419 		error("multiplex uid mismatch: peer euid %u != uid %u",
2420 		    (u_int)euid, (u_int)getuid());
2421 		close(newsock);
2422 		return;
2423 	}
2424 	nc = channel_new(ssh, "mux-control", SSH_CHANNEL_MUX_CLIENT,
2425 	    newsock, newsock, -1, c->local_window_max,
2426 	    c->local_maxpacket, 0, "mux-control", 1);
2427 	nc->mux_rcb = c->mux_rcb;
2428 	debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2429 	/* establish state */
2430 	nc->mux_rcb(ssh, nc);
2431 	/* mux state transitions must not elicit protocol messages */
2432 	nc->flags |= CHAN_LOCAL;
2433 }
2434 
2435 static void
2436 channel_handler_init(struct ssh_channels *sc)
2437 {
2438 	chan_fn **pre, **post;
2439 
2440 	if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2441 	    (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2442 		fatal_f("allocation failed");
2443 
2444 	pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
2445 	pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
2446 	pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
2447 	pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
2448 	pre[SSH_CHANNEL_UNIX_LISTENER] =	&channel_pre_listener;
2449 	pre[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_pre_listener;
2450 	pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
2451 	pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
2452 	pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
2453 	pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
2454 	pre[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_pre_connecting;
2455 	pre[SSH_CHANNEL_MUX_LISTENER] =		&channel_pre_listener;
2456 	pre[SSH_CHANNEL_MUX_CLIENT] =		&channel_pre_mux_client;
2457 
2458 	post[SSH_CHANNEL_OPEN] =		&channel_post_open;
2459 	post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
2460 	post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
2461 	post[SSH_CHANNEL_UNIX_LISTENER] =	&channel_post_port_listener;
2462 	post[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_post_port_listener;
2463 	post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
2464 	post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
2465 	post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
2466 	post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
2467 	post[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_post_connecting;
2468 	post[SSH_CHANNEL_MUX_LISTENER] =	&channel_post_mux_listener;
2469 	post[SSH_CHANNEL_MUX_CLIENT] =		&channel_post_mux_client;
2470 
2471 	sc->channel_pre = pre;
2472 	sc->channel_post = post;
2473 }
2474 
2475 /* gc dead channels */
2476 static void
2477 channel_garbage_collect(struct ssh *ssh, Channel *c)
2478 {
2479 	if (c == NULL)
2480 		return;
2481 	if (c->detach_user != NULL) {
2482 		if (!chan_is_dead(ssh, c, c->detach_close))
2483 			return;
2484 
2485 		debug2("channel %d: gc: notify user", c->self);
2486 		c->detach_user(ssh, c->self, 0, NULL);
2487 		/* if we still have a callback */
2488 		if (c->detach_user != NULL)
2489 			return;
2490 		debug2("channel %d: gc: user detached", c->self);
2491 	}
2492 	if (!chan_is_dead(ssh, c, 1))
2493 		return;
2494 	debug2("channel %d: garbage collecting", c->self);
2495 	channel_free(ssh, c);
2496 }
2497 
2498 enum channel_table { CHAN_PRE, CHAN_POST };
2499 
2500 static void
2501 channel_handler(struct ssh *ssh, int table, struct timespec *timeout)
2502 {
2503 	struct ssh_channels *sc = ssh->chanctxt;
2504 	chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2505 	u_int i, oalloc;
2506 	Channel *c;
2507 	time_t now;
2508 
2509 	now = monotime();
2510 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2511 		c = sc->channels[i];
2512 		if (c == NULL)
2513 			continue;
2514 		/* Try to keep IO going while rekeying */
2515 		if (ssh_packet_is_rekeying(ssh) && c->type != SSH_CHANNEL_OPEN)
2516 			continue;
2517 		if (c->delayed) {
2518 			if (table == CHAN_PRE)
2519 				c->delayed = 0;
2520 			else
2521 				continue;
2522 		}
2523 		if (ftab[c->type] != NULL) {
2524 			if (table == CHAN_PRE &&
2525 			    c->type == SSH_CHANNEL_OPEN &&
2526 			    c->inactive_deadline != 0 && c->lastused != 0 &&
2527 			    now >= c->lastused + c->inactive_deadline) {
2528 				/* channel closed for inactivity */
2529 				verbose("channel %d: closing after %u seconds "
2530 				    "of inactivity", c->self,
2531 				    c->inactive_deadline);
2532 				channel_force_close(ssh, c, 1);
2533 			} else if (c->notbefore <= now) {
2534 				/* Run handlers that are not paused. */
2535 				(*ftab[c->type])(ssh, c);
2536 				/* inactivity timeouts must interrupt poll() */
2537 				if (timeout != NULL &&
2538 				    c->type == SSH_CHANNEL_OPEN &&
2539 				    c->lastused != 0 &&
2540 				    c->inactive_deadline != 0) {
2541 					ptimeout_deadline_monotime(timeout,
2542 					    c->lastused + c->inactive_deadline);
2543 				}
2544 			} else if (timeout != NULL) {
2545 				/*
2546 				 * Arrange for poll() wakeup when channel pause
2547 				 * timer expires.
2548 				 */
2549 				ptimeout_deadline_monotime(timeout,
2550 				    c->notbefore);
2551 			}
2552 		}
2553 		channel_garbage_collect(ssh, c);
2554 	}
2555 }
2556 
2557 /*
2558  * Create sockets before preparing IO.
2559  * This is necessary for things that need to happen after reading
2560  * the network-input but need to be completed before IO event setup, e.g.
2561  * because they may create new channels.
2562  */
2563 static void
2564 channel_before_prepare_io(struct ssh *ssh)
2565 {
2566 	struct ssh_channels *sc = ssh->chanctxt;
2567 	Channel *c;
2568 	u_int i, oalloc;
2569 
2570 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2571 		c = sc->channels[i];
2572 		if (c == NULL)
2573 			continue;
2574 		if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2575 			channel_before_prepare_io_rdynamic(ssh, c);
2576 	}
2577 }
2578 
2579 static void
2580 dump_channel_poll(const char *func, const char *what, Channel *c,
2581     u_int pollfd_offset, struct pollfd *pfd)
2582 {
2583 #ifdef DEBUG_CHANNEL_POLL
2584 	debug3("%s: channel %d: %s r%d w%d e%d s%d c->pfds [ %d %d %d %d ] "
2585 	    "io_want 0x%02x io_ready 0x%02x pfd[%u].fd=%d "
2586 	    "pfd.ev 0x%02x pfd.rev 0x%02x", func, c->self, what,
2587 	    c->rfd, c->wfd, c->efd, c->sock,
2588 	    c->pfds[0], c->pfds[1], c->pfds[2], c->pfds[3],
2589 	    c->io_want, c->io_ready,
2590 	    pollfd_offset, pfd->fd, pfd->events, pfd->revents);
2591 #endif
2592 }
2593 
2594 /* Prepare pollfd entries for a single channel */
2595 static void
2596 channel_prepare_pollfd(Channel *c, u_int *next_pollfd,
2597     struct pollfd *pfd, u_int npfd)
2598 {
2599 	u_int ev, p = *next_pollfd;
2600 
2601 	if (c == NULL)
2602 		return;
2603 	if (p + 4 > npfd) {
2604 		/* Shouldn't happen */
2605 		fatal_f("channel %d: bad pfd offset %u (max %u)",
2606 		    c->self, p, npfd);
2607 	}
2608 	c->pfds[0] = c->pfds[1] = c->pfds[2] = c->pfds[3] = -1;
2609 	/*
2610 	 * prepare c->rfd
2611 	 *
2612 	 * This is a special case, since c->rfd might be the same as
2613 	 * c->wfd, c->efd and/or c->sock. Handle those here if they want
2614 	 * IO too.
2615 	 */
2616 	if (c->rfd != -1) {
2617 		ev = 0;
2618 		if ((c->io_want & SSH_CHAN_IO_RFD) != 0)
2619 			ev |= POLLIN;
2620 		/* rfd == wfd */
2621 		if (c->wfd == c->rfd) {
2622 			if ((c->io_want & SSH_CHAN_IO_WFD) != 0)
2623 				ev |= POLLOUT;
2624 		}
2625 		/* rfd == efd */
2626 		if (c->efd == c->rfd) {
2627 			if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2628 				ev |= POLLIN;
2629 			if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2630 				ev |= POLLOUT;
2631 		}
2632 		/* rfd == sock */
2633 		if (c->sock == c->rfd) {
2634 			if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2635 				ev |= POLLIN;
2636 			if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2637 				ev |= POLLOUT;
2638 		}
2639 		/* Pack a pfd entry if any event armed for this fd */
2640 		if (ev != 0) {
2641 			c->pfds[0] = p;
2642 			pfd[p].fd = c->rfd;
2643 			pfd[p].events = ev;
2644 			dump_channel_poll(__func__, "rfd", c, p, &pfd[p]);
2645 			p++;
2646 		}
2647 	}
2648 	/* prepare c->wfd if wanting IO and not already handled above */
2649 	if (c->wfd != -1 && c->rfd != c->wfd) {
2650 		ev = 0;
2651 		if ((c->io_want & SSH_CHAN_IO_WFD))
2652 			ev |= POLLOUT;
2653 		/* Pack a pfd entry if any event armed for this fd */
2654 		if (ev != 0) {
2655 			c->pfds[1] = p;
2656 			pfd[p].fd = c->wfd;
2657 			pfd[p].events = ev;
2658 			dump_channel_poll(__func__, "wfd", c, p, &pfd[p]);
2659 			p++;
2660 		}
2661 	}
2662 	/* prepare c->efd if wanting IO and not already handled above */
2663 	if (c->efd != -1 && c->rfd != c->efd) {
2664 		ev = 0;
2665 		if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2666 			ev |= POLLIN;
2667 		if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2668 			ev |= POLLOUT;
2669 		/* Pack a pfd entry if any event armed for this fd */
2670 		if (ev != 0) {
2671 			c->pfds[2] = p;
2672 			pfd[p].fd = c->efd;
2673 			pfd[p].events = ev;
2674 			dump_channel_poll(__func__, "efd", c, p, &pfd[p]);
2675 			p++;
2676 		}
2677 	}
2678 	/* prepare c->sock if wanting IO and not already handled above */
2679 	if (c->sock != -1 && c->rfd != c->sock) {
2680 		ev = 0;
2681 		if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2682 			ev |= POLLIN;
2683 		if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2684 			ev |= POLLOUT;
2685 		/* Pack a pfd entry if any event armed for this fd */
2686 		if (ev != 0) {
2687 			c->pfds[3] = p;
2688 			pfd[p].fd = c->sock;
2689 			pfd[p].events = 0;
2690 			dump_channel_poll(__func__, "sock", c, p, &pfd[p]);
2691 			p++;
2692 		}
2693 	}
2694 	*next_pollfd = p;
2695 }
2696 
2697 /* * Allocate/prepare poll structure */
2698 void
2699 channel_prepare_poll(struct ssh *ssh, struct pollfd **pfdp, u_int *npfd_allocp,
2700     u_int *npfd_activep, u_int npfd_reserved, struct timespec *timeout)
2701 {
2702 	struct ssh_channels *sc = ssh->chanctxt;
2703 	u_int i, oalloc, p, npfd = npfd_reserved;
2704 
2705 	channel_before_prepare_io(ssh); /* might create a new channel */
2706 	/* clear out I/O flags from last poll */
2707 	for (i = 0; i < sc->channels_alloc; i++) {
2708 		if (sc->channels[i] == NULL)
2709 			continue;
2710 		sc->channels[i]->io_want = sc->channels[i]->io_ready = 0;
2711 	}
2712 	/* Allocate 4x pollfd for each channel (rfd, wfd, efd, sock) */
2713 	if (sc->channels_alloc >= (INT_MAX / 4) - npfd_reserved)
2714 		fatal_f("too many channels"); /* shouldn't happen */
2715 	npfd += sc->channels_alloc * 4;
2716 	if (npfd > *npfd_allocp) {
2717 		*pfdp = xrecallocarray(*pfdp, *npfd_allocp,
2718 		    npfd, sizeof(**pfdp));
2719 		*npfd_allocp = npfd;
2720 	}
2721 	*npfd_activep = npfd_reserved;
2722 	oalloc = sc->channels_alloc;
2723 
2724 	channel_handler(ssh, CHAN_PRE, timeout);
2725 
2726 	if (oalloc != sc->channels_alloc) {
2727 		/* shouldn't happen */
2728 		fatal_f("channels_alloc changed during CHAN_PRE "
2729 		    "(was %u, now %u)", oalloc, sc->channels_alloc);
2730 	}
2731 
2732 	/* Prepare pollfd */
2733 	p = npfd_reserved;
2734 	for (i = 0; i < sc->channels_alloc; i++)
2735 		channel_prepare_pollfd(sc->channels[i], &p, *pfdp, npfd);
2736 	*npfd_activep = p;
2737 }
2738 
2739 static void
2740 fd_ready(Channel *c, int p, struct pollfd *pfds, u_int npfd, int fd,
2741     const char *what, u_int revents_mask, u_int ready)
2742 {
2743 	struct pollfd *pfd = &pfds[p];
2744 
2745 	if (fd == -1)
2746 		return;
2747 	if (p == -1 || (u_int)p >= npfd)
2748 		fatal_f("channel %d: bad pfd %d (max %u)", c->self, p, npfd);
2749 	dump_channel_poll(__func__, what, c, p, pfd);
2750 	if (pfd->fd != fd) {
2751 		fatal("channel %d: inconsistent %s fd=%d pollfd[%u].fd %d "
2752 		    "r%d w%d e%d s%d", c->self, what, fd, p, pfd->fd,
2753 		    c->rfd, c->wfd, c->efd, c->sock);
2754 	}
2755 	if ((pfd->revents & POLLNVAL) != 0) {
2756 		fatal("channel %d: invalid %s pollfd[%u].fd %d r%d w%d e%d s%d",
2757 		    c->self, what, p, pfd->fd, c->rfd, c->wfd, c->efd, c->sock);
2758 	}
2759 	if ((pfd->revents & (revents_mask|POLLHUP|POLLERR)) != 0)
2760 		c->io_ready |= ready & c->io_want;
2761 }
2762 
2763 /*
2764  * After poll, perform any appropriate operations for channels which have
2765  * events pending.
2766  */
2767 void
2768 channel_after_poll(struct ssh *ssh, struct pollfd *pfd, u_int npfd)
2769 {
2770 	struct ssh_channels *sc = ssh->chanctxt;
2771 	u_int i;
2772 	int p;
2773 	Channel *c;
2774 
2775 #ifdef DEBUG_CHANNEL_POLL
2776 	for (p = 0; p < (int)npfd; p++) {
2777 		if (pfd[p].revents == 0)
2778 			continue;
2779 		debug_f("pfd[%u].fd %d rev 0x%04x",
2780 		    p, pfd[p].fd, pfd[p].revents);
2781 	}
2782 #endif
2783 
2784 	/* Convert pollfd into c->io_ready */
2785 	for (i = 0; i < sc->channels_alloc; i++) {
2786 		c = sc->channels[i];
2787 		if (c == NULL)
2788 			continue;
2789 		/* if rfd is shared with efd/sock then wfd should be too */
2790 		if (c->rfd != -1 && c->wfd != -1 && c->rfd != c->wfd &&
2791 		    (c->rfd == c->efd || c->rfd == c->sock)) {
2792 			/* Shouldn't happen */
2793 			fatal_f("channel %d: unexpected fds r%d w%d e%d s%d",
2794 			    c->self, c->rfd, c->wfd, c->efd, c->sock);
2795 		}
2796 		c->io_ready = 0;
2797 		/* rfd, potentially shared with wfd, efd and sock */
2798 		if (c->rfd != -1 && (p = c->pfds[0]) != -1) {
2799 			fd_ready(c, p, pfd, npfd, c->rfd,
2800 			    "rfd", POLLIN, SSH_CHAN_IO_RFD);
2801 			if (c->rfd == c->wfd) {
2802 				fd_ready(c, p, pfd, npfd, c->wfd,
2803 				    "wfd/r", POLLOUT, SSH_CHAN_IO_WFD);
2804 			}
2805 			if (c->rfd == c->efd) {
2806 				fd_ready(c, p, pfd, npfd, c->efd,
2807 				    "efdr/r", POLLIN, SSH_CHAN_IO_EFD_R);
2808 				fd_ready(c, p, pfd, npfd, c->efd,
2809 				    "efdw/r", POLLOUT, SSH_CHAN_IO_EFD_W);
2810 			}
2811 			if (c->rfd == c->sock) {
2812 				fd_ready(c, p, pfd, npfd, c->sock,
2813 				    "sockr/r", POLLIN, SSH_CHAN_IO_SOCK_R);
2814 				fd_ready(c, p, pfd, npfd, c->sock,
2815 				    "sockw/r", POLLOUT, SSH_CHAN_IO_SOCK_W);
2816 			}
2817 			dump_channel_poll(__func__, "rfd", c, p, pfd);
2818 		}
2819 		/* wfd */
2820 		if (c->wfd != -1 && c->wfd != c->rfd &&
2821 		    (p = c->pfds[1]) != -1) {
2822 			fd_ready(c, p, pfd, npfd, c->wfd,
2823 			    "wfd", POLLOUT, SSH_CHAN_IO_WFD);
2824 			dump_channel_poll(__func__, "wfd", c, p, pfd);
2825 		}
2826 		/* efd */
2827 		if (c->efd != -1 && c->efd != c->rfd &&
2828 		    (p = c->pfds[2]) != -1) {
2829 			fd_ready(c, p, pfd, npfd, c->efd,
2830 			    "efdr", POLLIN, SSH_CHAN_IO_EFD_R);
2831 			fd_ready(c, p, pfd, npfd, c->efd,
2832 			    "efdw", POLLOUT, SSH_CHAN_IO_EFD_W);
2833 			dump_channel_poll(__func__, "efd", c, p, pfd);
2834 		}
2835 		/* sock */
2836 		if (c->sock != -1 && c->sock != c->rfd &&
2837 		    (p = c->pfds[3]) != -1) {
2838 			fd_ready(c, p, pfd, npfd, c->sock,
2839 			    "sockr", POLLIN, SSH_CHAN_IO_SOCK_R);
2840 			fd_ready(c, p, pfd, npfd, c->sock,
2841 			    "sockw", POLLOUT, SSH_CHAN_IO_SOCK_W);
2842 			dump_channel_poll(__func__, "sock", c, p, pfd);
2843 		}
2844 	}
2845 	channel_handler(ssh, CHAN_POST, NULL);
2846 }
2847 
2848 /*
2849  * Enqueue data for channels with open or draining c->input.
2850  */
2851 static void
2852 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2853 {
2854 	size_t len, plen;
2855 	const u_char *pkt;
2856 	int r;
2857 
2858 	if ((len = sshbuf_len(c->input)) == 0) {
2859 		if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2860 			/*
2861 			 * input-buffer is empty and read-socket shutdown:
2862 			 * tell peer, that we will not send more data:
2863 			 * send IEOF.
2864 			 * hack for extended data: delay EOF if EFD still
2865 			 * in use.
2866 			 */
2867 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
2868 				debug2("channel %d: "
2869 				    "ibuf_empty delayed efd %d/(%zu)",
2870 				    c->self, c->efd, sshbuf_len(c->extended));
2871 			else
2872 				chan_ibuf_empty(ssh, c);
2873 		}
2874 		return;
2875 	}
2876 
2877 	if (!c->have_remote_id)
2878 		fatal_f("channel %d: no remote id", c->self);
2879 
2880 	if (c->datagram) {
2881 		/* Check datagram will fit; drop if not */
2882 		if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2883 			fatal_fr(r, "channel %i: get datagram", c->self);
2884 		/*
2885 		 * XXX this does tail-drop on the datagram queue which is
2886 		 * usually suboptimal compared to head-drop. Better to have
2887 		 * backpressure at read time? (i.e. read + discard)
2888 		 */
2889 		if (plen > c->remote_window || plen > c->remote_maxpacket) {
2890 			debug("channel %d: datagram too big", c->self);
2891 			return;
2892 		}
2893 		/* Enqueue it */
2894 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2895 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2896 		    (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2897 		    (r = sshpkt_send(ssh)) != 0)
2898 			fatal_fr(r, "channel %i: send datagram", c->self);
2899 		c->remote_window -= plen;
2900 		return;
2901 	}
2902 
2903 	/* Enqueue packet for buffered data. */
2904 	if (len > c->remote_window)
2905 		len = c->remote_window;
2906 	if (len > c->remote_maxpacket)
2907 		len = c->remote_maxpacket;
2908 	if (len == 0)
2909 		return;
2910 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2911 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2912 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2913 	    (r = sshpkt_send(ssh)) != 0)
2914 		fatal_fr(r, "channel %i: send data", c->self);
2915 	if ((r = sshbuf_consume(c->input, len)) != 0)
2916 		fatal_fr(r, "channel %i: consume", c->self);
2917 	c->remote_window -= len;
2918 }
2919 
2920 /*
2921  * Enqueue data for channels with open c->extended in read mode.
2922  */
2923 static void
2924 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2925 {
2926 	size_t len;
2927 	int r;
2928 
2929 	if ((len = sshbuf_len(c->extended)) == 0)
2930 		return;
2931 
2932 	debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2933 	    c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2934 	if (len > c->remote_window)
2935 		len = c->remote_window;
2936 	if (len > c->remote_maxpacket)
2937 		len = c->remote_maxpacket;
2938 	if (len == 0)
2939 		return;
2940 	if (!c->have_remote_id)
2941 		fatal_f("channel %d: no remote id", c->self);
2942 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2943 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2944 	    (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2945 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2946 	    (r = sshpkt_send(ssh)) != 0)
2947 		fatal_fr(r, "channel %i: data", c->self);
2948 	if ((r = sshbuf_consume(c->extended, len)) != 0)
2949 		fatal_fr(r, "channel %i: consume", c->self);
2950 	c->remote_window -= len;
2951 	debug2("channel %d: sent ext data %zu", c->self, len);
2952 }
2953 
2954 /* If there is data to send to the connection, enqueue some of it now. */
2955 void
2956 channel_output_poll(struct ssh *ssh)
2957 {
2958 	struct ssh_channels *sc = ssh->chanctxt;
2959 	Channel *c;
2960 	u_int i;
2961 
2962 	for (i = 0; i < sc->channels_alloc; i++) {
2963 		c = sc->channels[i];
2964 		if (c == NULL)
2965 			continue;
2966 
2967 		/*
2968 		 * We are only interested in channels that can have buffered
2969 		 * incoming data.
2970 		 */
2971 		if (c->type != SSH_CHANNEL_OPEN)
2972 			continue;
2973 		if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2974 			/* XXX is this true? */
2975 			debug3("channel %d: will not send data after close",
2976 			    c->self);
2977 			continue;
2978 		}
2979 
2980 		/* Get the amount of buffered data for this channel. */
2981 		if (c->istate == CHAN_INPUT_OPEN ||
2982 		    c->istate == CHAN_INPUT_WAIT_DRAIN)
2983 			channel_output_poll_input_open(ssh, c);
2984 		/* Send extended data, i.e. stderr */
2985 		if (!(c->flags & CHAN_EOF_SENT) &&
2986 		    c->extended_usage == CHAN_EXTENDED_READ)
2987 			channel_output_poll_extended_read(ssh, c);
2988 	}
2989 }
2990 
2991 /* -- mux proxy support  */
2992 
2993 /*
2994  * When multiplexing channel messages for mux clients we have to deal
2995  * with downstream messages from the mux client and upstream messages
2996  * from the ssh server:
2997  * 1) Handling downstream messages is straightforward and happens
2998  *    in channel_proxy_downstream():
2999  *    - We forward all messages (mostly) unmodified to the server.
3000  *    - However, in order to route messages from upstream to the correct
3001  *      downstream client, we have to replace the channel IDs used by the
3002  *      mux clients with a unique channel ID because the mux clients might
3003  *      use conflicting channel IDs.
3004  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
3005  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
3006  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
3007  *      with the newly allocated channel ID.
3008  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
3009  *    channels and processed by channel_proxy_upstream(). The local channel ID
3010  *    is then translated back to the original mux client ID.
3011  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
3012  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
3013  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
3014  *    downstream mux client are removed.
3015  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
3016  *    requires more work, because they are not addressed to a specific
3017  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
3018  *    out whether the request is addressed to the local client or a
3019  *    specific downstream client based on the listen-address/port.
3020  * 6) Agent and X11-Forwarding have a similar problem and are currently
3021  *    not supported as the matching session/channel cannot be identified
3022  *    easily.
3023  */
3024 
3025 /*
3026  * receive packets from downstream mux clients:
3027  * channel callback fired on read from mux client, creates
3028  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
3029  * on channel creation.
3030  */
3031 int
3032 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
3033 {
3034 	Channel *c = NULL;
3035 	struct sshbuf *original = NULL, *modified = NULL;
3036 	const u_char *cp;
3037 	char *ctype = NULL, *listen_host = NULL;
3038 	u_char type;
3039 	size_t have;
3040 	int ret = -1, r;
3041 	u_int id, remote_id, listen_port;
3042 
3043 	/* sshbuf_dump(downstream->input, stderr); */
3044 	if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
3045 	    != 0) {
3046 		error_fr(r, "parse");
3047 		return -1;
3048 	}
3049 	if (have < 2) {
3050 		error_f("short message");
3051 		return -1;
3052 	}
3053 	type = cp[1];
3054 	/* skip padlen + type */
3055 	cp += 2;
3056 	have -= 2;
3057 	if (ssh_packet_log_type(type))
3058 		debug3_f("channel %u: down->up: type %u",
3059 		    downstream->self, type);
3060 
3061 	switch (type) {
3062 	case SSH2_MSG_CHANNEL_OPEN:
3063 		if ((original = sshbuf_from(cp, have)) == NULL ||
3064 		    (modified = sshbuf_new()) == NULL) {
3065 			error_f("alloc");
3066 			goto out;
3067 		}
3068 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
3069 		    (r = sshbuf_get_u32(original, &id)) != 0) {
3070 			error_fr(r, "parse");
3071 			goto out;
3072 		}
3073 		c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3074 		    -1, -1, -1, 0, 0, 0, ctype, 1);
3075 		c->mux_ctx = downstream;	/* point to mux client */
3076 		c->mux_downstream_id = id;	/* original downstream id */
3077 		if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
3078 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3079 		    (r = sshbuf_putb(modified, original)) != 0) {
3080 			error_fr(r, "compose");
3081 			channel_free(ssh, c);
3082 			goto out;
3083 		}
3084 		break;
3085 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3086 		/*
3087 		 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
3088 		 * need to parse 'remote_id' instead of 'ctype'.
3089 		 */
3090 		if ((original = sshbuf_from(cp, have)) == NULL ||
3091 		    (modified = sshbuf_new()) == NULL) {
3092 			error_f("alloc");
3093 			goto out;
3094 		}
3095 		if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
3096 		    (r = sshbuf_get_u32(original, &id)) != 0) {
3097 			error_fr(r, "parse");
3098 			goto out;
3099 		}
3100 		c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3101 		    -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
3102 		c->mux_ctx = downstream;	/* point to mux client */
3103 		c->mux_downstream_id = id;
3104 		c->remote_id = remote_id;
3105 		c->have_remote_id = 1;
3106 		if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
3107 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3108 		    (r = sshbuf_putb(modified, original)) != 0) {
3109 			error_fr(r, "compose");
3110 			channel_free(ssh, c);
3111 			goto out;
3112 		}
3113 		break;
3114 	case SSH2_MSG_GLOBAL_REQUEST:
3115 		if ((original = sshbuf_from(cp, have)) == NULL) {
3116 			error_f("alloc");
3117 			goto out;
3118 		}
3119 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
3120 			error_fr(r, "parse");
3121 			goto out;
3122 		}
3123 		if (strcmp(ctype, "tcpip-forward") != 0) {
3124 			error_f("unsupported request %s", ctype);
3125 			goto out;
3126 		}
3127 		if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
3128 		    (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
3129 		    (r = sshbuf_get_u32(original, &listen_port)) != 0) {
3130 			error_fr(r, "parse");
3131 			goto out;
3132 		}
3133 		if (listen_port > 65535) {
3134 			error_f("tcpip-forward for %s: bad port %u",
3135 			    listen_host, listen_port);
3136 			goto out;
3137 		}
3138 		/* Record that connection to this host/port is permitted. */
3139 		permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
3140 		    listen_host, NULL, (int)listen_port, downstream);
3141 		listen_host = NULL;
3142 		break;
3143 	case SSH2_MSG_CHANNEL_CLOSE:
3144 		if (have < 4)
3145 			break;
3146 		remote_id = PEEK_U32(cp);
3147 		if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
3148 			if (c->flags & CHAN_CLOSE_RCVD)
3149 				channel_free(ssh, c);
3150 			else
3151 				c->flags |= CHAN_CLOSE_SENT;
3152 		}
3153 		break;
3154 	}
3155 	if (modified) {
3156 		if ((r = sshpkt_start(ssh, type)) != 0 ||
3157 		    (r = sshpkt_putb(ssh, modified)) != 0 ||
3158 		    (r = sshpkt_send(ssh)) != 0) {
3159 			error_fr(r, "send");
3160 			goto out;
3161 		}
3162 	} else {
3163 		if ((r = sshpkt_start(ssh, type)) != 0 ||
3164 		    (r = sshpkt_put(ssh, cp, have)) != 0 ||
3165 		    (r = sshpkt_send(ssh)) != 0) {
3166 			error_fr(r, "send");
3167 			goto out;
3168 		}
3169 	}
3170 	ret = 0;
3171  out:
3172 	free(ctype);
3173 	free(listen_host);
3174 	sshbuf_free(original);
3175 	sshbuf_free(modified);
3176 	return ret;
3177 }
3178 
3179 /*
3180  * receive packets from upstream server and de-multiplex packets
3181  * to correct downstream:
3182  * implemented as a helper for channel input handlers,
3183  * replaces local (proxy) channel ID with downstream channel ID.
3184  */
3185 int
3186 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
3187 {
3188 	struct sshbuf *b = NULL;
3189 	Channel *downstream;
3190 	const u_char *cp = NULL;
3191 	size_t len;
3192 	int r;
3193 
3194 	/*
3195 	 * When receiving packets from the peer we need to check whether we
3196 	 * need to forward the packets to the mux client. In this case we
3197 	 * restore the original channel id and keep track of CLOSE messages,
3198 	 * so we can cleanup the channel.
3199 	 */
3200 	if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
3201 		return 0;
3202 	if ((downstream = c->mux_ctx) == NULL)
3203 		return 0;
3204 	switch (type) {
3205 	case SSH2_MSG_CHANNEL_CLOSE:
3206 	case SSH2_MSG_CHANNEL_DATA:
3207 	case SSH2_MSG_CHANNEL_EOF:
3208 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
3209 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3210 	case SSH2_MSG_CHANNEL_OPEN_FAILURE:
3211 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
3212 	case SSH2_MSG_CHANNEL_SUCCESS:
3213 	case SSH2_MSG_CHANNEL_FAILURE:
3214 	case SSH2_MSG_CHANNEL_REQUEST:
3215 		break;
3216 	default:
3217 		debug2_f("channel %u: unsupported type %u", c->self, type);
3218 		return 0;
3219 	}
3220 	if ((b = sshbuf_new()) == NULL) {
3221 		error_f("alloc reply");
3222 		goto out;
3223 	}
3224 	/* get remaining payload (after id) */
3225 	cp = sshpkt_ptr(ssh, &len);
3226 	if (cp == NULL) {
3227 		error_f("no packet");
3228 		goto out;
3229 	}
3230 	/* translate id and send to muxclient */
3231 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* padlen */
3232 	    (r = sshbuf_put_u8(b, type)) != 0 ||
3233 	    (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
3234 	    (r = sshbuf_put(b, cp, len)) != 0 ||
3235 	    (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
3236 		error_fr(r, "compose muxclient");
3237 		goto out;
3238 	}
3239 	/* sshbuf_dump(b, stderr); */
3240 	if (ssh_packet_log_type(type))
3241 		debug3_f("channel %u: up->down: type %u", c->self, type);
3242  out:
3243 	/* update state */
3244 	switch (type) {
3245 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3246 		/* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
3247 		if (cp && len > 4) {
3248 			c->remote_id = PEEK_U32(cp);
3249 			c->have_remote_id = 1;
3250 		}
3251 		break;
3252 	case SSH2_MSG_CHANNEL_CLOSE:
3253 		if (c->flags & CHAN_CLOSE_SENT)
3254 			channel_free(ssh, c);
3255 		else
3256 			c->flags |= CHAN_CLOSE_RCVD;
3257 		break;
3258 	}
3259 	sshbuf_free(b);
3260 	return 1;
3261 }
3262 
3263 /* -- protocol input */
3264 
3265 /* Parse a channel ID from the current packet */
3266 static int
3267 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
3268 {
3269 	u_int32_t id;
3270 	int r;
3271 
3272 	if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
3273 		error_r(r, "%s: parse id", where);
3274 		ssh_packet_disconnect(ssh, "Invalid %s message", what);
3275 	}
3276 	if (id > INT_MAX) {
3277 		error_r(r, "%s: bad channel id %u", where, id);
3278 		ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
3279 	}
3280 	return (int)id;
3281 }
3282 
3283 /* Lookup a channel from an ID in the current packet */
3284 static Channel *
3285 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
3286 {
3287 	int id = channel_parse_id(ssh, where, what);
3288 	Channel *c;
3289 
3290 	if ((c = channel_lookup(ssh, id)) == NULL) {
3291 		ssh_packet_disconnect(ssh,
3292 		    "%s packet referred to nonexistent channel %d", what, id);
3293 	}
3294 	return c;
3295 }
3296 
3297 int
3298 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
3299 {
3300 	const u_char *data;
3301 	size_t data_len, win_len;
3302 	Channel *c = channel_from_packet_id(ssh, __func__, "data");
3303 	int r;
3304 
3305 	if (channel_proxy_upstream(c, type, seq, ssh))
3306 		return 0;
3307 
3308 	/* Ignore any data for non-open channels (might happen on close) */
3309 	if (c->type != SSH_CHANNEL_OPEN &&
3310 	    c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
3311 	    c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
3312 	    c->type != SSH_CHANNEL_X11_OPEN)
3313 		return 0;
3314 
3315 	/* Get the data. */
3316 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3317             (r = sshpkt_get_end(ssh)) != 0)
3318 		fatal_fr(r, "channel %i: get data", c->self);
3319 
3320 	win_len = data_len;
3321 	if (c->datagram)
3322 		win_len += 4;  /* string length header */
3323 
3324 	/*
3325 	 * The sending side reduces its window as it sends data, so we
3326 	 * must 'fake' consumption of the data in order to ensure that window
3327 	 * updates are sent back. Otherwise the connection might deadlock.
3328 	 */
3329 	if (c->ostate != CHAN_OUTPUT_OPEN) {
3330 		c->local_window -= win_len;
3331 		c->local_consumed += win_len;
3332 		return 0;
3333 	}
3334 
3335 	if (win_len > c->local_maxpacket) {
3336 		logit("channel %d: rcvd big packet %zu, maxpack %u",
3337 		    c->self, win_len, c->local_maxpacket);
3338 		return 0;
3339 	}
3340 	if (win_len > c->local_window) {
3341 		logit("channel %d: rcvd too much data %zu, win %u",
3342 		    c->self, win_len, c->local_window);
3343 		return 0;
3344 	}
3345 	c->local_window -= win_len;
3346 
3347 	if (c->datagram) {
3348 		if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3349 			fatal_fr(r, "channel %i: append datagram", c->self);
3350 	} else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3351 		fatal_fr(r, "channel %i: append data", c->self);
3352 
3353 	return 0;
3354 }
3355 
3356 int
3357 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3358 {
3359 	const u_char *data;
3360 	size_t data_len;
3361 	u_int32_t tcode;
3362 	Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3363 	int r;
3364 
3365 	if (channel_proxy_upstream(c, type, seq, ssh))
3366 		return 0;
3367 	if (c->type != SSH_CHANNEL_OPEN) {
3368 		logit("channel %d: ext data for non open", c->self);
3369 		return 0;
3370 	}
3371 	if (c->flags & CHAN_EOF_RCVD) {
3372 		if (ssh->compat & SSH_BUG_EXTEOF)
3373 			debug("channel %d: accepting ext data after eof",
3374 			    c->self);
3375 		else
3376 			ssh_packet_disconnect(ssh, "Received extended_data "
3377 			    "after EOF on channel %d.", c->self);
3378 	}
3379 
3380 	if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3381 		error_fr(r, "parse tcode");
3382 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
3383 	}
3384 	if (c->efd == -1 ||
3385 	    c->extended_usage != CHAN_EXTENDED_WRITE ||
3386 	    tcode != SSH2_EXTENDED_DATA_STDERR) {
3387 		logit("channel %d: bad ext data", c->self);
3388 		return 0;
3389 	}
3390 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3391             (r = sshpkt_get_end(ssh)) != 0) {
3392 		error_fr(r, "parse data");
3393 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
3394 	}
3395 
3396 	if (data_len > c->local_window) {
3397 		logit("channel %d: rcvd too much extended_data %zu, win %u",
3398 		    c->self, data_len, c->local_window);
3399 		return 0;
3400 	}
3401 	debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3402 	/* XXX sshpkt_getb? */
3403 	if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3404 		error_fr(r, "append");
3405 	c->local_window -= data_len;
3406 	return 0;
3407 }
3408 
3409 int
3410 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3411 {
3412 	Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3413 	int r;
3414 
3415         if ((r = sshpkt_get_end(ssh)) != 0) {
3416 		error_fr(r, "parse data");
3417 		ssh_packet_disconnect(ssh, "Invalid ieof message");
3418 	}
3419 
3420 	if (channel_proxy_upstream(c, type, seq, ssh))
3421 		return 0;
3422 	chan_rcvd_ieof(ssh, c);
3423 
3424 	/* XXX force input close */
3425 	if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3426 		debug("channel %d: FORCE input drain", c->self);
3427 		c->istate = CHAN_INPUT_WAIT_DRAIN;
3428 		if (sshbuf_len(c->input) == 0)
3429 			chan_ibuf_empty(ssh, c);
3430 	}
3431 	return 0;
3432 }
3433 
3434 int
3435 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3436 {
3437 	Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3438 	int r;
3439 
3440 	if (channel_proxy_upstream(c, type, seq, ssh))
3441 		return 0;
3442         if ((r = sshpkt_get_end(ssh)) != 0) {
3443 		error_fr(r, "parse data");
3444 		ssh_packet_disconnect(ssh, "Invalid oclose message");
3445 	}
3446 	chan_rcvd_oclose(ssh, c);
3447 	return 0;
3448 }
3449 
3450 int
3451 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3452 {
3453 	Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3454 	u_int32_t remote_window, remote_maxpacket;
3455 	int r;
3456 
3457 	if (channel_proxy_upstream(c, type, seq, ssh))
3458 		return 0;
3459 	if (c->type != SSH_CHANNEL_OPENING)
3460 		ssh_packet_disconnect(ssh, "Received open confirmation for "
3461 		    "non-opening channel %d.", c->self);
3462 	/*
3463 	 * Record the remote channel number and mark that the channel
3464 	 * is now open.
3465 	 */
3466 	if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3467 	    (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3468 	    (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3469             (r = sshpkt_get_end(ssh)) != 0) {
3470 		error_fr(r, "window/maxpacket");
3471 		ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3472 	}
3473 
3474 	c->have_remote_id = 1;
3475 	c->remote_window = remote_window;
3476 	c->remote_maxpacket = remote_maxpacket;
3477 	c->type = SSH_CHANNEL_OPEN;
3478 	if (c->open_confirm) {
3479 		debug2_f("channel %d: callback start", c->self);
3480 		c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3481 		debug2_f("channel %d: callback done", c->self);
3482 	}
3483 	c->lastused = monotime();
3484 	debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3485 	    c->remote_window, c->remote_maxpacket);
3486 	return 0;
3487 }
3488 
3489 static char *
3490 reason2txt(int reason)
3491 {
3492 	switch (reason) {
3493 	case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3494 		return "administratively prohibited";
3495 	case SSH2_OPEN_CONNECT_FAILED:
3496 		return "connect failed";
3497 	case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3498 		return "unknown channel type";
3499 	case SSH2_OPEN_RESOURCE_SHORTAGE:
3500 		return "resource shortage";
3501 	}
3502 	return "unknown reason";
3503 }
3504 
3505 int
3506 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3507 {
3508 	Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3509 	u_int32_t reason;
3510 	char *msg = NULL;
3511 	int r;
3512 
3513 	if (channel_proxy_upstream(c, type, seq, ssh))
3514 		return 0;
3515 	if (c->type != SSH_CHANNEL_OPENING)
3516 		ssh_packet_disconnect(ssh, "Received open failure for "
3517 		    "non-opening channel %d.", c->self);
3518 	if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3519 		error_fr(r, "parse reason");
3520 		ssh_packet_disconnect(ssh, "Invalid open failure message");
3521 	}
3522 	/* skip language */
3523 	if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3524 	    (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3525             (r = sshpkt_get_end(ssh)) != 0) {
3526 		error_fr(r, "parse msg/lang");
3527 		ssh_packet_disconnect(ssh, "Invalid open failure message");
3528 	}
3529 	logit("channel %d: open failed: %s%s%s", c->self,
3530 	    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3531 	free(msg);
3532 	if (c->open_confirm) {
3533 		debug2_f("channel %d: callback start", c->self);
3534 		c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3535 		debug2_f("channel %d: callback done", c->self);
3536 	}
3537 	/* Schedule the channel for cleanup/deletion. */
3538 	chan_mark_dead(ssh, c);
3539 	return 0;
3540 }
3541 
3542 int
3543 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3544 {
3545 	int id = channel_parse_id(ssh, __func__, "window adjust");
3546 	Channel *c;
3547 	u_int32_t adjust;
3548 	u_int new_rwin;
3549 	int r;
3550 
3551 	if ((c = channel_lookup(ssh, id)) == NULL) {
3552 		logit("Received window adjust for non-open channel %d.", id);
3553 		return 0;
3554 	}
3555 
3556 	if (channel_proxy_upstream(c, type, seq, ssh))
3557 		return 0;
3558 	if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3559             (r = sshpkt_get_end(ssh)) != 0) {
3560 		error_fr(r, "parse adjust");
3561 		ssh_packet_disconnect(ssh, "Invalid window adjust message");
3562 	}
3563 	debug2("channel %d: rcvd adjust %u", c->self, adjust);
3564 	if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3565 		fatal("channel %d: adjust %u overflows remote window %u",
3566 		    c->self, adjust, c->remote_window);
3567 	}
3568 	c->remote_window = new_rwin;
3569 	return 0;
3570 }
3571 
3572 int
3573 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3574 {
3575 	int id = channel_parse_id(ssh, __func__, "status confirm");
3576 	Channel *c;
3577 	struct channel_confirm *cc;
3578 
3579 	/* Reset keepalive timeout */
3580 	ssh_packet_set_alive_timeouts(ssh, 0);
3581 
3582 	debug2_f("type %d id %d", type, id);
3583 
3584 	if ((c = channel_lookup(ssh, id)) == NULL) {
3585 		logit_f("%d: unknown", id);
3586 		return 0;
3587 	}
3588 	if (channel_proxy_upstream(c, type, seq, ssh))
3589 		return 0;
3590         if (sshpkt_get_end(ssh) != 0)
3591 		ssh_packet_disconnect(ssh, "Invalid status confirm message");
3592 	if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3593 		return 0;
3594 	cc->cb(ssh, type, c, cc->ctx);
3595 	TAILQ_REMOVE(&c->status_confirms, cc, entry);
3596 	freezero(cc, sizeof(*cc));
3597 	return 0;
3598 }
3599 
3600 /* -- tcp forwarding */
3601 
3602 void
3603 channel_set_af(struct ssh *ssh, int af)
3604 {
3605 	ssh->chanctxt->IPv4or6 = af;
3606 }
3607 
3608 
3609 /*
3610  * Determine whether or not a port forward listens to loopback, the
3611  * specified address or wildcard. On the client, a specified bind
3612  * address will always override gateway_ports. On the server, a
3613  * gateway_ports of 1 (``yes'') will override the client's specification
3614  * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3615  * will bind to whatever address the client asked for.
3616  *
3617  * Special-case listen_addrs are:
3618  *
3619  * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3620  * "" (empty string), "*"  -> wildcard v4/v6
3621  * "localhost"             -> loopback v4/v6
3622  * "127.0.0.1" / "::1"     -> accepted even if gateway_ports isn't set
3623  */
3624 static const char *
3625 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3626     int is_client, struct ForwardOptions *fwd_opts)
3627 {
3628 	const char *addr = NULL;
3629 	int wildcard = 0;
3630 
3631 	if (listen_addr == NULL) {
3632 		/* No address specified: default to gateway_ports setting */
3633 		if (fwd_opts->gateway_ports)
3634 			wildcard = 1;
3635 	} else if (fwd_opts->gateway_ports || is_client) {
3636 		if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3637 		    strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3638 		    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3639 		    (!is_client && fwd_opts->gateway_ports == 1)) {
3640 			wildcard = 1;
3641 			/*
3642 			 * Notify client if they requested a specific listen
3643 			 * address and it was overridden.
3644 			 */
3645 			if (*listen_addr != '\0' &&
3646 			    strcmp(listen_addr, "0.0.0.0") != 0 &&
3647 			    strcmp(listen_addr, "*") != 0) {
3648 				ssh_packet_send_debug(ssh,
3649 				    "Forwarding listen address "
3650 				    "\"%s\" overridden by server "
3651 				    "GatewayPorts", listen_addr);
3652 			}
3653 		} else if (strcmp(listen_addr, "localhost") != 0 ||
3654 		    strcmp(listen_addr, "127.0.0.1") == 0 ||
3655 		    strcmp(listen_addr, "::1") == 0) {
3656 			/*
3657 			 * Accept explicit localhost address when
3658 			 * GatewayPorts=yes. The "localhost" hostname is
3659 			 * deliberately skipped here so it will listen on all
3660 			 * available local address families.
3661 			 */
3662 			addr = listen_addr;
3663 		}
3664 	} else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3665 	    strcmp(listen_addr, "::1") == 0) {
3666 		/*
3667 		 * If a specific IPv4/IPv6 localhost address has been
3668 		 * requested then accept it even if gateway_ports is in
3669 		 * effect. This allows the client to prefer IPv4 or IPv6.
3670 		 */
3671 		addr = listen_addr;
3672 	}
3673 	if (wildcardp != NULL)
3674 		*wildcardp = wildcard;
3675 	return addr;
3676 }
3677 
3678 static int
3679 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3680     struct Forward *fwd, int *allocated_listen_port,
3681     struct ForwardOptions *fwd_opts)
3682 {
3683 	Channel *c;
3684 	int sock, r, success = 0, wildcard = 0, is_client;
3685 	struct addrinfo hints, *ai, *aitop;
3686 	const char *host, *addr;
3687 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3688 	in_port_t *lport_p;
3689 
3690 	is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3691 
3692 	if (is_client && fwd->connect_path != NULL) {
3693 		host = fwd->connect_path;
3694 	} else {
3695 		host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3696 		    fwd->listen_host : fwd->connect_host;
3697 		if (host == NULL) {
3698 			error("No forward host name.");
3699 			return 0;
3700 		}
3701 		if (strlen(host) >= NI_MAXHOST) {
3702 			error("Forward host name too long.");
3703 			return 0;
3704 		}
3705 	}
3706 
3707 	/* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3708 	addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3709 	    is_client, fwd_opts);
3710 	debug3_f("type %d wildcard %d addr %s", type, wildcard,
3711 	    (addr == NULL) ? "NULL" : addr);
3712 
3713 	/*
3714 	 * getaddrinfo returns a loopback address if the hostname is
3715 	 * set to NULL and hints.ai_flags is not AI_PASSIVE
3716 	 */
3717 	memset(&hints, 0, sizeof(hints));
3718 	hints.ai_family = ssh->chanctxt->IPv4or6;
3719 	hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3720 	hints.ai_socktype = SOCK_STREAM;
3721 	snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3722 	if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3723 		if (addr == NULL) {
3724 			/* This really shouldn't happen */
3725 			ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3726 			    ssh_gai_strerror(r));
3727 		} else {
3728 			error_f("getaddrinfo(%.64s): %s", addr,
3729 			    ssh_gai_strerror(r));
3730 		}
3731 		return 0;
3732 	}
3733 	if (allocated_listen_port != NULL)
3734 		*allocated_listen_port = 0;
3735 	for (ai = aitop; ai; ai = ai->ai_next) {
3736 		switch (ai->ai_family) {
3737 		case AF_INET:
3738 			lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3739 			    sin_port;
3740 			break;
3741 		case AF_INET6:
3742 			lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3743 			    sin6_port;
3744 			break;
3745 		default:
3746 			continue;
3747 		}
3748 		/*
3749 		 * If allocating a port for -R forwards, then use the
3750 		 * same port for all address families.
3751 		 */
3752 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
3753 		    fwd->listen_port == 0 && allocated_listen_port != NULL &&
3754 		    *allocated_listen_port > 0)
3755 			*lport_p = htons(*allocated_listen_port);
3756 
3757 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3758 		    strport, sizeof(strport),
3759 		    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3760 			error_f("getnameinfo failed");
3761 			continue;
3762 		}
3763 		/* Create a port to listen for the host. */
3764 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3765 		if (sock == -1) {
3766 			/* this is no error since kernel may not support ipv6 */
3767 			verbose("socket [%s]:%s: %.100s", ntop, strport,
3768 			    strerror(errno));
3769 			continue;
3770 		}
3771 
3772 		set_reuseaddr(sock);
3773 
3774 		debug("Local forwarding listening on %s port %s.",
3775 		    ntop, strport);
3776 
3777 		/* Bind the socket to the address. */
3778 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3779 			/*
3780 			 * address can be in if use ipv6 address is
3781 			 * already bound
3782 			 */
3783 			verbose("bind [%s]:%s: %.100s",
3784 			    ntop, strport, strerror(errno));
3785 			close(sock);
3786 			continue;
3787 		}
3788 		/* Start listening for connections on the socket. */
3789 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3790 			error("listen [%s]:%s: %.100s", ntop, strport,
3791 			    strerror(errno));
3792 			close(sock);
3793 			continue;
3794 		}
3795 
3796 		/*
3797 		 * fwd->listen_port == 0 requests a dynamically allocated port -
3798 		 * record what we got.
3799 		 */
3800 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
3801 		    fwd->listen_port == 0 &&
3802 		    allocated_listen_port != NULL &&
3803 		    *allocated_listen_port == 0) {
3804 			*allocated_listen_port = get_local_port(sock);
3805 			debug("Allocated listen port %d",
3806 			    *allocated_listen_port);
3807 		}
3808 
3809 		/* Allocate a channel number for the socket. */
3810 		c = channel_new(ssh, "port-listener", type, sock, sock, -1,
3811 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3812 		    0, "port listener", 1);
3813 		c->path = xstrdup(host);
3814 		c->host_port = fwd->connect_port;
3815 		c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3816 		if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3817 		    !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3818 			c->listening_port = *allocated_listen_port;
3819 		else
3820 			c->listening_port = fwd->listen_port;
3821 		success = 1;
3822 	}
3823 	if (success == 0)
3824 		error_f("cannot listen to port: %d", fwd->listen_port);
3825 	freeaddrinfo(aitop);
3826 	return success;
3827 }
3828 
3829 static int
3830 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3831     struct Forward *fwd, struct ForwardOptions *fwd_opts)
3832 {
3833 	struct sockaddr_un sunaddr;
3834 	const char *path;
3835 	Channel *c;
3836 	int port, sock;
3837 	mode_t omask;
3838 
3839 	switch (type) {
3840 	case SSH_CHANNEL_UNIX_LISTENER:
3841 		if (fwd->connect_path != NULL) {
3842 			if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3843 				error("Local connecting path too long: %s",
3844 				    fwd->connect_path);
3845 				return 0;
3846 			}
3847 			path = fwd->connect_path;
3848 			port = PORT_STREAMLOCAL;
3849 		} else {
3850 			if (fwd->connect_host == NULL) {
3851 				error("No forward host name.");
3852 				return 0;
3853 			}
3854 			if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3855 				error("Forward host name too long.");
3856 				return 0;
3857 			}
3858 			path = fwd->connect_host;
3859 			port = fwd->connect_port;
3860 		}
3861 		break;
3862 	case SSH_CHANNEL_RUNIX_LISTENER:
3863 		path = fwd->listen_path;
3864 		port = PORT_STREAMLOCAL;
3865 		break;
3866 	default:
3867 		error_f("unexpected channel type %d", type);
3868 		return 0;
3869 	}
3870 
3871 	if (fwd->listen_path == NULL) {
3872 		error("No forward path name.");
3873 		return 0;
3874 	}
3875 	if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3876 		error("Local listening path too long: %s", fwd->listen_path);
3877 		return 0;
3878 	}
3879 
3880 	debug3_f("type %d path %s", type, fwd->listen_path);
3881 
3882 	/* Start a Unix domain listener. */
3883 	omask = umask(fwd_opts->streamlocal_bind_mask);
3884 	sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3885 	    fwd_opts->streamlocal_bind_unlink);
3886 	umask(omask);
3887 	if (sock < 0)
3888 		return 0;
3889 
3890 	debug("Local forwarding listening on path %s.", fwd->listen_path);
3891 
3892 	/* Allocate a channel number for the socket. */
3893 	c = channel_new(ssh, "unix-listener", type, sock, sock, -1,
3894 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3895 	    0, "unix listener", 1);
3896 	c->path = xstrdup(path);
3897 	c->host_port = port;
3898 	c->listening_port = PORT_STREAMLOCAL;
3899 	c->listening_addr = xstrdup(fwd->listen_path);
3900 	return 1;
3901 }
3902 
3903 static int
3904 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3905     const char *host, u_short port)
3906 {
3907 	u_int i;
3908 	int found = 0;
3909 
3910 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3911 		Channel *c = ssh->chanctxt->channels[i];
3912 		if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3913 			continue;
3914 		if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3915 			debug2_f("close channel %d", i);
3916 			channel_free(ssh, c);
3917 			found = 1;
3918 		}
3919 	}
3920 
3921 	return found;
3922 }
3923 
3924 static int
3925 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3926 {
3927 	u_int i;
3928 	int found = 0;
3929 
3930 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3931 		Channel *c = ssh->chanctxt->channels[i];
3932 		if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3933 			continue;
3934 		if (c->path == NULL)
3935 			continue;
3936 		if (strcmp(c->path, path) == 0) {
3937 			debug2_f("close channel %d", i);
3938 			channel_free(ssh, c);
3939 			found = 1;
3940 		}
3941 	}
3942 
3943 	return found;
3944 }
3945 
3946 int
3947 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3948 {
3949 	if (fwd->listen_path != NULL) {
3950 		return channel_cancel_rport_listener_streamlocal(ssh,
3951 		    fwd->listen_path);
3952 	} else {
3953 		return channel_cancel_rport_listener_tcpip(ssh,
3954 		    fwd->listen_host, fwd->listen_port);
3955 	}
3956 }
3957 
3958 static int
3959 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3960     const char *lhost, u_short lport, int cport,
3961     struct ForwardOptions *fwd_opts)
3962 {
3963 	u_int i;
3964 	int found = 0;
3965 	const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
3966 
3967 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3968 		Channel *c = ssh->chanctxt->channels[i];
3969 		if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3970 			continue;
3971 		if (c->listening_port != lport)
3972 			continue;
3973 		if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3974 			/* skip dynamic forwardings */
3975 			if (c->host_port == 0)
3976 				continue;
3977 		} else {
3978 			if (c->host_port != cport)
3979 				continue;
3980 		}
3981 		if ((c->listening_addr == NULL && addr != NULL) ||
3982 		    (c->listening_addr != NULL && addr == NULL))
3983 			continue;
3984 		if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3985 			debug2_f("close channel %d", i);
3986 			channel_free(ssh, c);
3987 			found = 1;
3988 		}
3989 	}
3990 
3991 	return found;
3992 }
3993 
3994 static int
3995 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
3996 {
3997 	u_int i;
3998 	int found = 0;
3999 
4000 	if (path == NULL) {
4001 		error_f("no path specified.");
4002 		return 0;
4003 	}
4004 
4005 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4006 		Channel *c = ssh->chanctxt->channels[i];
4007 		if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
4008 			continue;
4009 		if (c->listening_addr == NULL)
4010 			continue;
4011 		if (strcmp(c->listening_addr, path) == 0) {
4012 			debug2_f("close channel %d", i);
4013 			channel_free(ssh, c);
4014 			found = 1;
4015 		}
4016 	}
4017 
4018 	return found;
4019 }
4020 
4021 int
4022 channel_cancel_lport_listener(struct ssh *ssh,
4023     struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
4024 {
4025 	if (fwd->listen_path != NULL) {
4026 		return channel_cancel_lport_listener_streamlocal(ssh,
4027 		    fwd->listen_path);
4028 	} else {
4029 		return channel_cancel_lport_listener_tcpip(ssh,
4030 		    fwd->listen_host, fwd->listen_port, cport, fwd_opts);
4031 	}
4032 }
4033 
4034 /* protocol local port fwd, used by ssh */
4035 int
4036 channel_setup_local_fwd_listener(struct ssh *ssh,
4037     struct Forward *fwd, struct ForwardOptions *fwd_opts)
4038 {
4039 	if (fwd->listen_path != NULL) {
4040 		return channel_setup_fwd_listener_streamlocal(ssh,
4041 		    SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
4042 	} else {
4043 		return channel_setup_fwd_listener_tcpip(ssh,
4044 		    SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
4045 	}
4046 }
4047 
4048 /* Matches a remote forwarding permission against a requested forwarding */
4049 static int
4050 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
4051 {
4052 	int ret;
4053 	char *lhost;
4054 
4055 	/* XXX add ACLs for streamlocal */
4056 	if (fwd->listen_path != NULL)
4057 		return 1;
4058 
4059 	if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
4060 		return 0;
4061 
4062 	if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
4063 	    allowed_open->listen_port != fwd->listen_port)
4064 		return 0;
4065 
4066 	/* Match hostnames case-insensitively */
4067 	lhost = xstrdup(fwd->listen_host);
4068 	lowercase(lhost);
4069 	ret = match_pattern(lhost, allowed_open->listen_host);
4070 	free(lhost);
4071 
4072 	return ret;
4073 }
4074 
4075 /* Checks whether a requested remote forwarding is permitted */
4076 static int
4077 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
4078 {
4079 	struct ssh_channels *sc = ssh->chanctxt;
4080 	struct permission_set *pset = &sc->remote_perms;
4081 	u_int i, permit, permit_adm = 1;
4082 	struct permission *perm;
4083 
4084 	/* XXX apply GatewayPorts override before checking? */
4085 
4086 	permit = pset->all_permitted;
4087 	if (!permit) {
4088 		for (i = 0; i < pset->num_permitted_user; i++) {
4089 			perm = &pset->permitted_user[i];
4090 			if (remote_open_match(perm, fwd)) {
4091 				permit = 1;
4092 				break;
4093 			}
4094 		}
4095 	}
4096 
4097 	if (pset->num_permitted_admin > 0) {
4098 		permit_adm = 0;
4099 		for (i = 0; i < pset->num_permitted_admin; i++) {
4100 			perm = &pset->permitted_admin[i];
4101 			if (remote_open_match(perm, fwd)) {
4102 				permit_adm = 1;
4103 				break;
4104 			}
4105 		}
4106 	}
4107 
4108 	return permit && permit_adm;
4109 }
4110 
4111 /* protocol v2 remote port fwd, used by sshd */
4112 int
4113 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
4114     int *allocated_listen_port, struct ForwardOptions *fwd_opts)
4115 {
4116 	if (!check_rfwd_permission(ssh, fwd)) {
4117 		ssh_packet_send_debug(ssh, "port forwarding refused");
4118 		if (fwd->listen_path != NULL)
4119 			/* XXX always allowed, see remote_open_match() */
4120 			logit("Received request from %.100s port %d to "
4121 			    "remote forward to path \"%.100s\", "
4122 			    "but the request was denied.",
4123 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4124 			    fwd->listen_path);
4125 		else if(fwd->listen_host != NULL)
4126 			logit("Received request from %.100s port %d to "
4127 			    "remote forward to host %.100s port %d, "
4128 			    "but the request was denied.",
4129 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4130 			    fwd->listen_host, fwd->listen_port );
4131 		else
4132 			logit("Received request from %.100s port %d to remote "
4133 			    "forward, but the request was denied.",
4134 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
4135 		return 0;
4136 	}
4137 	if (fwd->listen_path != NULL) {
4138 		return channel_setup_fwd_listener_streamlocal(ssh,
4139 		    SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
4140 	} else {
4141 		return channel_setup_fwd_listener_tcpip(ssh,
4142 		    SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
4143 		    fwd_opts);
4144 	}
4145 }
4146 
4147 /*
4148  * Translate the requested rfwd listen host to something usable for
4149  * this server.
4150  */
4151 static const char *
4152 channel_rfwd_bind_host(const char *listen_host)
4153 {
4154 	if (listen_host == NULL) {
4155 		return "localhost";
4156 	} else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
4157 		return "";
4158 	} else
4159 		return listen_host;
4160 }
4161 
4162 /*
4163  * Initiate forwarding of connections to port "port" on remote host through
4164  * the secure channel to host:port from local side.
4165  * Returns handle (index) for updating the dynamic listen port with
4166  * channel_update_permission().
4167  */
4168 int
4169 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
4170 {
4171 	int r, success = 0, idx = -1;
4172 	const char *host_to_connect, *listen_host, *listen_path;
4173 	int port_to_connect, listen_port;
4174 
4175 	/* Send the forward request to the remote side. */
4176 	if (fwd->listen_path != NULL) {
4177 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4178 		    (r = sshpkt_put_cstring(ssh,
4179 		    "streamlocal-forward@openssh.com")) != 0 ||
4180 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4181 		    (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
4182 		    (r = sshpkt_send(ssh)) != 0 ||
4183 		    (r = ssh_packet_write_wait(ssh)) != 0)
4184 			fatal_fr(r, "request streamlocal");
4185 	} else {
4186 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4187 		    (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
4188 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4189 		    (r = sshpkt_put_cstring(ssh,
4190 		    channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
4191 		    (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
4192 		    (r = sshpkt_send(ssh)) != 0 ||
4193 		    (r = ssh_packet_write_wait(ssh)) != 0)
4194 			fatal_fr(r, "request tcpip-forward");
4195 	}
4196 	/* Assume that server accepts the request */
4197 	success = 1;
4198 	if (success) {
4199 		/* Record that connection to this host/port is permitted. */
4200 		host_to_connect = listen_host = listen_path = NULL;
4201 		port_to_connect = listen_port = 0;
4202 		if (fwd->connect_path != NULL) {
4203 			host_to_connect = fwd->connect_path;
4204 			port_to_connect = PORT_STREAMLOCAL;
4205 		} else {
4206 			host_to_connect = fwd->connect_host;
4207 			port_to_connect = fwd->connect_port;
4208 		}
4209 		if (fwd->listen_path != NULL) {
4210 			listen_path = fwd->listen_path;
4211 			listen_port = PORT_STREAMLOCAL;
4212 		} else {
4213 			listen_host = fwd->listen_host;
4214 			listen_port = fwd->listen_port;
4215 		}
4216 		idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
4217 		    host_to_connect, port_to_connect,
4218 		    listen_host, listen_path, listen_port, NULL);
4219 	}
4220 	return idx;
4221 }
4222 
4223 static int
4224 open_match(struct permission *allowed_open, const char *requestedhost,
4225     int requestedport)
4226 {
4227 	if (allowed_open->host_to_connect == NULL)
4228 		return 0;
4229 	if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
4230 	    allowed_open->port_to_connect != requestedport)
4231 		return 0;
4232 	if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
4233 	    strcmp(allowed_open->host_to_connect, requestedhost) != 0)
4234 		return 0;
4235 	return 1;
4236 }
4237 
4238 /*
4239  * Note that in the listen host/port case
4240  * we don't support FWD_PERMIT_ANY_PORT and
4241  * need to translate between the configured-host (listen_host)
4242  * and what we've sent to the remote server (channel_rfwd_bind_host)
4243  */
4244 static int
4245 open_listen_match_tcpip(struct permission *allowed_open,
4246     const char *requestedhost, u_short requestedport, int translate)
4247 {
4248 	const char *allowed_host;
4249 
4250 	if (allowed_open->host_to_connect == NULL)
4251 		return 0;
4252 	if (allowed_open->listen_port != requestedport)
4253 		return 0;
4254 	if (!translate && allowed_open->listen_host == NULL &&
4255 	    requestedhost == NULL)
4256 		return 1;
4257 	allowed_host = translate ?
4258 	    channel_rfwd_bind_host(allowed_open->listen_host) :
4259 	    allowed_open->listen_host;
4260 	if (allowed_host == NULL || requestedhost == NULL ||
4261 	    strcmp(allowed_host, requestedhost) != 0)
4262 		return 0;
4263 	return 1;
4264 }
4265 
4266 static int
4267 open_listen_match_streamlocal(struct permission *allowed_open,
4268     const char *requestedpath)
4269 {
4270 	if (allowed_open->host_to_connect == NULL)
4271 		return 0;
4272 	if (allowed_open->listen_port != PORT_STREAMLOCAL)
4273 		return 0;
4274 	if (allowed_open->listen_path == NULL ||
4275 	    strcmp(allowed_open->listen_path, requestedpath) != 0)
4276 		return 0;
4277 	return 1;
4278 }
4279 
4280 /*
4281  * Request cancellation of remote forwarding of connection host:port from
4282  * local side.
4283  */
4284 static int
4285 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
4286     const char *host, u_short port)
4287 {
4288 	struct ssh_channels *sc = ssh->chanctxt;
4289 	struct permission_set *pset = &sc->local_perms;
4290 	int r;
4291 	u_int i;
4292 	struct permission *perm = NULL;
4293 
4294 	for (i = 0; i < pset->num_permitted_user; i++) {
4295 		perm = &pset->permitted_user[i];
4296 		if (open_listen_match_tcpip(perm, host, port, 0))
4297 			break;
4298 		perm = NULL;
4299 	}
4300 	if (perm == NULL) {
4301 		debug_f("requested forward not found");
4302 		return -1;
4303 	}
4304 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4305 	    (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
4306 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4307 	    (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
4308 	    (r = sshpkt_put_u32(ssh, port)) != 0 ||
4309 	    (r = sshpkt_send(ssh)) != 0)
4310 		fatal_fr(r, "send cancel");
4311 
4312 	fwd_perm_clear(perm); /* unregister */
4313 
4314 	return 0;
4315 }
4316 
4317 /*
4318  * Request cancellation of remote forwarding of Unix domain socket
4319  * path from local side.
4320  */
4321 static int
4322 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
4323 {
4324 	struct ssh_channels *sc = ssh->chanctxt;
4325 	struct permission_set *pset = &sc->local_perms;
4326 	int r;
4327 	u_int i;
4328 	struct permission *perm = NULL;
4329 
4330 	for (i = 0; i < pset->num_permitted_user; i++) {
4331 		perm = &pset->permitted_user[i];
4332 		if (open_listen_match_streamlocal(perm, path))
4333 			break;
4334 		perm = NULL;
4335 	}
4336 	if (perm == NULL) {
4337 		debug_f("requested forward not found");
4338 		return -1;
4339 	}
4340 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4341 	    (r = sshpkt_put_cstring(ssh,
4342 	    "cancel-streamlocal-forward@openssh.com")) != 0 ||
4343 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4344 	    (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4345 	    (r = sshpkt_send(ssh)) != 0)
4346 		fatal_fr(r, "send cancel");
4347 
4348 	fwd_perm_clear(perm); /* unregister */
4349 
4350 	return 0;
4351 }
4352 
4353 /*
4354  * Request cancellation of remote forwarding of a connection from local side.
4355  */
4356 int
4357 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4358 {
4359 	if (fwd->listen_path != NULL) {
4360 		return channel_request_rforward_cancel_streamlocal(ssh,
4361 		    fwd->listen_path);
4362 	} else {
4363 		return channel_request_rforward_cancel_tcpip(ssh,
4364 		    fwd->listen_host,
4365 		    fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4366 	}
4367 }
4368 
4369 /*
4370  * Permits opening to any host/port if permitted_user[] is empty.  This is
4371  * usually called by the server, because the user could connect to any port
4372  * anyway, and the server has no way to know but to trust the client anyway.
4373  */
4374 void
4375 channel_permit_all(struct ssh *ssh, int where)
4376 {
4377 	struct permission_set *pset = permission_set_get(ssh, where);
4378 
4379 	if (pset->num_permitted_user == 0)
4380 		pset->all_permitted = 1;
4381 }
4382 
4383 /*
4384  * Permit the specified host/port for forwarding.
4385  */
4386 void
4387 channel_add_permission(struct ssh *ssh, int who, int where,
4388     char *host, int port)
4389 {
4390 	int local = where == FORWARD_LOCAL;
4391 	struct permission_set *pset = permission_set_get(ssh, where);
4392 
4393 	debug("allow %s forwarding to host %s port %d",
4394 	    fwd_ident(who, where), host, port);
4395 	/*
4396 	 * Remote forwards set listen_host/port, local forwards set
4397 	 * host/port_to_connect.
4398 	 */
4399 	permission_set_add(ssh, who, where,
4400 	    local ? host : 0, local ? port : 0,
4401 	    local ? NULL : host, NULL, local ? 0 : port, NULL);
4402 	pset->all_permitted = 0;
4403 }
4404 
4405 /*
4406  * Administratively disable forwarding.
4407  */
4408 void
4409 channel_disable_admin(struct ssh *ssh, int where)
4410 {
4411 	channel_clear_permission(ssh, FORWARD_ADM, where);
4412 	permission_set_add(ssh, FORWARD_ADM, where,
4413 	    NULL, 0, NULL, NULL, 0, NULL);
4414 }
4415 
4416 /*
4417  * Clear a list of permitted opens.
4418  */
4419 void
4420 channel_clear_permission(struct ssh *ssh, int who, int where)
4421 {
4422 	struct permission **permp;
4423 	u_int *npermp;
4424 
4425 	permission_set_get_array(ssh, who, where, &permp, &npermp);
4426 	*permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4427 	*npermp = 0;
4428 }
4429 
4430 /*
4431  * Update the listen port for a dynamic remote forward, after
4432  * the actual 'newport' has been allocated. If 'newport' < 0 is
4433  * passed then they entry will be invalidated.
4434  */
4435 void
4436 channel_update_permission(struct ssh *ssh, int idx, int newport)
4437 {
4438 	struct permission_set *pset = &ssh->chanctxt->local_perms;
4439 
4440 	if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4441 		debug_f("index out of range: %d num_permitted_user %d",
4442 		    idx, pset->num_permitted_user);
4443 		return;
4444 	}
4445 	debug("%s allowed port %d for forwarding to host %s port %d",
4446 	    newport > 0 ? "Updating" : "Removing",
4447 	    newport,
4448 	    pset->permitted_user[idx].host_to_connect,
4449 	    pset->permitted_user[idx].port_to_connect);
4450 	if (newport <= 0)
4451 		fwd_perm_clear(&pset->permitted_user[idx]);
4452 	else {
4453 		pset->permitted_user[idx].listen_port =
4454 		    (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4455 	}
4456 }
4457 
4458 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4459 int
4460 permitopen_port(const char *p)
4461 {
4462 	int port;
4463 
4464 	if (strcmp(p, "*") == 0)
4465 		return FWD_PERMIT_ANY_PORT;
4466 	if ((port = a2port(p)) > 0)
4467 		return port;
4468 	return -1;
4469 }
4470 
4471 /* Try to start non-blocking connect to next host in cctx list */
4472 static int
4473 connect_next(struct channel_connect *cctx)
4474 {
4475 	int sock, saved_errno;
4476 	struct sockaddr_un *sunaddr;
4477 	char ntop[NI_MAXHOST];
4478 	char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4479 
4480 	for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4481 		switch (cctx->ai->ai_family) {
4482 		case AF_UNIX:
4483 			/* unix:pathname instead of host:port */
4484 			sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4485 			strlcpy(ntop, "unix", sizeof(ntop));
4486 			strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4487 			break;
4488 		case AF_INET:
4489 		case AF_INET6:
4490 			if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4491 			    ntop, sizeof(ntop), strport, sizeof(strport),
4492 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4493 				error_f("getnameinfo failed");
4494 				continue;
4495 			}
4496 			break;
4497 		default:
4498 			continue;
4499 		}
4500 		debug_f("start for host %.100s ([%.100s]:%s)",
4501 		    cctx->host, ntop, strport);
4502 		if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4503 		    cctx->ai->ai_protocol)) == -1) {
4504 			if (cctx->ai->ai_next == NULL)
4505 				error("socket: %.100s", strerror(errno));
4506 			else
4507 				verbose("socket: %.100s", strerror(errno));
4508 			continue;
4509 		}
4510 		if (set_nonblock(sock) == -1)
4511 			fatal_f("set_nonblock(%d)", sock);
4512 		if (connect(sock, cctx->ai->ai_addr,
4513 		    cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4514 			debug_f("host %.100s ([%.100s]:%s): %.100s",
4515 			    cctx->host, ntop, strport, strerror(errno));
4516 			saved_errno = errno;
4517 			close(sock);
4518 			errno = saved_errno;
4519 			continue;	/* fail -- try next */
4520 		}
4521 		if (cctx->ai->ai_family != AF_UNIX)
4522 			set_nodelay(sock);
4523 		debug_f("connect host %.100s ([%.100s]:%s) in progress, fd=%d",
4524 		    cctx->host, ntop, strport, sock);
4525 		cctx->ai = cctx->ai->ai_next;
4526 		return sock;
4527 	}
4528 	return -1;
4529 }
4530 
4531 static void
4532 channel_connect_ctx_free(struct channel_connect *cctx)
4533 {
4534 	free(cctx->host);
4535 	if (cctx->aitop) {
4536 		if (cctx->aitop->ai_family == AF_UNIX)
4537 			free(cctx->aitop);
4538 		else
4539 			freeaddrinfo(cctx->aitop);
4540 	}
4541 	memset(cctx, 0, sizeof(*cctx));
4542 }
4543 
4544 /*
4545  * Return connecting socket to remote host:port or local socket path,
4546  * passing back the failure reason if appropriate.
4547  */
4548 static int
4549 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4550     char *ctype, char *rname, struct channel_connect *cctx,
4551     int *reason, const char **errmsg)
4552 {
4553 	struct addrinfo hints;
4554 	int gaierr;
4555 	int sock = -1;
4556 	char strport[NI_MAXSERV];
4557 
4558 	if (port == PORT_STREAMLOCAL) {
4559 		struct sockaddr_un *sunaddr;
4560 		struct addrinfo *ai;
4561 
4562 		if (strlen(name) > sizeof(sunaddr->sun_path)) {
4563 			error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4564 			return -1;
4565 		}
4566 
4567 		/*
4568 		 * Fake up a struct addrinfo for AF_UNIX connections.
4569 		 * channel_connect_ctx_free() must check ai_family
4570 		 * and use free() not freeaddirinfo() for AF_UNIX.
4571 		 */
4572 		ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4573 		memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4574 		ai->ai_addr = (struct sockaddr *)(ai + 1);
4575 		ai->ai_addrlen = sizeof(*sunaddr);
4576 		ai->ai_family = AF_UNIX;
4577 		ai->ai_socktype = socktype;
4578 		ai->ai_protocol = PF_UNSPEC;
4579 		sunaddr = (struct sockaddr_un *)ai->ai_addr;
4580 		sunaddr->sun_family = AF_UNIX;
4581 		strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4582 		cctx->aitop = ai;
4583 	} else {
4584 		memset(&hints, 0, sizeof(hints));
4585 		hints.ai_family = ssh->chanctxt->IPv4or6;
4586 		hints.ai_socktype = socktype;
4587 		snprintf(strport, sizeof strport, "%d", port);
4588 		if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4589 		    != 0) {
4590 			if (errmsg != NULL)
4591 				*errmsg = ssh_gai_strerror(gaierr);
4592 			if (reason != NULL)
4593 				*reason = SSH2_OPEN_CONNECT_FAILED;
4594 			error("connect_to %.100s: unknown host (%s)", name,
4595 			    ssh_gai_strerror(gaierr));
4596 			return -1;
4597 		}
4598 	}
4599 
4600 	cctx->host = xstrdup(name);
4601 	cctx->port = port;
4602 	cctx->ai = cctx->aitop;
4603 
4604 	if ((sock = connect_next(cctx)) == -1) {
4605 		error("connect to %.100s port %d failed: %s",
4606 		    name, port, strerror(errno));
4607 		return -1;
4608 	}
4609 
4610 	return sock;
4611 }
4612 
4613 /* Return CONNECTING channel to remote host:port or local socket path */
4614 static Channel *
4615 connect_to(struct ssh *ssh, const char *host, int port,
4616     char *ctype, char *rname)
4617 {
4618 	struct channel_connect cctx;
4619 	Channel *c;
4620 	int sock;
4621 
4622 	memset(&cctx, 0, sizeof(cctx));
4623 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4624 	    &cctx, NULL, NULL);
4625 	if (sock == -1) {
4626 		channel_connect_ctx_free(&cctx);
4627 		return NULL;
4628 	}
4629 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4630 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4631 	c->host_port = port;
4632 	c->path = xstrdup(host);
4633 	c->connect_ctx = cctx;
4634 
4635 	return c;
4636 }
4637 
4638 /*
4639  * returns either the newly connected channel or the downstream channel
4640  * that needs to deal with this connection.
4641  */
4642 Channel *
4643 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4644     u_short listen_port, char *ctype, char *rname)
4645 {
4646 	struct ssh_channels *sc = ssh->chanctxt;
4647 	struct permission_set *pset = &sc->local_perms;
4648 	u_int i;
4649 	struct permission *perm;
4650 
4651 	for (i = 0; i < pset->num_permitted_user; i++) {
4652 		perm = &pset->permitted_user[i];
4653 		if (open_listen_match_tcpip(perm,
4654 		    listen_host, listen_port, 1)) {
4655 			if (perm->downstream)
4656 				return perm->downstream;
4657 			if (perm->port_to_connect == 0)
4658 				return rdynamic_connect_prepare(ssh,
4659 				    ctype, rname);
4660 			return connect_to(ssh,
4661 			    perm->host_to_connect, perm->port_to_connect,
4662 			    ctype, rname);
4663 		}
4664 	}
4665 	error("WARNING: Server requests forwarding for unknown listen_port %d",
4666 	    listen_port);
4667 	return NULL;
4668 }
4669 
4670 Channel *
4671 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4672     char *ctype, char *rname)
4673 {
4674 	struct ssh_channels *sc = ssh->chanctxt;
4675 	struct permission_set *pset = &sc->local_perms;
4676 	u_int i;
4677 	struct permission *perm;
4678 
4679 	for (i = 0; i < pset->num_permitted_user; i++) {
4680 		perm = &pset->permitted_user[i];
4681 		if (open_listen_match_streamlocal(perm, path)) {
4682 			return connect_to(ssh,
4683 			    perm->host_to_connect, perm->port_to_connect,
4684 			    ctype, rname);
4685 		}
4686 	}
4687 	error("WARNING: Server requests forwarding for unknown path %.100s",
4688 	    path);
4689 	return NULL;
4690 }
4691 
4692 /* Check if connecting to that port is permitted and connect. */
4693 Channel *
4694 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4695     char *ctype, char *rname, int *reason, const char **errmsg)
4696 {
4697 	struct ssh_channels *sc = ssh->chanctxt;
4698 	struct permission_set *pset = &sc->local_perms;
4699 	struct channel_connect cctx;
4700 	Channel *c;
4701 	u_int i, permit, permit_adm = 1;
4702 	int sock;
4703 	struct permission *perm;
4704 
4705 	permit = pset->all_permitted;
4706 	if (!permit) {
4707 		for (i = 0; i < pset->num_permitted_user; i++) {
4708 			perm = &pset->permitted_user[i];
4709 			if (open_match(perm, host, port)) {
4710 				permit = 1;
4711 				break;
4712 			}
4713 		}
4714 	}
4715 
4716 	if (pset->num_permitted_admin > 0) {
4717 		permit_adm = 0;
4718 		for (i = 0; i < pset->num_permitted_admin; i++) {
4719 			perm = &pset->permitted_admin[i];
4720 			if (open_match(perm, host, port)) {
4721 				permit_adm = 1;
4722 				break;
4723 			}
4724 		}
4725 	}
4726 
4727 	if (!permit || !permit_adm) {
4728 		logit("Received request from %.100s port %d to connect to "
4729 		    "host %.100s port %d, but the request was denied.",
4730 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4731 		if (reason != NULL)
4732 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4733 		return NULL;
4734 	}
4735 
4736 	memset(&cctx, 0, sizeof(cctx));
4737 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4738 	    &cctx, reason, errmsg);
4739 	if (sock == -1) {
4740 		channel_connect_ctx_free(&cctx);
4741 		return NULL;
4742 	}
4743 
4744 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4745 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4746 	c->host_port = port;
4747 	c->path = xstrdup(host);
4748 	c->connect_ctx = cctx;
4749 
4750 	return c;
4751 }
4752 
4753 /* Check if connecting to that path is permitted and connect. */
4754 Channel *
4755 channel_connect_to_path(struct ssh *ssh, const char *path,
4756     char *ctype, char *rname)
4757 {
4758 	struct ssh_channels *sc = ssh->chanctxt;
4759 	struct permission_set *pset = &sc->local_perms;
4760 	u_int i, permit, permit_adm = 1;
4761 	struct permission *perm;
4762 
4763 	permit = pset->all_permitted;
4764 	if (!permit) {
4765 		for (i = 0; i < pset->num_permitted_user; i++) {
4766 			perm = &pset->permitted_user[i];
4767 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
4768 				permit = 1;
4769 				break;
4770 			}
4771 		}
4772 	}
4773 
4774 	if (pset->num_permitted_admin > 0) {
4775 		permit_adm = 0;
4776 		for (i = 0; i < pset->num_permitted_admin; i++) {
4777 			perm = &pset->permitted_admin[i];
4778 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
4779 				permit_adm = 1;
4780 				break;
4781 			}
4782 		}
4783 	}
4784 
4785 	if (!permit || !permit_adm) {
4786 		logit("Received request to connect to path %.100s, "
4787 		    "but the request was denied.", path);
4788 		return NULL;
4789 	}
4790 	return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4791 }
4792 
4793 void
4794 channel_send_window_changes(struct ssh *ssh)
4795 {
4796 	struct ssh_channels *sc = ssh->chanctxt;
4797 	struct winsize ws;
4798 	int r;
4799 	u_int i;
4800 
4801 	for (i = 0; i < sc->channels_alloc; i++) {
4802 		if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4803 		    sc->channels[i]->type != SSH_CHANNEL_OPEN)
4804 			continue;
4805 		if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4806 			continue;
4807 		channel_request_start(ssh, i, "window-change", 0);
4808 		if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4809 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4810 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4811 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4812 		    (r = sshpkt_send(ssh)) != 0)
4813 			fatal_fr(r, "channel %u; send window-change", i);
4814 	}
4815 }
4816 
4817 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4818 static Channel *
4819 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4820 {
4821 	Channel *c;
4822 	int r;
4823 
4824 	c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4825 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4826 	c->host_port = 0;
4827 	c->path = NULL;
4828 
4829 	/*
4830 	 * We need to open the channel before we have a FD,
4831 	 * so that we can get SOCKS header from peer.
4832 	 */
4833 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4834 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4835 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4836 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4837 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4838 		fatal_fr(r, "channel %i; confirm", c->self);
4839 	return c;
4840 }
4841 
4842 /* Return CONNECTING socket to remote host:port or local socket path */
4843 static int
4844 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4845 {
4846 	struct ssh_channels *sc = ssh->chanctxt;
4847 	struct permission_set *pset = &sc->local_perms;
4848 	struct permission *perm;
4849 	struct channel_connect cctx;
4850 	u_int i, permit_adm = 1;
4851 	int sock;
4852 
4853 	if (pset->num_permitted_admin > 0) {
4854 		permit_adm = 0;
4855 		for (i = 0; i < pset->num_permitted_admin; i++) {
4856 			perm = &pset->permitted_admin[i];
4857 			if (open_match(perm, c->path, c->host_port)) {
4858 				permit_adm = 1;
4859 				break;
4860 			}
4861 		}
4862 	}
4863 	if (!permit_adm) {
4864 		debug_f("requested forward not permitted");
4865 		return -1;
4866 	}
4867 
4868 	memset(&cctx, 0, sizeof(cctx));
4869 	sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4870 	    NULL, &cctx, NULL, NULL);
4871 	if (sock == -1)
4872 		channel_connect_ctx_free(&cctx);
4873 	else {
4874 		/* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4875 		c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4876 		c->connect_ctx = cctx;
4877 		channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4878 	}
4879 	return sock;
4880 }
4881 
4882 /* -- X11 forwarding */
4883 
4884 /*
4885  * Creates an internet domain socket for listening for X11 connections.
4886  * Returns 0 and a suitable display number for the DISPLAY variable
4887  * stored in display_numberp , or -1 if an error occurs.
4888  */
4889 int
4890 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4891     int x11_use_localhost, int single_connection,
4892     u_int *display_numberp, int **chanids)
4893 {
4894 	Channel *nc = NULL;
4895 	int display_number, sock;
4896 	u_short port;
4897 	struct addrinfo hints, *ai, *aitop;
4898 	char strport[NI_MAXSERV];
4899 	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4900 
4901 	if (chanids == NULL)
4902 		return -1;
4903 
4904 	for (display_number = x11_display_offset;
4905 	    display_number < MAX_DISPLAYS;
4906 	    display_number++) {
4907 		port = 6000 + display_number;
4908 		memset(&hints, 0, sizeof(hints));
4909 		hints.ai_family = ssh->chanctxt->IPv4or6;
4910 		hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4911 		hints.ai_socktype = SOCK_STREAM;
4912 		snprintf(strport, sizeof strport, "%d", port);
4913 		if ((gaierr = getaddrinfo(NULL, strport,
4914 		    &hints, &aitop)) != 0) {
4915 			error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4916 			return -1;
4917 		}
4918 		for (ai = aitop; ai; ai = ai->ai_next) {
4919 			if (ai->ai_family != AF_INET &&
4920 			    ai->ai_family != AF_INET6)
4921 				continue;
4922 			sock = socket(ai->ai_family, ai->ai_socktype,
4923 			    ai->ai_protocol);
4924 			if (sock == -1) {
4925 				error("socket: %.100s", strerror(errno));
4926 				freeaddrinfo(aitop);
4927 				return -1;
4928 			}
4929 			set_reuseaddr(sock);
4930 			if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4931 				debug2_f("bind port %d: %.100s", port,
4932 				    strerror(errno));
4933 				close(sock);
4934 				for (n = 0; n < num_socks; n++)
4935 					close(socks[n]);
4936 				num_socks = 0;
4937 				break;
4938 			}
4939 			socks[num_socks++] = sock;
4940 			if (num_socks == NUM_SOCKS)
4941 				break;
4942 		}
4943 		freeaddrinfo(aitop);
4944 		if (num_socks > 0)
4945 			break;
4946 	}
4947 	if (display_number >= MAX_DISPLAYS) {
4948 		error("Failed to allocate internet-domain X11 display socket.");
4949 		return -1;
4950 	}
4951 	/* Start listening for connections on the socket. */
4952 	for (n = 0; n < num_socks; n++) {
4953 		sock = socks[n];
4954 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
4955 			error("listen: %.100s", strerror(errno));
4956 			close(sock);
4957 			return -1;
4958 		}
4959 	}
4960 
4961 	/* Allocate a channel for each socket. */
4962 	*chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4963 	for (n = 0; n < num_socks; n++) {
4964 		sock = socks[n];
4965 		nc = channel_new(ssh, "x11-listener",
4966 		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4967 		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4968 		    0, "X11 inet listener", 1);
4969 		nc->single_connection = single_connection;
4970 		(*chanids)[n] = nc->self;
4971 	}
4972 	(*chanids)[n] = -1;
4973 
4974 	/* Return the display number for the DISPLAY environment variable. */
4975 	*display_numberp = display_number;
4976 	return 0;
4977 }
4978 
4979 static int
4980 connect_local_xsocket(u_int dnr)
4981 {
4982 	int sock;
4983 	struct sockaddr_un addr;
4984 
4985 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
4986 	if (sock == -1)
4987 		error("socket: %.100s", strerror(errno));
4988 	memset(&addr, 0, sizeof(addr));
4989 	addr.sun_family = AF_UNIX;
4990 	snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
4991 	if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
4992 		return sock;
4993 	close(sock);
4994 	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
4995 	return -1;
4996 }
4997 
4998 int
4999 x11_connect_display(struct ssh *ssh)
5000 {
5001 	u_int display_number;
5002 	const char *display;
5003 	char buf[1024], *cp;
5004 	struct addrinfo hints, *ai, *aitop;
5005 	char strport[NI_MAXSERV];
5006 	int gaierr, sock = 0;
5007 
5008 	/* Try to open a socket for the local X server. */
5009 	display = getenv("DISPLAY");
5010 	if (!display) {
5011 		error("DISPLAY not set.");
5012 		return -1;
5013 	}
5014 	/*
5015 	 * Now we decode the value of the DISPLAY variable and make a
5016 	 * connection to the real X server.
5017 	 */
5018 
5019 	/*
5020 	 * Check if it is a unix domain socket.  Unix domain displays are in
5021 	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
5022 	 */
5023 	if (strncmp(display, "unix:", 5) == 0 ||
5024 	    display[0] == ':') {
5025 		/* Connect to the unix domain socket. */
5026 		if (sscanf(strrchr(display, ':') + 1, "%u",
5027 		    &display_number) != 1) {
5028 			error("Could not parse display number from DISPLAY: "
5029 			    "%.100s", display);
5030 			return -1;
5031 		}
5032 		/* Create a socket. */
5033 		sock = connect_local_xsocket(display_number);
5034 		if (sock < 0)
5035 			return -1;
5036 
5037 		/* OK, we now have a connection to the display. */
5038 		return sock;
5039 	}
5040 	/*
5041 	 * Connect to an inet socket.  The DISPLAY value is supposedly
5042 	 * hostname:d[.s], where hostname may also be numeric IP address.
5043 	 */
5044 	strlcpy(buf, display, sizeof(buf));
5045 	cp = strchr(buf, ':');
5046 	if (!cp) {
5047 		error("Could not find ':' in DISPLAY: %.100s", display);
5048 		return -1;
5049 	}
5050 	*cp = 0;
5051 	/*
5052 	 * buf now contains the host name.  But first we parse the
5053 	 * display number.
5054 	 */
5055 	if (sscanf(cp + 1, "%u", &display_number) != 1) {
5056 		error("Could not parse display number from DISPLAY: %.100s",
5057 		    display);
5058 		return -1;
5059 	}
5060 
5061 	/* Look up the host address */
5062 	memset(&hints, 0, sizeof(hints));
5063 	hints.ai_family = ssh->chanctxt->IPv4or6;
5064 	hints.ai_socktype = SOCK_STREAM;
5065 	snprintf(strport, sizeof strport, "%u", 6000 + display_number);
5066 	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
5067 		error("%.100s: unknown host. (%s)", buf,
5068 		ssh_gai_strerror(gaierr));
5069 		return -1;
5070 	}
5071 	for (ai = aitop; ai; ai = ai->ai_next) {
5072 		/* Create a socket. */
5073 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
5074 		if (sock == -1) {
5075 			debug2("socket: %.100s", strerror(errno));
5076 			continue;
5077 		}
5078 		/* Connect it to the display. */
5079 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
5080 			debug2("connect %.100s port %u: %.100s", buf,
5081 			    6000 + display_number, strerror(errno));
5082 			close(sock);
5083 			continue;
5084 		}
5085 		/* Success */
5086 		break;
5087 	}
5088 	freeaddrinfo(aitop);
5089 	if (!ai) {
5090 		error("connect %.100s port %u: %.100s", buf,
5091 		    6000 + display_number, strerror(errno));
5092 		return -1;
5093 	}
5094 	set_nodelay(sock);
5095 	return sock;
5096 }
5097 
5098 /*
5099  * Requests forwarding of X11 connections, generates fake authentication
5100  * data, and enables authentication spoofing.
5101  * This should be called in the client only.
5102  */
5103 void
5104 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
5105     const char *disp, const char *proto, const char *data, int want_reply)
5106 {
5107 	struct ssh_channels *sc = ssh->chanctxt;
5108 	u_int data_len = (u_int) strlen(data) / 2;
5109 	u_int i, value;
5110 	const char *cp;
5111 	char *new_data;
5112 	int r, screen_number;
5113 
5114 	if (sc->x11_saved_display == NULL)
5115 		sc->x11_saved_display = xstrdup(disp);
5116 	else if (strcmp(disp, sc->x11_saved_display) != 0) {
5117 		error("x11_request_forwarding_with_spoofing: different "
5118 		    "$DISPLAY already forwarded");
5119 		return;
5120 	}
5121 
5122 	cp = strchr(disp, ':');
5123 	if (cp)
5124 		cp = strchr(cp, '.');
5125 	if (cp)
5126 		screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
5127 	else
5128 		screen_number = 0;
5129 
5130 	if (sc->x11_saved_proto == NULL) {
5131 		/* Save protocol name. */
5132 		sc->x11_saved_proto = xstrdup(proto);
5133 
5134 		/* Extract real authentication data. */
5135 		sc->x11_saved_data = xmalloc(data_len);
5136 		for (i = 0; i < data_len; i++) {
5137 			if (sscanf(data + 2 * i, "%2x", &value) != 1) {
5138 				fatal("x11_request_forwarding: bad "
5139 				    "authentication data: %.100s", data);
5140 			}
5141 			sc->x11_saved_data[i] = value;
5142 		}
5143 		sc->x11_saved_data_len = data_len;
5144 
5145 		/* Generate fake data of the same length. */
5146 		sc->x11_fake_data = xmalloc(data_len);
5147 		arc4random_buf(sc->x11_fake_data, data_len);
5148 		sc->x11_fake_data_len = data_len;
5149 	}
5150 
5151 	/* Convert the fake data into hex. */
5152 	new_data = tohex(sc->x11_fake_data, data_len);
5153 
5154 	/* Send the request packet. */
5155 	channel_request_start(ssh, client_session_id, "x11-req", want_reply);
5156 	if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
5157 	    (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
5158 	    (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
5159 	    (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
5160 	    (r = sshpkt_send(ssh)) != 0 ||
5161 	    (r = ssh_packet_write_wait(ssh)) != 0)
5162 		fatal_fr(r, "send x11-req");
5163 	free(new_data);
5164 }
5165