xref: /openbsd-src/usr.bin/ssh/channels.c (revision 1ad61ae0a79a724d2d3ec69e69c8e1d1ff6b53a0)
1 /* $OpenBSD: channels.c,v 1.433 2023/09/04 00:01:46 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains functions for generic socket connection forwarding.
7  * There is also code for initiating connection forwarding for X11 connections,
8  * arbitrary tcp/ip connections, and the authentication agent connection.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * SSH2 support added by Markus Friedl.
17  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
18  * Copyright (c) 1999 Dug Song.  All rights reserved.
19  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 #include <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, int 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, port_to_connect == PORT_STREAMLOCAL ?
1643 	    "direct-streamlocal@openssh.com" : "direct-tcpip");
1644 
1645 	return c;
1646 }
1647 
1648 /* dynamic port forwarding */
1649 static void
1650 channel_pre_dynamic(struct ssh *ssh, Channel *c)
1651 {
1652 	const u_char *p;
1653 	u_int have;
1654 	int ret;
1655 
1656 	c->io_want = 0;
1657 	have = sshbuf_len(c->input);
1658 	debug2("channel %d: pre_dynamic: have %d", c->self, have);
1659 	/* sshbuf_dump(c->input, stderr); */
1660 	/* check if the fixed size part of the packet is in buffer. */
1661 	if (have < 3) {
1662 		/* need more */
1663 		c->io_want |= SSH_CHAN_IO_RFD;
1664 		return;
1665 	}
1666 	/* try to guess the protocol */
1667 	p = sshbuf_ptr(c->input);
1668 	/* XXX sshbuf_peek_u8? */
1669 	switch (p[0]) {
1670 	case 0x04:
1671 		ret = channel_decode_socks4(c, c->input, c->output);
1672 		break;
1673 	case 0x05:
1674 		ret = channel_decode_socks5(c, c->input, c->output);
1675 		break;
1676 	default:
1677 		ret = -1;
1678 		break;
1679 	}
1680 	if (ret < 0) {
1681 		chan_mark_dead(ssh, c);
1682 	} else if (ret == 0) {
1683 		debug2("channel %d: pre_dynamic: need more", c->self);
1684 		/* need more */
1685 		c->io_want |= SSH_CHAN_IO_RFD;
1686 		if (sshbuf_len(c->output))
1687 			c->io_want |= SSH_CHAN_IO_WFD;
1688 	} else {
1689 		/* switch to the next state */
1690 		c->type = SSH_CHANNEL_OPENING;
1691 		port_open_helper(ssh, c, "direct-tcpip");
1692 	}
1693 }
1694 
1695 /* simulate read-error */
1696 static void
1697 rdynamic_close(struct ssh *ssh, Channel *c)
1698 {
1699 	c->type = SSH_CHANNEL_OPEN;
1700 	channel_force_close(ssh, c, 0);
1701 }
1702 
1703 /* reverse dynamic port forwarding */
1704 static void
1705 channel_before_prepare_io_rdynamic(struct ssh *ssh, Channel *c)
1706 {
1707 	const u_char *p;
1708 	u_int have, len;
1709 	int r, ret;
1710 
1711 	have = sshbuf_len(c->output);
1712 	debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1713 	/* sshbuf_dump(c->output, stderr); */
1714 	/* EOF received */
1715 	if (c->flags & CHAN_EOF_RCVD) {
1716 		if ((r = sshbuf_consume(c->output, have)) != 0)
1717 			fatal_fr(r, "channel %d: consume", c->self);
1718 		rdynamic_close(ssh, c);
1719 		return;
1720 	}
1721 	/* check if the fixed size part of the packet is in buffer. */
1722 	if (have < 3)
1723 		return;
1724 	/* try to guess the protocol */
1725 	p = sshbuf_ptr(c->output);
1726 	switch (p[0]) {
1727 	case 0x04:
1728 		/* switch input/output for reverse forwarding */
1729 		ret = channel_decode_socks4(c, c->output, c->input);
1730 		break;
1731 	case 0x05:
1732 		ret = channel_decode_socks5(c, c->output, c->input);
1733 		break;
1734 	default:
1735 		ret = -1;
1736 		break;
1737 	}
1738 	if (ret < 0) {
1739 		rdynamic_close(ssh, c);
1740 	} else if (ret == 0) {
1741 		debug2("channel %d: pre_rdynamic: need more", c->self);
1742 		/* send socks request to peer */
1743 		len = sshbuf_len(c->input);
1744 		if (len > 0 && len < c->remote_window) {
1745 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1746 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1747 			    (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1748 			    (r = sshpkt_send(ssh)) != 0) {
1749 				fatal_fr(r, "channel %i: rdynamic", c->self);
1750 			}
1751 			if ((r = sshbuf_consume(c->input, len)) != 0)
1752 				fatal_fr(r, "channel %d: consume", c->self);
1753 			c->remote_window -= len;
1754 		}
1755 	} else if (rdynamic_connect_finish(ssh, c) < 0) {
1756 		/* the connect failed */
1757 		rdynamic_close(ssh, c);
1758 	}
1759 }
1760 
1761 /* This is our fake X11 server socket. */
1762 static void
1763 channel_post_x11_listener(struct ssh *ssh, Channel *c)
1764 {
1765 	Channel *nc;
1766 	struct sockaddr_storage addr;
1767 	int r, newsock, oerrno, remote_port;
1768 	socklen_t addrlen;
1769 	char buf[16384], *remote_ipaddr;
1770 
1771 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1772 		return;
1773 
1774 	debug("X11 connection requested.");
1775 	addrlen = sizeof(addr);
1776 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1777 	if (c->single_connection) {
1778 		oerrno = errno;
1779 		debug2("single_connection: closing X11 listener.");
1780 		channel_close_fd(ssh, c, &c->sock);
1781 		chan_mark_dead(ssh, c);
1782 		errno = oerrno;
1783 	}
1784 	if (newsock == -1) {
1785 		if (errno != EINTR && errno != EWOULDBLOCK &&
1786 		    errno != ECONNABORTED)
1787 			error("accept: %.100s", strerror(errno));
1788 		if (errno == EMFILE || errno == ENFILE)
1789 			c->notbefore = monotime() + 1;
1790 		return;
1791 	}
1792 	set_nodelay(newsock);
1793 	remote_ipaddr = get_peer_ipaddr(newsock);
1794 	remote_port = get_peer_port(newsock);
1795 	snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1796 	    remote_ipaddr, remote_port);
1797 
1798 	nc = channel_new(ssh, "x11-connection",
1799 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1800 	    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1801 	open_preamble(ssh, __func__, nc, "x11");
1802 	if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1803 	    (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1804 		fatal_fr(r, "channel %i: reply", c->self);
1805 	}
1806 	if ((r = sshpkt_send(ssh)) != 0)
1807 		fatal_fr(r, "channel %i: send", c->self);
1808 	free(remote_ipaddr);
1809 }
1810 
1811 static void
1812 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1813 {
1814 	char *local_ipaddr = get_local_ipaddr(c->sock);
1815 	int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1816 	char *remote_ipaddr = get_peer_ipaddr(c->sock);
1817 	int remote_port = get_peer_port(c->sock);
1818 	int r;
1819 
1820 	if (remote_port == -1) {
1821 		/* Fake addr/port to appease peers that validate it (Tectia) */
1822 		free(remote_ipaddr);
1823 		remote_ipaddr = xstrdup("127.0.0.1");
1824 		remote_port = 65535;
1825 	}
1826 
1827 	free(c->remote_name);
1828 	xasprintf(&c->remote_name,
1829 	    "%s: listening port %d for %.100s port %d, "
1830 	    "connect from %.200s port %d to %.100s port %d",
1831 	    rtype, c->listening_port, c->path, c->host_port,
1832 	    remote_ipaddr, remote_port, local_ipaddr, local_port);
1833 
1834 	open_preamble(ssh, __func__, c, rtype);
1835 	if (strcmp(rtype, "direct-tcpip") == 0) {
1836 		/* target host, port */
1837 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1838 		    (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1839 			fatal_fr(r, "channel %i: reply", c->self);
1840 	} else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1841 		/* target path */
1842 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1843 			fatal_fr(r, "channel %i: reply", c->self);
1844 	} else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1845 		/* listen path */
1846 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1847 			fatal_fr(r, "channel %i: reply", c->self);
1848 	} else {
1849 		/* listen address, port */
1850 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1851 		    (r = sshpkt_put_u32(ssh, local_port)) != 0)
1852 			fatal_fr(r, "channel %i: reply", c->self);
1853 	}
1854 	if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1855 		/* reserved for future owner/mode info */
1856 		if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1857 			fatal_fr(r, "channel %i: reply", c->self);
1858 	} else {
1859 		/* originator host and port */
1860 		if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1861 		    (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1862 			fatal_fr(r, "channel %i: reply", c->self);
1863 	}
1864 	if ((r = sshpkt_send(ssh)) != 0)
1865 		fatal_fr(r, "channel %i: send", c->self);
1866 	free(remote_ipaddr);
1867 	free(local_ipaddr);
1868 }
1869 
1870 void
1871 channel_set_x11_refuse_time(struct ssh *ssh, time_t refuse_time)
1872 {
1873 	ssh->chanctxt->x11_refuse_time = refuse_time;
1874 }
1875 
1876 /*
1877  * This socket is listening for connections to a forwarded TCP/IP port.
1878  */
1879 static void
1880 channel_post_port_listener(struct ssh *ssh, Channel *c)
1881 {
1882 	Channel *nc;
1883 	struct sockaddr_storage addr;
1884 	int newsock, nextstate;
1885 	socklen_t addrlen;
1886 	char *rtype;
1887 
1888 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1889 		return;
1890 
1891 	debug("Connection to port %d forwarding to %.100s port %d requested.",
1892 	    c->listening_port, c->path, c->host_port);
1893 
1894 	if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1895 		nextstate = SSH_CHANNEL_OPENING;
1896 		rtype = "forwarded-tcpip";
1897 	} else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1898 		nextstate = SSH_CHANNEL_OPENING;
1899 		rtype = "forwarded-streamlocal@openssh.com";
1900 	} else if (c->host_port == PORT_STREAMLOCAL) {
1901 		nextstate = SSH_CHANNEL_OPENING;
1902 		rtype = "direct-streamlocal@openssh.com";
1903 	} else if (c->host_port == 0) {
1904 		nextstate = SSH_CHANNEL_DYNAMIC;
1905 		rtype = "dynamic-tcpip";
1906 	} else {
1907 		nextstate = SSH_CHANNEL_OPENING;
1908 		rtype = "direct-tcpip";
1909 	}
1910 
1911 	addrlen = sizeof(addr);
1912 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1913 	if (newsock == -1) {
1914 		if (errno != EINTR && errno != EWOULDBLOCK &&
1915 		    errno != ECONNABORTED)
1916 			error("accept: %.100s", strerror(errno));
1917 		if (errno == EMFILE || errno == ENFILE)
1918 			c->notbefore = monotime() + 1;
1919 		return;
1920 	}
1921 	if (c->host_port != PORT_STREAMLOCAL)
1922 		set_nodelay(newsock);
1923 	nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1924 	    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1925 	nc->listening_port = c->listening_port;
1926 	nc->host_port = c->host_port;
1927 	if (c->path != NULL)
1928 		nc->path = xstrdup(c->path);
1929 
1930 	if (nextstate != SSH_CHANNEL_DYNAMIC)
1931 		port_open_helper(ssh, nc, rtype);
1932 }
1933 
1934 /*
1935  * This is the authentication agent socket listening for connections from
1936  * clients.
1937  */
1938 static void
1939 channel_post_auth_listener(struct ssh *ssh, Channel *c)
1940 {
1941 	Channel *nc;
1942 	int r, newsock;
1943 	struct sockaddr_storage addr;
1944 	socklen_t addrlen;
1945 
1946 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1947 		return;
1948 
1949 	addrlen = sizeof(addr);
1950 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1951 	if (newsock == -1) {
1952 		error("accept from auth socket: %.100s", strerror(errno));
1953 		if (errno == EMFILE || errno == ENFILE)
1954 			c->notbefore = monotime() + 1;
1955 		return;
1956 	}
1957 	nc = channel_new(ssh, "agent-connection",
1958 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1959 	    c->local_window_max, c->local_maxpacket,
1960 	    0, "accepted auth socket", 1);
1961 	open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1962 	if ((r = sshpkt_send(ssh)) != 0)
1963 		fatal_fr(r, "channel %i", c->self);
1964 }
1965 
1966 static void
1967 channel_post_connecting(struct ssh *ssh, Channel *c)
1968 {
1969 	int err = 0, sock, isopen, r;
1970 	socklen_t sz = sizeof(err);
1971 
1972 	if ((c->io_ready & SSH_CHAN_IO_SOCK_W) == 0)
1973 		return;
1974 	if (!c->have_remote_id)
1975 		fatal_f("channel %d: no remote id", c->self);
1976 	/* for rdynamic the OPEN_CONFIRMATION has been sent already */
1977 	isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1978 
1979 	if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1980 		err = errno;
1981 		error("getsockopt SO_ERROR failed");
1982 	}
1983 
1984 	if (err == 0) {
1985 		/* Non-blocking connection completed */
1986 		debug("channel %d: connected to %s port %d",
1987 		    c->self, c->connect_ctx.host, c->connect_ctx.port);
1988 		channel_connect_ctx_free(&c->connect_ctx);
1989 		c->type = SSH_CHANNEL_OPEN;
1990 		c->lastused = monotime();
1991 		if (isopen) {
1992 			/* no message necessary */
1993 		} else {
1994 			if ((r = sshpkt_start(ssh,
1995 			    SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1996 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1997 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1998 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1999 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
2000 			    (r = sshpkt_send(ssh)) != 0)
2001 				fatal_fr(r, "channel %i open confirm", c->self);
2002 		}
2003 		return;
2004 	}
2005 	if (err == EINTR || err == EAGAIN || err == EINPROGRESS)
2006 		return;
2007 
2008 	/* Non-blocking connection failed */
2009 	debug("channel %d: connection failed: %s", c->self, strerror(err));
2010 
2011 	/* Try next address, if any */
2012 	if ((sock = connect_next(&c->connect_ctx)) == -1) {
2013 		/* Exhausted all addresses for this destination */
2014 		error("connect_to %.100s port %d: failed.",
2015 		    c->connect_ctx.host, c->connect_ctx.port);
2016 		channel_connect_ctx_free(&c->connect_ctx);
2017 		if (isopen) {
2018 			rdynamic_close(ssh, c);
2019 		} else {
2020 			if ((r = sshpkt_start(ssh,
2021 			    SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
2022 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2023 			    (r = sshpkt_put_u32(ssh,
2024 			    SSH2_OPEN_CONNECT_FAILED)) != 0 ||
2025 			    (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
2026 			    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2027 			    (r = sshpkt_send(ssh)) != 0)
2028 				fatal_fr(r, "channel %i: failure", c->self);
2029 			chan_mark_dead(ssh, c);
2030 		}
2031 	}
2032 
2033 	/* New non-blocking connection in progress */
2034 	close(c->sock);
2035 	c->sock = c->rfd = c->wfd = sock;
2036 }
2037 
2038 static int
2039 channel_handle_rfd(struct ssh *ssh, Channel *c)
2040 {
2041 	char buf[CHAN_RBUF];
2042 	ssize_t len;
2043 	int r;
2044 	size_t nr = 0, have, avail, maxlen = CHANNEL_MAX_READ;
2045 
2046 	if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2047 		return 1; /* Shouldn't happen */
2048 	if ((avail = sshbuf_avail(c->input)) == 0)
2049 		return 1; /* Shouldn't happen */
2050 
2051 	/*
2052 	 * For "simple" channels (i.e. not datagram or filtered), we can
2053 	 * read directly to the channel buffer.
2054 	 */
2055 	if (c->input_filter == NULL && !c->datagram) {
2056 		/* Only OPEN channels have valid rwin */
2057 		if (c->type == SSH_CHANNEL_OPEN) {
2058 			if ((have = sshbuf_len(c->input)) >= c->remote_window)
2059 				return 1; /* shouldn't happen */
2060 			if (maxlen > c->remote_window - have)
2061 				maxlen = c->remote_window - have;
2062 		}
2063 		if (maxlen > avail)
2064 			maxlen = avail;
2065 		if ((r = sshbuf_read(c->rfd, c->input, maxlen, &nr)) != 0) {
2066 			if (errno == EINTR || errno == EAGAIN)
2067 				return 1;
2068 			debug2("channel %d: read failed rfd %d maxlen %zu: %s",
2069 			    c->self, c->rfd, maxlen, ssh_err(r));
2070 			goto rfail;
2071 		}
2072 		if (nr != 0)
2073 			c->lastused = monotime();
2074 		return 1;
2075 	}
2076 
2077 	len = read(c->rfd, buf, sizeof(buf));
2078 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2079 		return 1;
2080 	if (len <= 0) {
2081 		debug2("channel %d: read<=0 rfd %d len %zd: %s",
2082 		    c->self, c->rfd, len,
2083 		    len == 0 ? "closed" : strerror(errno));
2084  rfail:
2085 		if (c->type != SSH_CHANNEL_OPEN) {
2086 			debug2("channel %d: not open", c->self);
2087 			chan_mark_dead(ssh, c);
2088 			return -1;
2089 		} else {
2090 			chan_read_failed(ssh, c);
2091 		}
2092 		return -1;
2093 	}
2094 	c->lastused = monotime();
2095 	if (c->input_filter != NULL) {
2096 		if (c->input_filter(ssh, c, buf, len) == -1) {
2097 			debug2("channel %d: filter stops", c->self);
2098 			chan_read_failed(ssh, c);
2099 		}
2100 	} else if (c->datagram) {
2101 		if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
2102 			fatal_fr(r, "channel %i: put datagram", c->self);
2103 	}
2104 	return 1;
2105 }
2106 
2107 static int
2108 channel_handle_wfd(struct ssh *ssh, Channel *c)
2109 {
2110 	struct termios tio;
2111 	u_char *data = NULL, *buf; /* XXX const; need filter API change */
2112 	size_t dlen, olen = 0;
2113 	int r, len;
2114 
2115 	if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2116 		return 1;
2117 	if (sshbuf_len(c->output) == 0)
2118 		return 1;
2119 
2120 	/* Send buffered output data to the socket. */
2121 	olen = sshbuf_len(c->output);
2122 	if (c->output_filter != NULL) {
2123 		if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
2124 			debug2("channel %d: filter stops", c->self);
2125 			if (c->type != SSH_CHANNEL_OPEN)
2126 				chan_mark_dead(ssh, c);
2127 			else
2128 				chan_write_failed(ssh, c);
2129 			return -1;
2130 		}
2131 	} else if (c->datagram) {
2132 		if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2133 			fatal_fr(r, "channel %i: get datagram", c->self);
2134 		buf = data;
2135 	} else {
2136 		buf = data = sshbuf_mutable_ptr(c->output);
2137 		dlen = sshbuf_len(c->output);
2138 	}
2139 
2140 	if (c->datagram) {
2141 		/* ignore truncated writes, datagrams might get lost */
2142 		len = write(c->wfd, buf, dlen);
2143 		free(data);
2144 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
2145 			return 1;
2146 		if (len <= 0)
2147 			goto write_fail;
2148 		goto out;
2149 	}
2150 
2151 	len = write(c->wfd, buf, dlen);
2152 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2153 		return 1;
2154 	if (len <= 0) {
2155  write_fail:
2156 		if (c->type != SSH_CHANNEL_OPEN) {
2157 			debug2("channel %d: not open", c->self);
2158 			chan_mark_dead(ssh, c);
2159 			return -1;
2160 		} else {
2161 			chan_write_failed(ssh, c);
2162 		}
2163 		return -1;
2164 	}
2165 	c->lastused = monotime();
2166 	if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2167 		if (tcgetattr(c->wfd, &tio) == 0 &&
2168 		    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2169 			/*
2170 			 * Simulate echo to reduce the impact of
2171 			 * traffic analysis. We need to match the
2172 			 * size of a SSH2_MSG_CHANNEL_DATA message
2173 			 * (4 byte channel id + buf)
2174 			 */
2175 			if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2176 			    (r = sshpkt_send(ssh)) != 0)
2177 				fatal_fr(r, "channel %i: ignore", c->self);
2178 		}
2179 	}
2180 	if ((r = sshbuf_consume(c->output, len)) != 0)
2181 		fatal_fr(r, "channel %i: consume", c->self);
2182  out:
2183 	c->local_consumed += olen - sshbuf_len(c->output);
2184 
2185 	return 1;
2186 }
2187 
2188 static int
2189 channel_handle_efd_write(struct ssh *ssh, Channel *c)
2190 {
2191 	int r;
2192 	ssize_t len;
2193 
2194 	if ((c->io_ready & SSH_CHAN_IO_EFD_W) == 0)
2195 		return 1;
2196 	if (sshbuf_len(c->extended) == 0)
2197 		return 1;
2198 
2199 	len = write(c->efd, sshbuf_ptr(c->extended),
2200 	    sshbuf_len(c->extended));
2201 	debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2202 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2203 		return 1;
2204 	if (len <= 0) {
2205 		debug2("channel %d: closing write-efd %d", c->self, c->efd);
2206 		channel_close_fd(ssh, c, &c->efd);
2207 	} else {
2208 		if ((r = sshbuf_consume(c->extended, len)) != 0)
2209 			fatal_fr(r, "channel %i: consume", c->self);
2210 		c->local_consumed += len;
2211 		c->lastused = monotime();
2212 	}
2213 	return 1;
2214 }
2215 
2216 static int
2217 channel_handle_efd_read(struct ssh *ssh, Channel *c)
2218 {
2219 	char buf[CHAN_RBUF];
2220 	int r;
2221 	ssize_t len;
2222 
2223 	if ((c->io_ready & SSH_CHAN_IO_EFD_R) == 0)
2224 		return 1;
2225 
2226 	len = read(c->efd, buf, sizeof(buf));
2227 	debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2228 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2229 		return 1;
2230 	if (len <= 0) {
2231 		debug2("channel %d: closing read-efd %d", c->self, c->efd);
2232 		channel_close_fd(ssh, c, &c->efd);
2233 		return 1;
2234 	}
2235 	c->lastused = monotime();
2236 	if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2237 		debug3("channel %d: discard efd", c->self);
2238 	else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2239 		fatal_fr(r, "channel %i: append", c->self);
2240 	return 1;
2241 }
2242 
2243 static int
2244 channel_handle_efd(struct ssh *ssh, Channel *c)
2245 {
2246 	if (c->efd == -1)
2247 		return 1;
2248 
2249 	/** XXX handle drain efd, too */
2250 
2251 	if (c->extended_usage == CHAN_EXTENDED_WRITE)
2252 		return channel_handle_efd_write(ssh, c);
2253 	else if (c->extended_usage == CHAN_EXTENDED_READ ||
2254 	    c->extended_usage == CHAN_EXTENDED_IGNORE)
2255 		return channel_handle_efd_read(ssh, c);
2256 
2257 	return 1;
2258 }
2259 
2260 static int
2261 channel_check_window(struct ssh *ssh, Channel *c)
2262 {
2263 	int r;
2264 
2265 	if (c->type == SSH_CHANNEL_OPEN &&
2266 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2267 	    ((c->local_window_max - c->local_window >
2268 	    c->local_maxpacket*3) ||
2269 	    c->local_window < c->local_window_max/2) &&
2270 	    c->local_consumed > 0) {
2271 		if (!c->have_remote_id)
2272 			fatal_f("channel %d: no remote id", c->self);
2273 		if ((r = sshpkt_start(ssh,
2274 		    SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2275 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2276 		    (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2277 		    (r = sshpkt_send(ssh)) != 0) {
2278 			fatal_fr(r, "channel %i", c->self);
2279 		}
2280 		debug2("channel %d: window %d sent adjust %d", c->self,
2281 		    c->local_window, c->local_consumed);
2282 		c->local_window += c->local_consumed;
2283 		c->local_consumed = 0;
2284 	}
2285 	return 1;
2286 }
2287 
2288 static void
2289 channel_post_open(struct ssh *ssh, Channel *c)
2290 {
2291 	channel_handle_rfd(ssh, c);
2292 	channel_handle_wfd(ssh, c);
2293 	channel_handle_efd(ssh, c);
2294 	channel_check_window(ssh, c);
2295 }
2296 
2297 static u_int
2298 read_mux(struct ssh *ssh, Channel *c, u_int need)
2299 {
2300 	char buf[CHAN_RBUF];
2301 	ssize_t len;
2302 	u_int rlen;
2303 	int r;
2304 
2305 	if (sshbuf_len(c->input) < need) {
2306 		rlen = need - sshbuf_len(c->input);
2307 		len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2308 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
2309 			return sshbuf_len(c->input);
2310 		if (len <= 0) {
2311 			debug2("channel %d: ctl read<=0 rfd %d len %zd",
2312 			    c->self, c->rfd, len);
2313 			chan_read_failed(ssh, c);
2314 			return 0;
2315 		} else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2316 			fatal_fr(r, "channel %i: append", c->self);
2317 	}
2318 	return sshbuf_len(c->input);
2319 }
2320 
2321 static void
2322 channel_post_mux_client_read(struct ssh *ssh, Channel *c)
2323 {
2324 	u_int need;
2325 
2326 	if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2327 		return;
2328 	if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2329 		return;
2330 	if (c->mux_pause)
2331 		return;
2332 
2333 	/*
2334 	 * Don't not read past the precise end of packets to
2335 	 * avoid disrupting fd passing.
2336 	 */
2337 	if (read_mux(ssh, c, 4) < 4) /* read header */
2338 		return;
2339 	/* XXX sshbuf_peek_u32 */
2340 	need = PEEK_U32(sshbuf_ptr(c->input));
2341 #define CHANNEL_MUX_MAX_PACKET	(256 * 1024)
2342 	if (need > CHANNEL_MUX_MAX_PACKET) {
2343 		debug2("channel %d: packet too big %u > %u",
2344 		    c->self, CHANNEL_MUX_MAX_PACKET, need);
2345 		chan_rcvd_oclose(ssh, c);
2346 		return;
2347 	}
2348 	if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2349 		return;
2350 	if (c->mux_rcb(ssh, c) != 0) {
2351 		debug("channel %d: mux_rcb failed", c->self);
2352 		chan_mark_dead(ssh, c);
2353 		return;
2354 	}
2355 }
2356 
2357 static void
2358 channel_post_mux_client_write(struct ssh *ssh, Channel *c)
2359 {
2360 	ssize_t len;
2361 	int r;
2362 
2363 	if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2364 		return;
2365 	if (sshbuf_len(c->output) == 0)
2366 		return;
2367 
2368 	len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2369 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2370 		return;
2371 	if (len <= 0) {
2372 		chan_mark_dead(ssh, c);
2373 		return;
2374 	}
2375 	if ((r = sshbuf_consume(c->output, len)) != 0)
2376 		fatal_fr(r, "channel %i: consume", c->self);
2377 }
2378 
2379 static void
2380 channel_post_mux_client(struct ssh *ssh, Channel *c)
2381 {
2382 	channel_post_mux_client_read(ssh, c);
2383 	channel_post_mux_client_write(ssh, c);
2384 }
2385 
2386 static void
2387 channel_post_mux_listener(struct ssh *ssh, Channel *c)
2388 {
2389 	Channel *nc;
2390 	struct sockaddr_storage addr;
2391 	socklen_t addrlen;
2392 	int newsock;
2393 	uid_t euid;
2394 	gid_t egid;
2395 
2396 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
2397 		return;
2398 
2399 	debug("multiplexing control connection");
2400 
2401 	/*
2402 	 * Accept connection on control socket
2403 	 */
2404 	memset(&addr, 0, sizeof(addr));
2405 	addrlen = sizeof(addr);
2406 	if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2407 	    &addrlen)) == -1) {
2408 		error_f("accept: %s", strerror(errno));
2409 		if (errno == EMFILE || errno == ENFILE)
2410 			c->notbefore = monotime() + 1;
2411 		return;
2412 	}
2413 
2414 	if (getpeereid(newsock, &euid, &egid) == -1) {
2415 		error_f("getpeereid failed: %s", strerror(errno));
2416 		close(newsock);
2417 		return;
2418 	}
2419 	if ((euid != 0) && (getuid() != euid)) {
2420 		error("multiplex uid mismatch: peer euid %u != uid %u",
2421 		    (u_int)euid, (u_int)getuid());
2422 		close(newsock);
2423 		return;
2424 	}
2425 	nc = channel_new(ssh, "mux-control", SSH_CHANNEL_MUX_CLIENT,
2426 	    newsock, newsock, -1, c->local_window_max,
2427 	    c->local_maxpacket, 0, "mux-control", 1);
2428 	nc->mux_rcb = c->mux_rcb;
2429 	debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2430 	/* establish state */
2431 	nc->mux_rcb(ssh, nc);
2432 	/* mux state transitions must not elicit protocol messages */
2433 	nc->flags |= CHAN_LOCAL;
2434 }
2435 
2436 static void
2437 channel_handler_init(struct ssh_channels *sc)
2438 {
2439 	chan_fn **pre, **post;
2440 
2441 	if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2442 	    (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2443 		fatal_f("allocation failed");
2444 
2445 	pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
2446 	pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
2447 	pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
2448 	pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
2449 	pre[SSH_CHANNEL_UNIX_LISTENER] =	&channel_pre_listener;
2450 	pre[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_pre_listener;
2451 	pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
2452 	pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
2453 	pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
2454 	pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
2455 	pre[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_pre_connecting;
2456 	pre[SSH_CHANNEL_MUX_LISTENER] =		&channel_pre_listener;
2457 	pre[SSH_CHANNEL_MUX_CLIENT] =		&channel_pre_mux_client;
2458 
2459 	post[SSH_CHANNEL_OPEN] =		&channel_post_open;
2460 	post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
2461 	post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
2462 	post[SSH_CHANNEL_UNIX_LISTENER] =	&channel_post_port_listener;
2463 	post[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_post_port_listener;
2464 	post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
2465 	post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
2466 	post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
2467 	post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
2468 	post[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_post_connecting;
2469 	post[SSH_CHANNEL_MUX_LISTENER] =	&channel_post_mux_listener;
2470 	post[SSH_CHANNEL_MUX_CLIENT] =		&channel_post_mux_client;
2471 
2472 	sc->channel_pre = pre;
2473 	sc->channel_post = post;
2474 }
2475 
2476 /* gc dead channels */
2477 static void
2478 channel_garbage_collect(struct ssh *ssh, Channel *c)
2479 {
2480 	if (c == NULL)
2481 		return;
2482 	if (c->detach_user != NULL) {
2483 		if (!chan_is_dead(ssh, c, c->detach_close))
2484 			return;
2485 
2486 		debug2("channel %d: gc: notify user", c->self);
2487 		c->detach_user(ssh, c->self, 0, NULL);
2488 		/* if we still have a callback */
2489 		if (c->detach_user != NULL)
2490 			return;
2491 		debug2("channel %d: gc: user detached", c->self);
2492 	}
2493 	if (!chan_is_dead(ssh, c, 1))
2494 		return;
2495 	debug2("channel %d: garbage collecting", c->self);
2496 	channel_free(ssh, c);
2497 }
2498 
2499 enum channel_table { CHAN_PRE, CHAN_POST };
2500 
2501 static void
2502 channel_handler(struct ssh *ssh, int table, struct timespec *timeout)
2503 {
2504 	struct ssh_channels *sc = ssh->chanctxt;
2505 	chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2506 	u_int i, oalloc;
2507 	Channel *c;
2508 	time_t now;
2509 
2510 	now = monotime();
2511 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2512 		c = sc->channels[i];
2513 		if (c == NULL)
2514 			continue;
2515 		/* Try to keep IO going while rekeying */
2516 		if (ssh_packet_is_rekeying(ssh) && c->type != SSH_CHANNEL_OPEN)
2517 			continue;
2518 		if (c->delayed) {
2519 			if (table == CHAN_PRE)
2520 				c->delayed = 0;
2521 			else
2522 				continue;
2523 		}
2524 		if (ftab[c->type] != NULL) {
2525 			if (table == CHAN_PRE &&
2526 			    c->type == SSH_CHANNEL_OPEN &&
2527 			    c->inactive_deadline != 0 && c->lastused != 0 &&
2528 			    now >= c->lastused + c->inactive_deadline) {
2529 				/* channel closed for inactivity */
2530 				verbose("channel %d: closing after %u seconds "
2531 				    "of inactivity", c->self,
2532 				    c->inactive_deadline);
2533 				channel_force_close(ssh, c, 1);
2534 			} else if (c->notbefore <= now) {
2535 				/* Run handlers that are not paused. */
2536 				(*ftab[c->type])(ssh, c);
2537 				/* inactivity timeouts must interrupt poll() */
2538 				if (timeout != NULL &&
2539 				    c->type == SSH_CHANNEL_OPEN &&
2540 				    c->lastused != 0 &&
2541 				    c->inactive_deadline != 0) {
2542 					ptimeout_deadline_monotime(timeout,
2543 					    c->lastused + c->inactive_deadline);
2544 				}
2545 			} else if (timeout != NULL) {
2546 				/*
2547 				 * Arrange for poll() wakeup when channel pause
2548 				 * timer expires.
2549 				 */
2550 				ptimeout_deadline_monotime(timeout,
2551 				    c->notbefore);
2552 			}
2553 		}
2554 		channel_garbage_collect(ssh, c);
2555 	}
2556 }
2557 
2558 /*
2559  * Create sockets before preparing IO.
2560  * This is necessary for things that need to happen after reading
2561  * the network-input but need to be completed before IO event setup, e.g.
2562  * because they may create new channels.
2563  */
2564 static void
2565 channel_before_prepare_io(struct ssh *ssh)
2566 {
2567 	struct ssh_channels *sc = ssh->chanctxt;
2568 	Channel *c;
2569 	u_int i, oalloc;
2570 
2571 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2572 		c = sc->channels[i];
2573 		if (c == NULL)
2574 			continue;
2575 		if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2576 			channel_before_prepare_io_rdynamic(ssh, c);
2577 	}
2578 }
2579 
2580 static void
2581 dump_channel_poll(const char *func, const char *what, Channel *c,
2582     u_int pollfd_offset, struct pollfd *pfd)
2583 {
2584 #ifdef DEBUG_CHANNEL_POLL
2585 	debug3("%s: channel %d: %s r%d w%d e%d s%d c->pfds [ %d %d %d %d ] "
2586 	    "io_want 0x%02x io_ready 0x%02x pfd[%u].fd=%d "
2587 	    "pfd.ev 0x%02x pfd.rev 0x%02x", func, c->self, what,
2588 	    c->rfd, c->wfd, c->efd, c->sock,
2589 	    c->pfds[0], c->pfds[1], c->pfds[2], c->pfds[3],
2590 	    c->io_want, c->io_ready,
2591 	    pollfd_offset, pfd->fd, pfd->events, pfd->revents);
2592 #endif
2593 }
2594 
2595 /* Prepare pollfd entries for a single channel */
2596 static void
2597 channel_prepare_pollfd(Channel *c, u_int *next_pollfd,
2598     struct pollfd *pfd, u_int npfd)
2599 {
2600 	u_int ev, p = *next_pollfd;
2601 
2602 	if (c == NULL)
2603 		return;
2604 	if (p + 4 > npfd) {
2605 		/* Shouldn't happen */
2606 		fatal_f("channel %d: bad pfd offset %u (max %u)",
2607 		    c->self, p, npfd);
2608 	}
2609 	c->pfds[0] = c->pfds[1] = c->pfds[2] = c->pfds[3] = -1;
2610 	/*
2611 	 * prepare c->rfd
2612 	 *
2613 	 * This is a special case, since c->rfd might be the same as
2614 	 * c->wfd, c->efd and/or c->sock. Handle those here if they want
2615 	 * IO too.
2616 	 */
2617 	if (c->rfd != -1) {
2618 		ev = 0;
2619 		if ((c->io_want & SSH_CHAN_IO_RFD) != 0)
2620 			ev |= POLLIN;
2621 		/* rfd == wfd */
2622 		if (c->wfd == c->rfd) {
2623 			if ((c->io_want & SSH_CHAN_IO_WFD) != 0)
2624 				ev |= POLLOUT;
2625 		}
2626 		/* rfd == efd */
2627 		if (c->efd == c->rfd) {
2628 			if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2629 				ev |= POLLIN;
2630 			if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2631 				ev |= POLLOUT;
2632 		}
2633 		/* rfd == sock */
2634 		if (c->sock == c->rfd) {
2635 			if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2636 				ev |= POLLIN;
2637 			if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2638 				ev |= POLLOUT;
2639 		}
2640 		/* Pack a pfd entry if any event armed for this fd */
2641 		if (ev != 0) {
2642 			c->pfds[0] = p;
2643 			pfd[p].fd = c->rfd;
2644 			pfd[p].events = ev;
2645 			dump_channel_poll(__func__, "rfd", c, p, &pfd[p]);
2646 			p++;
2647 		}
2648 	}
2649 	/* prepare c->wfd if wanting IO and not already handled above */
2650 	if (c->wfd != -1 && c->rfd != c->wfd) {
2651 		ev = 0;
2652 		if ((c->io_want & SSH_CHAN_IO_WFD))
2653 			ev |= POLLOUT;
2654 		/* Pack a pfd entry if any event armed for this fd */
2655 		if (ev != 0) {
2656 			c->pfds[1] = p;
2657 			pfd[p].fd = c->wfd;
2658 			pfd[p].events = ev;
2659 			dump_channel_poll(__func__, "wfd", c, p, &pfd[p]);
2660 			p++;
2661 		}
2662 	}
2663 	/* prepare c->efd if wanting IO and not already handled above */
2664 	if (c->efd != -1 && c->rfd != c->efd) {
2665 		ev = 0;
2666 		if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2667 			ev |= POLLIN;
2668 		if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2669 			ev |= POLLOUT;
2670 		/* Pack a pfd entry if any event armed for this fd */
2671 		if (ev != 0) {
2672 			c->pfds[2] = p;
2673 			pfd[p].fd = c->efd;
2674 			pfd[p].events = ev;
2675 			dump_channel_poll(__func__, "efd", c, p, &pfd[p]);
2676 			p++;
2677 		}
2678 	}
2679 	/* prepare c->sock if wanting IO and not already handled above */
2680 	if (c->sock != -1 && c->rfd != c->sock) {
2681 		ev = 0;
2682 		if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2683 			ev |= POLLIN;
2684 		if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2685 			ev |= POLLOUT;
2686 		/* Pack a pfd entry if any event armed for this fd */
2687 		if (ev != 0) {
2688 			c->pfds[3] = p;
2689 			pfd[p].fd = c->sock;
2690 			pfd[p].events = 0;
2691 			dump_channel_poll(__func__, "sock", c, p, &pfd[p]);
2692 			p++;
2693 		}
2694 	}
2695 	*next_pollfd = p;
2696 }
2697 
2698 /* * Allocate/prepare poll structure */
2699 void
2700 channel_prepare_poll(struct ssh *ssh, struct pollfd **pfdp, u_int *npfd_allocp,
2701     u_int *npfd_activep, u_int npfd_reserved, struct timespec *timeout)
2702 {
2703 	struct ssh_channels *sc = ssh->chanctxt;
2704 	u_int i, oalloc, p, npfd = npfd_reserved;
2705 
2706 	channel_before_prepare_io(ssh); /* might create a new channel */
2707 	/* clear out I/O flags from last poll */
2708 	for (i = 0; i < sc->channels_alloc; i++) {
2709 		if (sc->channels[i] == NULL)
2710 			continue;
2711 		sc->channels[i]->io_want = sc->channels[i]->io_ready = 0;
2712 	}
2713 	/* Allocate 4x pollfd for each channel (rfd, wfd, efd, sock) */
2714 	if (sc->channels_alloc >= (INT_MAX / 4) - npfd_reserved)
2715 		fatal_f("too many channels"); /* shouldn't happen */
2716 	npfd += sc->channels_alloc * 4;
2717 	if (npfd > *npfd_allocp) {
2718 		*pfdp = xrecallocarray(*pfdp, *npfd_allocp,
2719 		    npfd, sizeof(**pfdp));
2720 		*npfd_allocp = npfd;
2721 	}
2722 	*npfd_activep = npfd_reserved;
2723 	oalloc = sc->channels_alloc;
2724 
2725 	channel_handler(ssh, CHAN_PRE, timeout);
2726 
2727 	if (oalloc != sc->channels_alloc) {
2728 		/* shouldn't happen */
2729 		fatal_f("channels_alloc changed during CHAN_PRE "
2730 		    "(was %u, now %u)", oalloc, sc->channels_alloc);
2731 	}
2732 
2733 	/* Prepare pollfd */
2734 	p = npfd_reserved;
2735 	for (i = 0; i < sc->channels_alloc; i++)
2736 		channel_prepare_pollfd(sc->channels[i], &p, *pfdp, npfd);
2737 	*npfd_activep = p;
2738 }
2739 
2740 static void
2741 fd_ready(Channel *c, int p, struct pollfd *pfds, u_int npfd, int fd,
2742     const char *what, u_int revents_mask, u_int ready)
2743 {
2744 	struct pollfd *pfd = &pfds[p];
2745 
2746 	if (fd == -1)
2747 		return;
2748 	if (p == -1 || (u_int)p >= npfd)
2749 		fatal_f("channel %d: bad pfd %d (max %u)", c->self, p, npfd);
2750 	dump_channel_poll(__func__, what, c, p, pfd);
2751 	if (pfd->fd != fd) {
2752 		fatal("channel %d: inconsistent %s fd=%d pollfd[%u].fd %d "
2753 		    "r%d w%d e%d s%d", c->self, what, fd, p, pfd->fd,
2754 		    c->rfd, c->wfd, c->efd, c->sock);
2755 	}
2756 	if ((pfd->revents & POLLNVAL) != 0) {
2757 		fatal("channel %d: invalid %s pollfd[%u].fd %d r%d w%d e%d s%d",
2758 		    c->self, what, p, pfd->fd, c->rfd, c->wfd, c->efd, c->sock);
2759 	}
2760 	if ((pfd->revents & (revents_mask|POLLHUP|POLLERR)) != 0)
2761 		c->io_ready |= ready & c->io_want;
2762 }
2763 
2764 /*
2765  * After poll, perform any appropriate operations for channels which have
2766  * events pending.
2767  */
2768 void
2769 channel_after_poll(struct ssh *ssh, struct pollfd *pfd, u_int npfd)
2770 {
2771 	struct ssh_channels *sc = ssh->chanctxt;
2772 	u_int i;
2773 	int p;
2774 	Channel *c;
2775 
2776 #ifdef DEBUG_CHANNEL_POLL
2777 	for (p = 0; p < (int)npfd; p++) {
2778 		if (pfd[p].revents == 0)
2779 			continue;
2780 		debug_f("pfd[%u].fd %d rev 0x%04x",
2781 		    p, pfd[p].fd, pfd[p].revents);
2782 	}
2783 #endif
2784 
2785 	/* Convert pollfd into c->io_ready */
2786 	for (i = 0; i < sc->channels_alloc; i++) {
2787 		c = sc->channels[i];
2788 		if (c == NULL)
2789 			continue;
2790 		/* if rfd is shared with efd/sock then wfd should be too */
2791 		if (c->rfd != -1 && c->wfd != -1 && c->rfd != c->wfd &&
2792 		    (c->rfd == c->efd || c->rfd == c->sock)) {
2793 			/* Shouldn't happen */
2794 			fatal_f("channel %d: unexpected fds r%d w%d e%d s%d",
2795 			    c->self, c->rfd, c->wfd, c->efd, c->sock);
2796 		}
2797 		c->io_ready = 0;
2798 		/* rfd, potentially shared with wfd, efd and sock */
2799 		if (c->rfd != -1 && (p = c->pfds[0]) != -1) {
2800 			fd_ready(c, p, pfd, npfd, c->rfd,
2801 			    "rfd", POLLIN, SSH_CHAN_IO_RFD);
2802 			if (c->rfd == c->wfd) {
2803 				fd_ready(c, p, pfd, npfd, c->wfd,
2804 				    "wfd/r", POLLOUT, SSH_CHAN_IO_WFD);
2805 			}
2806 			if (c->rfd == c->efd) {
2807 				fd_ready(c, p, pfd, npfd, c->efd,
2808 				    "efdr/r", POLLIN, SSH_CHAN_IO_EFD_R);
2809 				fd_ready(c, p, pfd, npfd, c->efd,
2810 				    "efdw/r", POLLOUT, SSH_CHAN_IO_EFD_W);
2811 			}
2812 			if (c->rfd == c->sock) {
2813 				fd_ready(c, p, pfd, npfd, c->sock,
2814 				    "sockr/r", POLLIN, SSH_CHAN_IO_SOCK_R);
2815 				fd_ready(c, p, pfd, npfd, c->sock,
2816 				    "sockw/r", POLLOUT, SSH_CHAN_IO_SOCK_W);
2817 			}
2818 			dump_channel_poll(__func__, "rfd", c, p, pfd);
2819 		}
2820 		/* wfd */
2821 		if (c->wfd != -1 && c->wfd != c->rfd &&
2822 		    (p = c->pfds[1]) != -1) {
2823 			fd_ready(c, p, pfd, npfd, c->wfd,
2824 			    "wfd", POLLOUT, SSH_CHAN_IO_WFD);
2825 			dump_channel_poll(__func__, "wfd", c, p, pfd);
2826 		}
2827 		/* efd */
2828 		if (c->efd != -1 && c->efd != c->rfd &&
2829 		    (p = c->pfds[2]) != -1) {
2830 			fd_ready(c, p, pfd, npfd, c->efd,
2831 			    "efdr", POLLIN, SSH_CHAN_IO_EFD_R);
2832 			fd_ready(c, p, pfd, npfd, c->efd,
2833 			    "efdw", POLLOUT, SSH_CHAN_IO_EFD_W);
2834 			dump_channel_poll(__func__, "efd", c, p, pfd);
2835 		}
2836 		/* sock */
2837 		if (c->sock != -1 && c->sock != c->rfd &&
2838 		    (p = c->pfds[3]) != -1) {
2839 			fd_ready(c, p, pfd, npfd, c->sock,
2840 			    "sockr", POLLIN, SSH_CHAN_IO_SOCK_R);
2841 			fd_ready(c, p, pfd, npfd, c->sock,
2842 			    "sockw", POLLOUT, SSH_CHAN_IO_SOCK_W);
2843 			dump_channel_poll(__func__, "sock", c, p, pfd);
2844 		}
2845 	}
2846 	channel_handler(ssh, CHAN_POST, NULL);
2847 }
2848 
2849 /*
2850  * Enqueue data for channels with open or draining c->input.
2851  * Returns non-zero if a packet was enqueued.
2852  */
2853 static int
2854 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2855 {
2856 	size_t len, plen;
2857 	const u_char *pkt;
2858 	int r;
2859 
2860 	if ((len = sshbuf_len(c->input)) == 0) {
2861 		if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2862 			/*
2863 			 * input-buffer is empty and read-socket shutdown:
2864 			 * tell peer, that we will not send more data:
2865 			 * send IEOF.
2866 			 * hack for extended data: delay EOF if EFD still
2867 			 * in use.
2868 			 */
2869 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
2870 				debug2("channel %d: "
2871 				    "ibuf_empty delayed efd %d/(%zu)",
2872 				    c->self, c->efd, sshbuf_len(c->extended));
2873 			else
2874 				chan_ibuf_empty(ssh, c);
2875 		}
2876 		return 0;
2877 	}
2878 
2879 	if (!c->have_remote_id)
2880 		fatal_f("channel %d: no remote id", c->self);
2881 
2882 	if (c->datagram) {
2883 		/* Check datagram will fit; drop if not */
2884 		if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2885 			fatal_fr(r, "channel %i: get datagram", c->self);
2886 		/*
2887 		 * XXX this does tail-drop on the datagram queue which is
2888 		 * usually suboptimal compared to head-drop. Better to have
2889 		 * backpressure at read time? (i.e. read + discard)
2890 		 */
2891 		if (plen > c->remote_window || plen > c->remote_maxpacket) {
2892 			debug("channel %d: datagram too big", c->self);
2893 			return 0;
2894 		}
2895 		/* Enqueue it */
2896 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2897 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2898 		    (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2899 		    (r = sshpkt_send(ssh)) != 0)
2900 			fatal_fr(r, "channel %i: send datagram", c->self);
2901 		c->remote_window -= plen;
2902 		return 1;
2903 	}
2904 
2905 	/* Enqueue packet for buffered data. */
2906 	if (len > c->remote_window)
2907 		len = c->remote_window;
2908 	if (len > c->remote_maxpacket)
2909 		len = c->remote_maxpacket;
2910 	if (len == 0)
2911 		return 0;
2912 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2913 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2914 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2915 	    (r = sshpkt_send(ssh)) != 0)
2916 		fatal_fr(r, "channel %i: send data", c->self);
2917 	if ((r = sshbuf_consume(c->input, len)) != 0)
2918 		fatal_fr(r, "channel %i: consume", c->self);
2919 	c->remote_window -= len;
2920 	return 1;
2921 }
2922 
2923 /*
2924  * Enqueue data for channels with open c->extended in read mode.
2925  * Returns non-zero if a packet was enqueued.
2926  */
2927 static int
2928 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2929 {
2930 	size_t len;
2931 	int r;
2932 
2933 	if ((len = sshbuf_len(c->extended)) == 0)
2934 		return 0;
2935 
2936 	debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2937 	    c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2938 	if (len > c->remote_window)
2939 		len = c->remote_window;
2940 	if (len > c->remote_maxpacket)
2941 		len = c->remote_maxpacket;
2942 	if (len == 0)
2943 		return 0;
2944 	if (!c->have_remote_id)
2945 		fatal_f("channel %d: no remote id", c->self);
2946 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2947 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2948 	    (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2949 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2950 	    (r = sshpkt_send(ssh)) != 0)
2951 		fatal_fr(r, "channel %i: data", c->self);
2952 	if ((r = sshbuf_consume(c->extended, len)) != 0)
2953 		fatal_fr(r, "channel %i: consume", c->self);
2954 	c->remote_window -= len;
2955 	debug2("channel %d: sent ext data %zu", c->self, len);
2956 	return 1;
2957 }
2958 
2959 /*
2960  * If there is data to send to the connection, enqueue some of it now.
2961  * Returns non-zero if data was enqueued.
2962  */
2963 int
2964 channel_output_poll(struct ssh *ssh)
2965 {
2966 	struct ssh_channels *sc = ssh->chanctxt;
2967 	Channel *c;
2968 	u_int i;
2969 	int ret = 0;
2970 
2971 	for (i = 0; i < sc->channels_alloc; i++) {
2972 		c = sc->channels[i];
2973 		if (c == NULL)
2974 			continue;
2975 
2976 		/*
2977 		 * We are only interested in channels that can have buffered
2978 		 * incoming data.
2979 		 */
2980 		if (c->type != SSH_CHANNEL_OPEN)
2981 			continue;
2982 		if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2983 			/* XXX is this true? */
2984 			debug3("channel %d: will not send data after close",
2985 			    c->self);
2986 			continue;
2987 		}
2988 
2989 		/* Get the amount of buffered data for this channel. */
2990 		if (c->istate == CHAN_INPUT_OPEN ||
2991 		    c->istate == CHAN_INPUT_WAIT_DRAIN)
2992 			ret |= channel_output_poll_input_open(ssh, c);
2993 		/* Send extended data, i.e. stderr */
2994 		if (!(c->flags & CHAN_EOF_SENT) &&
2995 		    c->extended_usage == CHAN_EXTENDED_READ)
2996 			ret |= channel_output_poll_extended_read(ssh, c);
2997 	}
2998 	return ret;
2999 }
3000 
3001 /* -- mux proxy support  */
3002 
3003 /*
3004  * When multiplexing channel messages for mux clients we have to deal
3005  * with downstream messages from the mux client and upstream messages
3006  * from the ssh server:
3007  * 1) Handling downstream messages is straightforward and happens
3008  *    in channel_proxy_downstream():
3009  *    - We forward all messages (mostly) unmodified to the server.
3010  *    - However, in order to route messages from upstream to the correct
3011  *      downstream client, we have to replace the channel IDs used by the
3012  *      mux clients with a unique channel ID because the mux clients might
3013  *      use conflicting channel IDs.
3014  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
3015  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
3016  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
3017  *      with the newly allocated channel ID.
3018  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
3019  *    channels and processed by channel_proxy_upstream(). The local channel ID
3020  *    is then translated back to the original mux client ID.
3021  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
3022  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
3023  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
3024  *    downstream mux client are removed.
3025  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
3026  *    requires more work, because they are not addressed to a specific
3027  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
3028  *    out whether the request is addressed to the local client or a
3029  *    specific downstream client based on the listen-address/port.
3030  * 6) Agent and X11-Forwarding have a similar problem and are currently
3031  *    not supported as the matching session/channel cannot be identified
3032  *    easily.
3033  */
3034 
3035 /*
3036  * receive packets from downstream mux clients:
3037  * channel callback fired on read from mux client, creates
3038  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
3039  * on channel creation.
3040  */
3041 int
3042 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
3043 {
3044 	Channel *c = NULL;
3045 	struct sshbuf *original = NULL, *modified = NULL;
3046 	const u_char *cp;
3047 	char *ctype = NULL, *listen_host = NULL;
3048 	u_char type;
3049 	size_t have;
3050 	int ret = -1, r;
3051 	u_int id, remote_id, listen_port;
3052 
3053 	/* sshbuf_dump(downstream->input, stderr); */
3054 	if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
3055 	    != 0) {
3056 		error_fr(r, "parse");
3057 		return -1;
3058 	}
3059 	if (have < 2) {
3060 		error_f("short message");
3061 		return -1;
3062 	}
3063 	type = cp[1];
3064 	/* skip padlen + type */
3065 	cp += 2;
3066 	have -= 2;
3067 	if (ssh_packet_log_type(type))
3068 		debug3_f("channel %u: down->up: type %u",
3069 		    downstream->self, type);
3070 
3071 	switch (type) {
3072 	case SSH2_MSG_CHANNEL_OPEN:
3073 		if ((original = sshbuf_from(cp, have)) == NULL ||
3074 		    (modified = sshbuf_new()) == NULL) {
3075 			error_f("alloc");
3076 			goto out;
3077 		}
3078 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
3079 		    (r = sshbuf_get_u32(original, &id)) != 0) {
3080 			error_fr(r, "parse");
3081 			goto out;
3082 		}
3083 		c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3084 		    -1, -1, -1, 0, 0, 0, ctype, 1);
3085 		c->mux_ctx = downstream;	/* point to mux client */
3086 		c->mux_downstream_id = id;	/* original downstream id */
3087 		if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
3088 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3089 		    (r = sshbuf_putb(modified, original)) != 0) {
3090 			error_fr(r, "compose");
3091 			channel_free(ssh, c);
3092 			goto out;
3093 		}
3094 		break;
3095 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3096 		/*
3097 		 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
3098 		 * need to parse 'remote_id' instead of 'ctype'.
3099 		 */
3100 		if ((original = sshbuf_from(cp, have)) == NULL ||
3101 		    (modified = sshbuf_new()) == NULL) {
3102 			error_f("alloc");
3103 			goto out;
3104 		}
3105 		if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
3106 		    (r = sshbuf_get_u32(original, &id)) != 0) {
3107 			error_fr(r, "parse");
3108 			goto out;
3109 		}
3110 		c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3111 		    -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
3112 		c->mux_ctx = downstream;	/* point to mux client */
3113 		c->mux_downstream_id = id;
3114 		c->remote_id = remote_id;
3115 		c->have_remote_id = 1;
3116 		if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
3117 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3118 		    (r = sshbuf_putb(modified, original)) != 0) {
3119 			error_fr(r, "compose");
3120 			channel_free(ssh, c);
3121 			goto out;
3122 		}
3123 		break;
3124 	case SSH2_MSG_GLOBAL_REQUEST:
3125 		if ((original = sshbuf_from(cp, have)) == NULL) {
3126 			error_f("alloc");
3127 			goto out;
3128 		}
3129 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
3130 			error_fr(r, "parse");
3131 			goto out;
3132 		}
3133 		if (strcmp(ctype, "tcpip-forward") != 0) {
3134 			error_f("unsupported request %s", ctype);
3135 			goto out;
3136 		}
3137 		if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
3138 		    (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
3139 		    (r = sshbuf_get_u32(original, &listen_port)) != 0) {
3140 			error_fr(r, "parse");
3141 			goto out;
3142 		}
3143 		if (listen_port > 65535) {
3144 			error_f("tcpip-forward for %s: bad port %u",
3145 			    listen_host, listen_port);
3146 			goto out;
3147 		}
3148 		/* Record that connection to this host/port is permitted. */
3149 		permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
3150 		    listen_host, NULL, (int)listen_port, downstream);
3151 		listen_host = NULL;
3152 		break;
3153 	case SSH2_MSG_CHANNEL_CLOSE:
3154 		if (have < 4)
3155 			break;
3156 		remote_id = PEEK_U32(cp);
3157 		if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
3158 			if (c->flags & CHAN_CLOSE_RCVD)
3159 				channel_free(ssh, c);
3160 			else
3161 				c->flags |= CHAN_CLOSE_SENT;
3162 		}
3163 		break;
3164 	}
3165 	if (modified) {
3166 		if ((r = sshpkt_start(ssh, type)) != 0 ||
3167 		    (r = sshpkt_putb(ssh, modified)) != 0 ||
3168 		    (r = sshpkt_send(ssh)) != 0) {
3169 			error_fr(r, "send");
3170 			goto out;
3171 		}
3172 	} else {
3173 		if ((r = sshpkt_start(ssh, type)) != 0 ||
3174 		    (r = sshpkt_put(ssh, cp, have)) != 0 ||
3175 		    (r = sshpkt_send(ssh)) != 0) {
3176 			error_fr(r, "send");
3177 			goto out;
3178 		}
3179 	}
3180 	ret = 0;
3181  out:
3182 	free(ctype);
3183 	free(listen_host);
3184 	sshbuf_free(original);
3185 	sshbuf_free(modified);
3186 	return ret;
3187 }
3188 
3189 /*
3190  * receive packets from upstream server and de-multiplex packets
3191  * to correct downstream:
3192  * implemented as a helper for channel input handlers,
3193  * replaces local (proxy) channel ID with downstream channel ID.
3194  */
3195 int
3196 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
3197 {
3198 	struct sshbuf *b = NULL;
3199 	Channel *downstream;
3200 	const u_char *cp = NULL;
3201 	size_t len;
3202 	int r;
3203 
3204 	/*
3205 	 * When receiving packets from the peer we need to check whether we
3206 	 * need to forward the packets to the mux client. In this case we
3207 	 * restore the original channel id and keep track of CLOSE messages,
3208 	 * so we can cleanup the channel.
3209 	 */
3210 	if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
3211 		return 0;
3212 	if ((downstream = c->mux_ctx) == NULL)
3213 		return 0;
3214 	switch (type) {
3215 	case SSH2_MSG_CHANNEL_CLOSE:
3216 	case SSH2_MSG_CHANNEL_DATA:
3217 	case SSH2_MSG_CHANNEL_EOF:
3218 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
3219 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3220 	case SSH2_MSG_CHANNEL_OPEN_FAILURE:
3221 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
3222 	case SSH2_MSG_CHANNEL_SUCCESS:
3223 	case SSH2_MSG_CHANNEL_FAILURE:
3224 	case SSH2_MSG_CHANNEL_REQUEST:
3225 		break;
3226 	default:
3227 		debug2_f("channel %u: unsupported type %u", c->self, type);
3228 		return 0;
3229 	}
3230 	if ((b = sshbuf_new()) == NULL) {
3231 		error_f("alloc reply");
3232 		goto out;
3233 	}
3234 	/* get remaining payload (after id) */
3235 	cp = sshpkt_ptr(ssh, &len);
3236 	if (cp == NULL) {
3237 		error_f("no packet");
3238 		goto out;
3239 	}
3240 	/* translate id and send to muxclient */
3241 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* padlen */
3242 	    (r = sshbuf_put_u8(b, type)) != 0 ||
3243 	    (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
3244 	    (r = sshbuf_put(b, cp, len)) != 0 ||
3245 	    (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
3246 		error_fr(r, "compose muxclient");
3247 		goto out;
3248 	}
3249 	/* sshbuf_dump(b, stderr); */
3250 	if (ssh_packet_log_type(type))
3251 		debug3_f("channel %u: up->down: type %u", c->self, type);
3252  out:
3253 	/* update state */
3254 	switch (type) {
3255 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3256 		/* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
3257 		if (cp && len > 4) {
3258 			c->remote_id = PEEK_U32(cp);
3259 			c->have_remote_id = 1;
3260 		}
3261 		break;
3262 	case SSH2_MSG_CHANNEL_CLOSE:
3263 		if (c->flags & CHAN_CLOSE_SENT)
3264 			channel_free(ssh, c);
3265 		else
3266 			c->flags |= CHAN_CLOSE_RCVD;
3267 		break;
3268 	}
3269 	sshbuf_free(b);
3270 	return 1;
3271 }
3272 
3273 /* -- protocol input */
3274 
3275 /* Parse a channel ID from the current packet */
3276 static int
3277 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
3278 {
3279 	u_int32_t id;
3280 	int r;
3281 
3282 	if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
3283 		error_r(r, "%s: parse id", where);
3284 		ssh_packet_disconnect(ssh, "Invalid %s message", what);
3285 	}
3286 	if (id > INT_MAX) {
3287 		error_r(r, "%s: bad channel id %u", where, id);
3288 		ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
3289 	}
3290 	return (int)id;
3291 }
3292 
3293 /* Lookup a channel from an ID in the current packet */
3294 static Channel *
3295 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
3296 {
3297 	int id = channel_parse_id(ssh, where, what);
3298 	Channel *c;
3299 
3300 	if ((c = channel_lookup(ssh, id)) == NULL) {
3301 		ssh_packet_disconnect(ssh,
3302 		    "%s packet referred to nonexistent channel %d", what, id);
3303 	}
3304 	return c;
3305 }
3306 
3307 int
3308 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
3309 {
3310 	const u_char *data;
3311 	size_t data_len, win_len;
3312 	Channel *c = channel_from_packet_id(ssh, __func__, "data");
3313 	int r;
3314 
3315 	if (channel_proxy_upstream(c, type, seq, ssh))
3316 		return 0;
3317 
3318 	/* Ignore any data for non-open channels (might happen on close) */
3319 	if (c->type != SSH_CHANNEL_OPEN &&
3320 	    c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
3321 	    c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
3322 	    c->type != SSH_CHANNEL_X11_OPEN)
3323 		return 0;
3324 
3325 	/* Get the data. */
3326 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3327             (r = sshpkt_get_end(ssh)) != 0)
3328 		fatal_fr(r, "channel %i: get data", c->self);
3329 
3330 	win_len = data_len;
3331 	if (c->datagram)
3332 		win_len += 4;  /* string length header */
3333 
3334 	/*
3335 	 * The sending side reduces its window as it sends data, so we
3336 	 * must 'fake' consumption of the data in order to ensure that window
3337 	 * updates are sent back. Otherwise the connection might deadlock.
3338 	 */
3339 	if (c->ostate != CHAN_OUTPUT_OPEN) {
3340 		c->local_window -= win_len;
3341 		c->local_consumed += win_len;
3342 		return 0;
3343 	}
3344 
3345 	if (win_len > c->local_maxpacket) {
3346 		logit("channel %d: rcvd big packet %zu, maxpack %u",
3347 		    c->self, win_len, c->local_maxpacket);
3348 		return 0;
3349 	}
3350 	if (win_len > c->local_window) {
3351 		logit("channel %d: rcvd too much data %zu, win %u",
3352 		    c->self, win_len, c->local_window);
3353 		return 0;
3354 	}
3355 	c->local_window -= win_len;
3356 
3357 	if (c->datagram) {
3358 		if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3359 			fatal_fr(r, "channel %i: append datagram", c->self);
3360 	} else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3361 		fatal_fr(r, "channel %i: append data", c->self);
3362 
3363 	return 0;
3364 }
3365 
3366 int
3367 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3368 {
3369 	const u_char *data;
3370 	size_t data_len;
3371 	u_int32_t tcode;
3372 	Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3373 	int r;
3374 
3375 	if (channel_proxy_upstream(c, type, seq, ssh))
3376 		return 0;
3377 	if (c->type != SSH_CHANNEL_OPEN) {
3378 		logit("channel %d: ext data for non open", c->self);
3379 		return 0;
3380 	}
3381 	if (c->flags & CHAN_EOF_RCVD) {
3382 		if (ssh->compat & SSH_BUG_EXTEOF)
3383 			debug("channel %d: accepting ext data after eof",
3384 			    c->self);
3385 		else
3386 			ssh_packet_disconnect(ssh, "Received extended_data "
3387 			    "after EOF on channel %d.", c->self);
3388 	}
3389 
3390 	if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3391 		error_fr(r, "parse tcode");
3392 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
3393 	}
3394 	if (c->efd == -1 ||
3395 	    c->extended_usage != CHAN_EXTENDED_WRITE ||
3396 	    tcode != SSH2_EXTENDED_DATA_STDERR) {
3397 		logit("channel %d: bad ext data", c->self);
3398 		return 0;
3399 	}
3400 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3401             (r = sshpkt_get_end(ssh)) != 0) {
3402 		error_fr(r, "parse data");
3403 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
3404 	}
3405 
3406 	if (data_len > c->local_window) {
3407 		logit("channel %d: rcvd too much extended_data %zu, win %u",
3408 		    c->self, data_len, c->local_window);
3409 		return 0;
3410 	}
3411 	debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3412 	/* XXX sshpkt_getb? */
3413 	if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3414 		error_fr(r, "append");
3415 	c->local_window -= data_len;
3416 	return 0;
3417 }
3418 
3419 int
3420 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3421 {
3422 	Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3423 	int r;
3424 
3425         if ((r = sshpkt_get_end(ssh)) != 0) {
3426 		error_fr(r, "parse data");
3427 		ssh_packet_disconnect(ssh, "Invalid ieof message");
3428 	}
3429 
3430 	if (channel_proxy_upstream(c, type, seq, ssh))
3431 		return 0;
3432 	chan_rcvd_ieof(ssh, c);
3433 
3434 	/* XXX force input close */
3435 	if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3436 		debug("channel %d: FORCE input drain", c->self);
3437 		c->istate = CHAN_INPUT_WAIT_DRAIN;
3438 		if (sshbuf_len(c->input) == 0)
3439 			chan_ibuf_empty(ssh, c);
3440 	}
3441 	return 0;
3442 }
3443 
3444 int
3445 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3446 {
3447 	Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3448 	int r;
3449 
3450 	if (channel_proxy_upstream(c, type, seq, ssh))
3451 		return 0;
3452         if ((r = sshpkt_get_end(ssh)) != 0) {
3453 		error_fr(r, "parse data");
3454 		ssh_packet_disconnect(ssh, "Invalid oclose message");
3455 	}
3456 	chan_rcvd_oclose(ssh, c);
3457 	return 0;
3458 }
3459 
3460 int
3461 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3462 {
3463 	Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3464 	u_int32_t remote_window, remote_maxpacket;
3465 	int r;
3466 
3467 	if (channel_proxy_upstream(c, type, seq, ssh))
3468 		return 0;
3469 	if (c->type != SSH_CHANNEL_OPENING)
3470 		ssh_packet_disconnect(ssh, "Received open confirmation for "
3471 		    "non-opening channel %d.", c->self);
3472 	/*
3473 	 * Record the remote channel number and mark that the channel
3474 	 * is now open.
3475 	 */
3476 	if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3477 	    (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3478 	    (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3479             (r = sshpkt_get_end(ssh)) != 0) {
3480 		error_fr(r, "window/maxpacket");
3481 		ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3482 	}
3483 
3484 	c->have_remote_id = 1;
3485 	c->remote_window = remote_window;
3486 	c->remote_maxpacket = remote_maxpacket;
3487 	c->type = SSH_CHANNEL_OPEN;
3488 	if (c->open_confirm) {
3489 		debug2_f("channel %d: callback start", c->self);
3490 		c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3491 		debug2_f("channel %d: callback done", c->self);
3492 	}
3493 	c->lastused = monotime();
3494 	debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3495 	    c->remote_window, c->remote_maxpacket);
3496 	return 0;
3497 }
3498 
3499 static char *
3500 reason2txt(int reason)
3501 {
3502 	switch (reason) {
3503 	case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3504 		return "administratively prohibited";
3505 	case SSH2_OPEN_CONNECT_FAILED:
3506 		return "connect failed";
3507 	case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3508 		return "unknown channel type";
3509 	case SSH2_OPEN_RESOURCE_SHORTAGE:
3510 		return "resource shortage";
3511 	}
3512 	return "unknown reason";
3513 }
3514 
3515 int
3516 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3517 {
3518 	Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3519 	u_int32_t reason;
3520 	char *msg = NULL;
3521 	int r;
3522 
3523 	if (channel_proxy_upstream(c, type, seq, ssh))
3524 		return 0;
3525 	if (c->type != SSH_CHANNEL_OPENING)
3526 		ssh_packet_disconnect(ssh, "Received open failure for "
3527 		    "non-opening channel %d.", c->self);
3528 	if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3529 		error_fr(r, "parse reason");
3530 		ssh_packet_disconnect(ssh, "Invalid open failure message");
3531 	}
3532 	/* skip language */
3533 	if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3534 	    (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3535             (r = sshpkt_get_end(ssh)) != 0) {
3536 		error_fr(r, "parse msg/lang");
3537 		ssh_packet_disconnect(ssh, "Invalid open failure message");
3538 	}
3539 	logit("channel %d: open failed: %s%s%s", c->self,
3540 	    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3541 	free(msg);
3542 	if (c->open_confirm) {
3543 		debug2_f("channel %d: callback start", c->self);
3544 		c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3545 		debug2_f("channel %d: callback done", c->self);
3546 	}
3547 	/* Schedule the channel for cleanup/deletion. */
3548 	chan_mark_dead(ssh, c);
3549 	return 0;
3550 }
3551 
3552 int
3553 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3554 {
3555 	int id = channel_parse_id(ssh, __func__, "window adjust");
3556 	Channel *c;
3557 	u_int32_t adjust;
3558 	u_int new_rwin;
3559 	int r;
3560 
3561 	if ((c = channel_lookup(ssh, id)) == NULL) {
3562 		logit("Received window adjust for non-open channel %d.", id);
3563 		return 0;
3564 	}
3565 
3566 	if (channel_proxy_upstream(c, type, seq, ssh))
3567 		return 0;
3568 	if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3569             (r = sshpkt_get_end(ssh)) != 0) {
3570 		error_fr(r, "parse adjust");
3571 		ssh_packet_disconnect(ssh, "Invalid window adjust message");
3572 	}
3573 	debug2("channel %d: rcvd adjust %u", c->self, adjust);
3574 	if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3575 		fatal("channel %d: adjust %u overflows remote window %u",
3576 		    c->self, adjust, c->remote_window);
3577 	}
3578 	c->remote_window = new_rwin;
3579 	return 0;
3580 }
3581 
3582 int
3583 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3584 {
3585 	int id = channel_parse_id(ssh, __func__, "status confirm");
3586 	Channel *c;
3587 	struct channel_confirm *cc;
3588 
3589 	/* Reset keepalive timeout */
3590 	ssh_packet_set_alive_timeouts(ssh, 0);
3591 
3592 	debug2_f("type %d id %d", type, id);
3593 
3594 	if ((c = channel_lookup(ssh, id)) == NULL) {
3595 		logit_f("%d: unknown", id);
3596 		return 0;
3597 	}
3598 	if (channel_proxy_upstream(c, type, seq, ssh))
3599 		return 0;
3600         if (sshpkt_get_end(ssh) != 0)
3601 		ssh_packet_disconnect(ssh, "Invalid status confirm message");
3602 	if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3603 		return 0;
3604 	cc->cb(ssh, type, c, cc->ctx);
3605 	TAILQ_REMOVE(&c->status_confirms, cc, entry);
3606 	freezero(cc, sizeof(*cc));
3607 	return 0;
3608 }
3609 
3610 /* -- tcp forwarding */
3611 
3612 void
3613 channel_set_af(struct ssh *ssh, int af)
3614 {
3615 	ssh->chanctxt->IPv4or6 = af;
3616 }
3617 
3618 
3619 /*
3620  * Determine whether or not a port forward listens to loopback, the
3621  * specified address or wildcard. On the client, a specified bind
3622  * address will always override gateway_ports. On the server, a
3623  * gateway_ports of 1 (``yes'') will override the client's specification
3624  * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3625  * will bind to whatever address the client asked for.
3626  *
3627  * Special-case listen_addrs are:
3628  *
3629  * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3630  * "" (empty string), "*"  -> wildcard v4/v6
3631  * "localhost"             -> loopback v4/v6
3632  * "127.0.0.1" / "::1"     -> accepted even if gateway_ports isn't set
3633  */
3634 static const char *
3635 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3636     int is_client, struct ForwardOptions *fwd_opts)
3637 {
3638 	const char *addr = NULL;
3639 	int wildcard = 0;
3640 
3641 	if (listen_addr == NULL) {
3642 		/* No address specified: default to gateway_ports setting */
3643 		if (fwd_opts->gateway_ports)
3644 			wildcard = 1;
3645 	} else if (fwd_opts->gateway_ports || is_client) {
3646 		if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3647 		    strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3648 		    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3649 		    (!is_client && fwd_opts->gateway_ports == 1)) {
3650 			wildcard = 1;
3651 			/*
3652 			 * Notify client if they requested a specific listen
3653 			 * address and it was overridden.
3654 			 */
3655 			if (*listen_addr != '\0' &&
3656 			    strcmp(listen_addr, "0.0.0.0") != 0 &&
3657 			    strcmp(listen_addr, "*") != 0) {
3658 				ssh_packet_send_debug(ssh,
3659 				    "Forwarding listen address "
3660 				    "\"%s\" overridden by server "
3661 				    "GatewayPorts", listen_addr);
3662 			}
3663 		} else if (strcmp(listen_addr, "localhost") != 0 ||
3664 		    strcmp(listen_addr, "127.0.0.1") == 0 ||
3665 		    strcmp(listen_addr, "::1") == 0) {
3666 			/*
3667 			 * Accept explicit localhost address when
3668 			 * GatewayPorts=yes. The "localhost" hostname is
3669 			 * deliberately skipped here so it will listen on all
3670 			 * available local address families.
3671 			 */
3672 			addr = listen_addr;
3673 		}
3674 	} else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3675 	    strcmp(listen_addr, "::1") == 0) {
3676 		/*
3677 		 * If a specific IPv4/IPv6 localhost address has been
3678 		 * requested then accept it even if gateway_ports is in
3679 		 * effect. This allows the client to prefer IPv4 or IPv6.
3680 		 */
3681 		addr = listen_addr;
3682 	}
3683 	if (wildcardp != NULL)
3684 		*wildcardp = wildcard;
3685 	return addr;
3686 }
3687 
3688 static int
3689 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3690     struct Forward *fwd, int *allocated_listen_port,
3691     struct ForwardOptions *fwd_opts)
3692 {
3693 	Channel *c;
3694 	int sock, r, success = 0, wildcard = 0, is_client;
3695 	struct addrinfo hints, *ai, *aitop;
3696 	const char *host, *addr;
3697 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3698 	in_port_t *lport_p;
3699 
3700 	is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3701 
3702 	if (is_client && fwd->connect_path != NULL) {
3703 		host = fwd->connect_path;
3704 	} else {
3705 		host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3706 		    fwd->listen_host : fwd->connect_host;
3707 		if (host == NULL) {
3708 			error("No forward host name.");
3709 			return 0;
3710 		}
3711 		if (strlen(host) >= NI_MAXHOST) {
3712 			error("Forward host name too long.");
3713 			return 0;
3714 		}
3715 	}
3716 
3717 	/* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3718 	addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3719 	    is_client, fwd_opts);
3720 	debug3_f("type %d wildcard %d addr %s", type, wildcard,
3721 	    (addr == NULL) ? "NULL" : addr);
3722 
3723 	/*
3724 	 * getaddrinfo returns a loopback address if the hostname is
3725 	 * set to NULL and hints.ai_flags is not AI_PASSIVE
3726 	 */
3727 	memset(&hints, 0, sizeof(hints));
3728 	hints.ai_family = ssh->chanctxt->IPv4or6;
3729 	hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3730 	hints.ai_socktype = SOCK_STREAM;
3731 	snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3732 	if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3733 		if (addr == NULL) {
3734 			/* This really shouldn't happen */
3735 			ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3736 			    ssh_gai_strerror(r));
3737 		} else {
3738 			error_f("getaddrinfo(%.64s): %s", addr,
3739 			    ssh_gai_strerror(r));
3740 		}
3741 		return 0;
3742 	}
3743 	if (allocated_listen_port != NULL)
3744 		*allocated_listen_port = 0;
3745 	for (ai = aitop; ai; ai = ai->ai_next) {
3746 		switch (ai->ai_family) {
3747 		case AF_INET:
3748 			lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3749 			    sin_port;
3750 			break;
3751 		case AF_INET6:
3752 			lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3753 			    sin6_port;
3754 			break;
3755 		default:
3756 			continue;
3757 		}
3758 		/*
3759 		 * If allocating a port for -R forwards, then use the
3760 		 * same port for all address families.
3761 		 */
3762 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
3763 		    fwd->listen_port == 0 && allocated_listen_port != NULL &&
3764 		    *allocated_listen_port > 0)
3765 			*lport_p = htons(*allocated_listen_port);
3766 
3767 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3768 		    strport, sizeof(strport),
3769 		    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3770 			error_f("getnameinfo failed");
3771 			continue;
3772 		}
3773 		/* Create a port to listen for the host. */
3774 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3775 		if (sock == -1) {
3776 			/* this is no error since kernel may not support ipv6 */
3777 			verbose("socket [%s]:%s: %.100s", ntop, strport,
3778 			    strerror(errno));
3779 			continue;
3780 		}
3781 
3782 		set_reuseaddr(sock);
3783 
3784 		debug("Local forwarding listening on %s port %s.",
3785 		    ntop, strport);
3786 
3787 		/* Bind the socket to the address. */
3788 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3789 			/*
3790 			 * address can be in if use ipv6 address is
3791 			 * already bound
3792 			 */
3793 			verbose("bind [%s]:%s: %.100s",
3794 			    ntop, strport, strerror(errno));
3795 			close(sock);
3796 			continue;
3797 		}
3798 		/* Start listening for connections on the socket. */
3799 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3800 			error("listen [%s]:%s: %.100s", ntop, strport,
3801 			    strerror(errno));
3802 			close(sock);
3803 			continue;
3804 		}
3805 
3806 		/*
3807 		 * fwd->listen_port == 0 requests a dynamically allocated port -
3808 		 * record what we got.
3809 		 */
3810 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
3811 		    fwd->listen_port == 0 &&
3812 		    allocated_listen_port != NULL &&
3813 		    *allocated_listen_port == 0) {
3814 			*allocated_listen_port = get_local_port(sock);
3815 			debug("Allocated listen port %d",
3816 			    *allocated_listen_port);
3817 		}
3818 
3819 		/* Allocate a channel number for the socket. */
3820 		c = channel_new(ssh, "port-listener", type, sock, sock, -1,
3821 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3822 		    0, "port listener", 1);
3823 		c->path = xstrdup(host);
3824 		c->host_port = fwd->connect_port;
3825 		c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3826 		if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3827 		    !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3828 			c->listening_port = *allocated_listen_port;
3829 		else
3830 			c->listening_port = fwd->listen_port;
3831 		success = 1;
3832 	}
3833 	if (success == 0)
3834 		error_f("cannot listen to port: %d", fwd->listen_port);
3835 	freeaddrinfo(aitop);
3836 	return success;
3837 }
3838 
3839 static int
3840 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3841     struct Forward *fwd, struct ForwardOptions *fwd_opts)
3842 {
3843 	struct sockaddr_un sunaddr;
3844 	const char *path;
3845 	Channel *c;
3846 	int port, sock;
3847 	mode_t omask;
3848 
3849 	switch (type) {
3850 	case SSH_CHANNEL_UNIX_LISTENER:
3851 		if (fwd->connect_path != NULL) {
3852 			if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3853 				error("Local connecting path too long: %s",
3854 				    fwd->connect_path);
3855 				return 0;
3856 			}
3857 			path = fwd->connect_path;
3858 			port = PORT_STREAMLOCAL;
3859 		} else {
3860 			if (fwd->connect_host == NULL) {
3861 				error("No forward host name.");
3862 				return 0;
3863 			}
3864 			if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3865 				error("Forward host name too long.");
3866 				return 0;
3867 			}
3868 			path = fwd->connect_host;
3869 			port = fwd->connect_port;
3870 		}
3871 		break;
3872 	case SSH_CHANNEL_RUNIX_LISTENER:
3873 		path = fwd->listen_path;
3874 		port = PORT_STREAMLOCAL;
3875 		break;
3876 	default:
3877 		error_f("unexpected channel type %d", type);
3878 		return 0;
3879 	}
3880 
3881 	if (fwd->listen_path == NULL) {
3882 		error("No forward path name.");
3883 		return 0;
3884 	}
3885 	if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3886 		error("Local listening path too long: %s", fwd->listen_path);
3887 		return 0;
3888 	}
3889 
3890 	debug3_f("type %d path %s", type, fwd->listen_path);
3891 
3892 	/* Start a Unix domain listener. */
3893 	omask = umask(fwd_opts->streamlocal_bind_mask);
3894 	sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3895 	    fwd_opts->streamlocal_bind_unlink);
3896 	umask(omask);
3897 	if (sock < 0)
3898 		return 0;
3899 
3900 	debug("Local forwarding listening on path %s.", fwd->listen_path);
3901 
3902 	/* Allocate a channel number for the socket. */
3903 	c = channel_new(ssh, "unix-listener", type, sock, sock, -1,
3904 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3905 	    0, "unix listener", 1);
3906 	c->path = xstrdup(path);
3907 	c->host_port = port;
3908 	c->listening_port = PORT_STREAMLOCAL;
3909 	c->listening_addr = xstrdup(fwd->listen_path);
3910 	return 1;
3911 }
3912 
3913 static int
3914 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3915     const char *host, u_short port)
3916 {
3917 	u_int i;
3918 	int found = 0;
3919 
3920 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3921 		Channel *c = ssh->chanctxt->channels[i];
3922 		if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3923 			continue;
3924 		if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3925 			debug2_f("close channel %d", i);
3926 			channel_free(ssh, c);
3927 			found = 1;
3928 		}
3929 	}
3930 
3931 	return found;
3932 }
3933 
3934 static int
3935 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3936 {
3937 	u_int i;
3938 	int found = 0;
3939 
3940 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3941 		Channel *c = ssh->chanctxt->channels[i];
3942 		if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3943 			continue;
3944 		if (c->path == NULL)
3945 			continue;
3946 		if (strcmp(c->path, path) == 0) {
3947 			debug2_f("close channel %d", i);
3948 			channel_free(ssh, c);
3949 			found = 1;
3950 		}
3951 	}
3952 
3953 	return found;
3954 }
3955 
3956 int
3957 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3958 {
3959 	if (fwd->listen_path != NULL) {
3960 		return channel_cancel_rport_listener_streamlocal(ssh,
3961 		    fwd->listen_path);
3962 	} else {
3963 		return channel_cancel_rport_listener_tcpip(ssh,
3964 		    fwd->listen_host, fwd->listen_port);
3965 	}
3966 }
3967 
3968 static int
3969 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
3970     const char *lhost, u_short lport, int cport,
3971     struct ForwardOptions *fwd_opts)
3972 {
3973 	u_int i;
3974 	int found = 0;
3975 	const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
3976 
3977 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3978 		Channel *c = ssh->chanctxt->channels[i];
3979 		if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
3980 			continue;
3981 		if (c->listening_port != lport)
3982 			continue;
3983 		if (cport == CHANNEL_CANCEL_PORT_STATIC) {
3984 			/* skip dynamic forwardings */
3985 			if (c->host_port == 0)
3986 				continue;
3987 		} else {
3988 			if (c->host_port != cport)
3989 				continue;
3990 		}
3991 		if ((c->listening_addr == NULL && addr != NULL) ||
3992 		    (c->listening_addr != NULL && addr == NULL))
3993 			continue;
3994 		if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
3995 			debug2_f("close channel %d", i);
3996 			channel_free(ssh, c);
3997 			found = 1;
3998 		}
3999 	}
4000 
4001 	return found;
4002 }
4003 
4004 static int
4005 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
4006 {
4007 	u_int i;
4008 	int found = 0;
4009 
4010 	if (path == NULL) {
4011 		error_f("no path specified.");
4012 		return 0;
4013 	}
4014 
4015 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4016 		Channel *c = ssh->chanctxt->channels[i];
4017 		if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
4018 			continue;
4019 		if (c->listening_addr == NULL)
4020 			continue;
4021 		if (strcmp(c->listening_addr, path) == 0) {
4022 			debug2_f("close channel %d", i);
4023 			channel_free(ssh, c);
4024 			found = 1;
4025 		}
4026 	}
4027 
4028 	return found;
4029 }
4030 
4031 int
4032 channel_cancel_lport_listener(struct ssh *ssh,
4033     struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
4034 {
4035 	if (fwd->listen_path != NULL) {
4036 		return channel_cancel_lport_listener_streamlocal(ssh,
4037 		    fwd->listen_path);
4038 	} else {
4039 		return channel_cancel_lport_listener_tcpip(ssh,
4040 		    fwd->listen_host, fwd->listen_port, cport, fwd_opts);
4041 	}
4042 }
4043 
4044 /* protocol local port fwd, used by ssh */
4045 int
4046 channel_setup_local_fwd_listener(struct ssh *ssh,
4047     struct Forward *fwd, struct ForwardOptions *fwd_opts)
4048 {
4049 	if (fwd->listen_path != NULL) {
4050 		return channel_setup_fwd_listener_streamlocal(ssh,
4051 		    SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
4052 	} else {
4053 		return channel_setup_fwd_listener_tcpip(ssh,
4054 		    SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
4055 	}
4056 }
4057 
4058 /* Matches a remote forwarding permission against a requested forwarding */
4059 static int
4060 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
4061 {
4062 	int ret;
4063 	char *lhost;
4064 
4065 	/* XXX add ACLs for streamlocal */
4066 	if (fwd->listen_path != NULL)
4067 		return 1;
4068 
4069 	if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
4070 		return 0;
4071 
4072 	if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
4073 	    allowed_open->listen_port != fwd->listen_port)
4074 		return 0;
4075 
4076 	/* Match hostnames case-insensitively */
4077 	lhost = xstrdup(fwd->listen_host);
4078 	lowercase(lhost);
4079 	ret = match_pattern(lhost, allowed_open->listen_host);
4080 	free(lhost);
4081 
4082 	return ret;
4083 }
4084 
4085 /* Checks whether a requested remote forwarding is permitted */
4086 static int
4087 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
4088 {
4089 	struct ssh_channels *sc = ssh->chanctxt;
4090 	struct permission_set *pset = &sc->remote_perms;
4091 	u_int i, permit, permit_adm = 1;
4092 	struct permission *perm;
4093 
4094 	/* XXX apply GatewayPorts override before checking? */
4095 
4096 	permit = pset->all_permitted;
4097 	if (!permit) {
4098 		for (i = 0; i < pset->num_permitted_user; i++) {
4099 			perm = &pset->permitted_user[i];
4100 			if (remote_open_match(perm, fwd)) {
4101 				permit = 1;
4102 				break;
4103 			}
4104 		}
4105 	}
4106 
4107 	if (pset->num_permitted_admin > 0) {
4108 		permit_adm = 0;
4109 		for (i = 0; i < pset->num_permitted_admin; i++) {
4110 			perm = &pset->permitted_admin[i];
4111 			if (remote_open_match(perm, fwd)) {
4112 				permit_adm = 1;
4113 				break;
4114 			}
4115 		}
4116 	}
4117 
4118 	return permit && permit_adm;
4119 }
4120 
4121 /* protocol v2 remote port fwd, used by sshd */
4122 int
4123 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
4124     int *allocated_listen_port, struct ForwardOptions *fwd_opts)
4125 {
4126 	if (!check_rfwd_permission(ssh, fwd)) {
4127 		ssh_packet_send_debug(ssh, "port forwarding refused");
4128 		if (fwd->listen_path != NULL)
4129 			/* XXX always allowed, see remote_open_match() */
4130 			logit("Received request from %.100s port %d to "
4131 			    "remote forward to path \"%.100s\", "
4132 			    "but the request was denied.",
4133 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4134 			    fwd->listen_path);
4135 		else if(fwd->listen_host != NULL)
4136 			logit("Received request from %.100s port %d to "
4137 			    "remote forward to host %.100s port %d, "
4138 			    "but the request was denied.",
4139 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4140 			    fwd->listen_host, fwd->listen_port );
4141 		else
4142 			logit("Received request from %.100s port %d to remote "
4143 			    "forward, but the request was denied.",
4144 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
4145 		return 0;
4146 	}
4147 	if (fwd->listen_path != NULL) {
4148 		return channel_setup_fwd_listener_streamlocal(ssh,
4149 		    SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
4150 	} else {
4151 		return channel_setup_fwd_listener_tcpip(ssh,
4152 		    SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
4153 		    fwd_opts);
4154 	}
4155 }
4156 
4157 /*
4158  * Translate the requested rfwd listen host to something usable for
4159  * this server.
4160  */
4161 static const char *
4162 channel_rfwd_bind_host(const char *listen_host)
4163 {
4164 	if (listen_host == NULL) {
4165 		return "localhost";
4166 	} else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
4167 		return "";
4168 	} else
4169 		return listen_host;
4170 }
4171 
4172 /*
4173  * Initiate forwarding of connections to port "port" on remote host through
4174  * the secure channel to host:port from local side.
4175  * Returns handle (index) for updating the dynamic listen port with
4176  * channel_update_permission().
4177  */
4178 int
4179 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
4180 {
4181 	int r, success = 0, idx = -1;
4182 	const char *host_to_connect, *listen_host, *listen_path;
4183 	int port_to_connect, listen_port;
4184 
4185 	/* Send the forward request to the remote side. */
4186 	if (fwd->listen_path != NULL) {
4187 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4188 		    (r = sshpkt_put_cstring(ssh,
4189 		    "streamlocal-forward@openssh.com")) != 0 ||
4190 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4191 		    (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
4192 		    (r = sshpkt_send(ssh)) != 0 ||
4193 		    (r = ssh_packet_write_wait(ssh)) != 0)
4194 			fatal_fr(r, "request streamlocal");
4195 	} else {
4196 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4197 		    (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
4198 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4199 		    (r = sshpkt_put_cstring(ssh,
4200 		    channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
4201 		    (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
4202 		    (r = sshpkt_send(ssh)) != 0 ||
4203 		    (r = ssh_packet_write_wait(ssh)) != 0)
4204 			fatal_fr(r, "request tcpip-forward");
4205 	}
4206 	/* Assume that server accepts the request */
4207 	success = 1;
4208 	if (success) {
4209 		/* Record that connection to this host/port is permitted. */
4210 		host_to_connect = listen_host = listen_path = NULL;
4211 		port_to_connect = listen_port = 0;
4212 		if (fwd->connect_path != NULL) {
4213 			host_to_connect = fwd->connect_path;
4214 			port_to_connect = PORT_STREAMLOCAL;
4215 		} else {
4216 			host_to_connect = fwd->connect_host;
4217 			port_to_connect = fwd->connect_port;
4218 		}
4219 		if (fwd->listen_path != NULL) {
4220 			listen_path = fwd->listen_path;
4221 			listen_port = PORT_STREAMLOCAL;
4222 		} else {
4223 			listen_host = fwd->listen_host;
4224 			listen_port = fwd->listen_port;
4225 		}
4226 		idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
4227 		    host_to_connect, port_to_connect,
4228 		    listen_host, listen_path, listen_port, NULL);
4229 	}
4230 	return idx;
4231 }
4232 
4233 static int
4234 open_match(struct permission *allowed_open, const char *requestedhost,
4235     int requestedport)
4236 {
4237 	if (allowed_open->host_to_connect == NULL)
4238 		return 0;
4239 	if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
4240 	    allowed_open->port_to_connect != requestedport)
4241 		return 0;
4242 	if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
4243 	    strcmp(allowed_open->host_to_connect, requestedhost) != 0)
4244 		return 0;
4245 	return 1;
4246 }
4247 
4248 /*
4249  * Note that in the listen host/port case
4250  * we don't support FWD_PERMIT_ANY_PORT and
4251  * need to translate between the configured-host (listen_host)
4252  * and what we've sent to the remote server (channel_rfwd_bind_host)
4253  */
4254 static int
4255 open_listen_match_tcpip(struct permission *allowed_open,
4256     const char *requestedhost, u_short requestedport, int translate)
4257 {
4258 	const char *allowed_host;
4259 
4260 	if (allowed_open->host_to_connect == NULL)
4261 		return 0;
4262 	if (allowed_open->listen_port != requestedport)
4263 		return 0;
4264 	if (!translate && allowed_open->listen_host == NULL &&
4265 	    requestedhost == NULL)
4266 		return 1;
4267 	allowed_host = translate ?
4268 	    channel_rfwd_bind_host(allowed_open->listen_host) :
4269 	    allowed_open->listen_host;
4270 	if (allowed_host == NULL || requestedhost == NULL ||
4271 	    strcmp(allowed_host, requestedhost) != 0)
4272 		return 0;
4273 	return 1;
4274 }
4275 
4276 static int
4277 open_listen_match_streamlocal(struct permission *allowed_open,
4278     const char *requestedpath)
4279 {
4280 	if (allowed_open->host_to_connect == NULL)
4281 		return 0;
4282 	if (allowed_open->listen_port != PORT_STREAMLOCAL)
4283 		return 0;
4284 	if (allowed_open->listen_path == NULL ||
4285 	    strcmp(allowed_open->listen_path, requestedpath) != 0)
4286 		return 0;
4287 	return 1;
4288 }
4289 
4290 /*
4291  * Request cancellation of remote forwarding of connection host:port from
4292  * local side.
4293  */
4294 static int
4295 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
4296     const char *host, u_short port)
4297 {
4298 	struct ssh_channels *sc = ssh->chanctxt;
4299 	struct permission_set *pset = &sc->local_perms;
4300 	int r;
4301 	u_int i;
4302 	struct permission *perm = NULL;
4303 
4304 	for (i = 0; i < pset->num_permitted_user; i++) {
4305 		perm = &pset->permitted_user[i];
4306 		if (open_listen_match_tcpip(perm, host, port, 0))
4307 			break;
4308 		perm = NULL;
4309 	}
4310 	if (perm == NULL) {
4311 		debug_f("requested forward not found");
4312 		return -1;
4313 	}
4314 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4315 	    (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
4316 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4317 	    (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
4318 	    (r = sshpkt_put_u32(ssh, port)) != 0 ||
4319 	    (r = sshpkt_send(ssh)) != 0)
4320 		fatal_fr(r, "send cancel");
4321 
4322 	fwd_perm_clear(perm); /* unregister */
4323 
4324 	return 0;
4325 }
4326 
4327 /*
4328  * Request cancellation of remote forwarding of Unix domain socket
4329  * path from local side.
4330  */
4331 static int
4332 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
4333 {
4334 	struct ssh_channels *sc = ssh->chanctxt;
4335 	struct permission_set *pset = &sc->local_perms;
4336 	int r;
4337 	u_int i;
4338 	struct permission *perm = NULL;
4339 
4340 	for (i = 0; i < pset->num_permitted_user; i++) {
4341 		perm = &pset->permitted_user[i];
4342 		if (open_listen_match_streamlocal(perm, path))
4343 			break;
4344 		perm = NULL;
4345 	}
4346 	if (perm == NULL) {
4347 		debug_f("requested forward not found");
4348 		return -1;
4349 	}
4350 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4351 	    (r = sshpkt_put_cstring(ssh,
4352 	    "cancel-streamlocal-forward@openssh.com")) != 0 ||
4353 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4354 	    (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4355 	    (r = sshpkt_send(ssh)) != 0)
4356 		fatal_fr(r, "send cancel");
4357 
4358 	fwd_perm_clear(perm); /* unregister */
4359 
4360 	return 0;
4361 }
4362 
4363 /*
4364  * Request cancellation of remote forwarding of a connection from local side.
4365  */
4366 int
4367 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4368 {
4369 	if (fwd->listen_path != NULL) {
4370 		return channel_request_rforward_cancel_streamlocal(ssh,
4371 		    fwd->listen_path);
4372 	} else {
4373 		return channel_request_rforward_cancel_tcpip(ssh,
4374 		    fwd->listen_host,
4375 		    fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4376 	}
4377 }
4378 
4379 /*
4380  * Permits opening to any host/port if permitted_user[] is empty.  This is
4381  * usually called by the server, because the user could connect to any port
4382  * anyway, and the server has no way to know but to trust the client anyway.
4383  */
4384 void
4385 channel_permit_all(struct ssh *ssh, int where)
4386 {
4387 	struct permission_set *pset = permission_set_get(ssh, where);
4388 
4389 	if (pset->num_permitted_user == 0)
4390 		pset->all_permitted = 1;
4391 }
4392 
4393 /*
4394  * Permit the specified host/port for forwarding.
4395  */
4396 void
4397 channel_add_permission(struct ssh *ssh, int who, int where,
4398     char *host, int port)
4399 {
4400 	int local = where == FORWARD_LOCAL;
4401 	struct permission_set *pset = permission_set_get(ssh, where);
4402 
4403 	debug("allow %s forwarding to host %s port %d",
4404 	    fwd_ident(who, where), host, port);
4405 	/*
4406 	 * Remote forwards set listen_host/port, local forwards set
4407 	 * host/port_to_connect.
4408 	 */
4409 	permission_set_add(ssh, who, where,
4410 	    local ? host : 0, local ? port : 0,
4411 	    local ? NULL : host, NULL, local ? 0 : port, NULL);
4412 	pset->all_permitted = 0;
4413 }
4414 
4415 /*
4416  * Administratively disable forwarding.
4417  */
4418 void
4419 channel_disable_admin(struct ssh *ssh, int where)
4420 {
4421 	channel_clear_permission(ssh, FORWARD_ADM, where);
4422 	permission_set_add(ssh, FORWARD_ADM, where,
4423 	    NULL, 0, NULL, NULL, 0, NULL);
4424 }
4425 
4426 /*
4427  * Clear a list of permitted opens.
4428  */
4429 void
4430 channel_clear_permission(struct ssh *ssh, int who, int where)
4431 {
4432 	struct permission **permp;
4433 	u_int *npermp;
4434 
4435 	permission_set_get_array(ssh, who, where, &permp, &npermp);
4436 	*permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4437 	*npermp = 0;
4438 }
4439 
4440 /*
4441  * Update the listen port for a dynamic remote forward, after
4442  * the actual 'newport' has been allocated. If 'newport' < 0 is
4443  * passed then they entry will be invalidated.
4444  */
4445 void
4446 channel_update_permission(struct ssh *ssh, int idx, int newport)
4447 {
4448 	struct permission_set *pset = &ssh->chanctxt->local_perms;
4449 
4450 	if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4451 		debug_f("index out of range: %d num_permitted_user %d",
4452 		    idx, pset->num_permitted_user);
4453 		return;
4454 	}
4455 	debug("%s allowed port %d for forwarding to host %s port %d",
4456 	    newport > 0 ? "Updating" : "Removing",
4457 	    newport,
4458 	    pset->permitted_user[idx].host_to_connect,
4459 	    pset->permitted_user[idx].port_to_connect);
4460 	if (newport <= 0)
4461 		fwd_perm_clear(&pset->permitted_user[idx]);
4462 	else {
4463 		pset->permitted_user[idx].listen_port =
4464 		    (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4465 	}
4466 }
4467 
4468 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4469 int
4470 permitopen_port(const char *p)
4471 {
4472 	int port;
4473 
4474 	if (strcmp(p, "*") == 0)
4475 		return FWD_PERMIT_ANY_PORT;
4476 	if ((port = a2port(p)) > 0)
4477 		return port;
4478 	return -1;
4479 }
4480 
4481 /* Try to start non-blocking connect to next host in cctx list */
4482 static int
4483 connect_next(struct channel_connect *cctx)
4484 {
4485 	int sock, saved_errno;
4486 	struct sockaddr_un *sunaddr;
4487 	char ntop[NI_MAXHOST];
4488 	char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4489 
4490 	for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4491 		switch (cctx->ai->ai_family) {
4492 		case AF_UNIX:
4493 			/* unix:pathname instead of host:port */
4494 			sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4495 			strlcpy(ntop, "unix", sizeof(ntop));
4496 			strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4497 			break;
4498 		case AF_INET:
4499 		case AF_INET6:
4500 			if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4501 			    ntop, sizeof(ntop), strport, sizeof(strport),
4502 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4503 				error_f("getnameinfo failed");
4504 				continue;
4505 			}
4506 			break;
4507 		default:
4508 			continue;
4509 		}
4510 		debug_f("start for host %.100s ([%.100s]:%s)",
4511 		    cctx->host, ntop, strport);
4512 		if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4513 		    cctx->ai->ai_protocol)) == -1) {
4514 			if (cctx->ai->ai_next == NULL)
4515 				error("socket: %.100s", strerror(errno));
4516 			else
4517 				verbose("socket: %.100s", strerror(errno));
4518 			continue;
4519 		}
4520 		if (set_nonblock(sock) == -1)
4521 			fatal_f("set_nonblock(%d)", sock);
4522 		if (connect(sock, cctx->ai->ai_addr,
4523 		    cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4524 			debug_f("host %.100s ([%.100s]:%s): %.100s",
4525 			    cctx->host, ntop, strport, strerror(errno));
4526 			saved_errno = errno;
4527 			close(sock);
4528 			errno = saved_errno;
4529 			continue;	/* fail -- try next */
4530 		}
4531 		if (cctx->ai->ai_family != AF_UNIX)
4532 			set_nodelay(sock);
4533 		debug_f("connect host %.100s ([%.100s]:%s) in progress, fd=%d",
4534 		    cctx->host, ntop, strport, sock);
4535 		cctx->ai = cctx->ai->ai_next;
4536 		return sock;
4537 	}
4538 	return -1;
4539 }
4540 
4541 static void
4542 channel_connect_ctx_free(struct channel_connect *cctx)
4543 {
4544 	free(cctx->host);
4545 	if (cctx->aitop) {
4546 		if (cctx->aitop->ai_family == AF_UNIX)
4547 			free(cctx->aitop);
4548 		else
4549 			freeaddrinfo(cctx->aitop);
4550 	}
4551 	memset(cctx, 0, sizeof(*cctx));
4552 }
4553 
4554 /*
4555  * Return connecting socket to remote host:port or local socket path,
4556  * passing back the failure reason if appropriate.
4557  */
4558 static int
4559 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4560     char *ctype, char *rname, struct channel_connect *cctx,
4561     int *reason, const char **errmsg)
4562 {
4563 	struct addrinfo hints;
4564 	int gaierr;
4565 	int sock = -1;
4566 	char strport[NI_MAXSERV];
4567 
4568 	if (port == PORT_STREAMLOCAL) {
4569 		struct sockaddr_un *sunaddr;
4570 		struct addrinfo *ai;
4571 
4572 		if (strlen(name) > sizeof(sunaddr->sun_path)) {
4573 			error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4574 			return -1;
4575 		}
4576 
4577 		/*
4578 		 * Fake up a struct addrinfo for AF_UNIX connections.
4579 		 * channel_connect_ctx_free() must check ai_family
4580 		 * and use free() not freeaddirinfo() for AF_UNIX.
4581 		 */
4582 		ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4583 		memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4584 		ai->ai_addr = (struct sockaddr *)(ai + 1);
4585 		ai->ai_addrlen = sizeof(*sunaddr);
4586 		ai->ai_family = AF_UNIX;
4587 		ai->ai_socktype = socktype;
4588 		ai->ai_protocol = PF_UNSPEC;
4589 		sunaddr = (struct sockaddr_un *)ai->ai_addr;
4590 		sunaddr->sun_family = AF_UNIX;
4591 		strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4592 		cctx->aitop = ai;
4593 	} else {
4594 		memset(&hints, 0, sizeof(hints));
4595 		hints.ai_family = ssh->chanctxt->IPv4or6;
4596 		hints.ai_socktype = socktype;
4597 		snprintf(strport, sizeof strport, "%d", port);
4598 		if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4599 		    != 0) {
4600 			if (errmsg != NULL)
4601 				*errmsg = ssh_gai_strerror(gaierr);
4602 			if (reason != NULL)
4603 				*reason = SSH2_OPEN_CONNECT_FAILED;
4604 			error("connect_to %.100s: unknown host (%s)", name,
4605 			    ssh_gai_strerror(gaierr));
4606 			return -1;
4607 		}
4608 	}
4609 
4610 	cctx->host = xstrdup(name);
4611 	cctx->port = port;
4612 	cctx->ai = cctx->aitop;
4613 
4614 	if ((sock = connect_next(cctx)) == -1) {
4615 		error("connect to %.100s port %d failed: %s",
4616 		    name, port, strerror(errno));
4617 		return -1;
4618 	}
4619 
4620 	return sock;
4621 }
4622 
4623 /* Return CONNECTING channel to remote host:port or local socket path */
4624 static Channel *
4625 connect_to(struct ssh *ssh, const char *host, int port,
4626     char *ctype, char *rname)
4627 {
4628 	struct channel_connect cctx;
4629 	Channel *c;
4630 	int sock;
4631 
4632 	memset(&cctx, 0, sizeof(cctx));
4633 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4634 	    &cctx, NULL, NULL);
4635 	if (sock == -1) {
4636 		channel_connect_ctx_free(&cctx);
4637 		return NULL;
4638 	}
4639 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4640 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4641 	c->host_port = port;
4642 	c->path = xstrdup(host);
4643 	c->connect_ctx = cctx;
4644 
4645 	return c;
4646 }
4647 
4648 /*
4649  * returns either the newly connected channel or the downstream channel
4650  * that needs to deal with this connection.
4651  */
4652 Channel *
4653 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4654     u_short listen_port, char *ctype, char *rname)
4655 {
4656 	struct ssh_channels *sc = ssh->chanctxt;
4657 	struct permission_set *pset = &sc->local_perms;
4658 	u_int i;
4659 	struct permission *perm;
4660 
4661 	for (i = 0; i < pset->num_permitted_user; i++) {
4662 		perm = &pset->permitted_user[i];
4663 		if (open_listen_match_tcpip(perm,
4664 		    listen_host, listen_port, 1)) {
4665 			if (perm->downstream)
4666 				return perm->downstream;
4667 			if (perm->port_to_connect == 0)
4668 				return rdynamic_connect_prepare(ssh,
4669 				    ctype, rname);
4670 			return connect_to(ssh,
4671 			    perm->host_to_connect, perm->port_to_connect,
4672 			    ctype, rname);
4673 		}
4674 	}
4675 	error("WARNING: Server requests forwarding for unknown listen_port %d",
4676 	    listen_port);
4677 	return NULL;
4678 }
4679 
4680 Channel *
4681 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4682     char *ctype, char *rname)
4683 {
4684 	struct ssh_channels *sc = ssh->chanctxt;
4685 	struct permission_set *pset = &sc->local_perms;
4686 	u_int i;
4687 	struct permission *perm;
4688 
4689 	for (i = 0; i < pset->num_permitted_user; i++) {
4690 		perm = &pset->permitted_user[i];
4691 		if (open_listen_match_streamlocal(perm, path)) {
4692 			return connect_to(ssh,
4693 			    perm->host_to_connect, perm->port_to_connect,
4694 			    ctype, rname);
4695 		}
4696 	}
4697 	error("WARNING: Server requests forwarding for unknown path %.100s",
4698 	    path);
4699 	return NULL;
4700 }
4701 
4702 /* Check if connecting to that port is permitted and connect. */
4703 Channel *
4704 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4705     char *ctype, char *rname, int *reason, const char **errmsg)
4706 {
4707 	struct ssh_channels *sc = ssh->chanctxt;
4708 	struct permission_set *pset = &sc->local_perms;
4709 	struct channel_connect cctx;
4710 	Channel *c;
4711 	u_int i, permit, permit_adm = 1;
4712 	int sock;
4713 	struct permission *perm;
4714 
4715 	permit = pset->all_permitted;
4716 	if (!permit) {
4717 		for (i = 0; i < pset->num_permitted_user; i++) {
4718 			perm = &pset->permitted_user[i];
4719 			if (open_match(perm, host, port)) {
4720 				permit = 1;
4721 				break;
4722 			}
4723 		}
4724 	}
4725 
4726 	if (pset->num_permitted_admin > 0) {
4727 		permit_adm = 0;
4728 		for (i = 0; i < pset->num_permitted_admin; i++) {
4729 			perm = &pset->permitted_admin[i];
4730 			if (open_match(perm, host, port)) {
4731 				permit_adm = 1;
4732 				break;
4733 			}
4734 		}
4735 	}
4736 
4737 	if (!permit || !permit_adm) {
4738 		logit("Received request from %.100s port %d to connect to "
4739 		    "host %.100s port %d, but the request was denied.",
4740 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4741 		if (reason != NULL)
4742 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4743 		return NULL;
4744 	}
4745 
4746 	memset(&cctx, 0, sizeof(cctx));
4747 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4748 	    &cctx, reason, errmsg);
4749 	if (sock == -1) {
4750 		channel_connect_ctx_free(&cctx);
4751 		return NULL;
4752 	}
4753 
4754 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4755 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4756 	c->host_port = port;
4757 	c->path = xstrdup(host);
4758 	c->connect_ctx = cctx;
4759 
4760 	return c;
4761 }
4762 
4763 /* Check if connecting to that path is permitted and connect. */
4764 Channel *
4765 channel_connect_to_path(struct ssh *ssh, const char *path,
4766     char *ctype, char *rname)
4767 {
4768 	struct ssh_channels *sc = ssh->chanctxt;
4769 	struct permission_set *pset = &sc->local_perms;
4770 	u_int i, permit, permit_adm = 1;
4771 	struct permission *perm;
4772 
4773 	permit = pset->all_permitted;
4774 	if (!permit) {
4775 		for (i = 0; i < pset->num_permitted_user; i++) {
4776 			perm = &pset->permitted_user[i];
4777 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
4778 				permit = 1;
4779 				break;
4780 			}
4781 		}
4782 	}
4783 
4784 	if (pset->num_permitted_admin > 0) {
4785 		permit_adm = 0;
4786 		for (i = 0; i < pset->num_permitted_admin; i++) {
4787 			perm = &pset->permitted_admin[i];
4788 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
4789 				permit_adm = 1;
4790 				break;
4791 			}
4792 		}
4793 	}
4794 
4795 	if (!permit || !permit_adm) {
4796 		logit("Received request to connect to path %.100s, "
4797 		    "but the request was denied.", path);
4798 		return NULL;
4799 	}
4800 	return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4801 }
4802 
4803 void
4804 channel_send_window_changes(struct ssh *ssh)
4805 {
4806 	struct ssh_channels *sc = ssh->chanctxt;
4807 	struct winsize ws;
4808 	int r;
4809 	u_int i;
4810 
4811 	for (i = 0; i < sc->channels_alloc; i++) {
4812 		if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4813 		    sc->channels[i]->type != SSH_CHANNEL_OPEN)
4814 			continue;
4815 		if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4816 			continue;
4817 		channel_request_start(ssh, i, "window-change", 0);
4818 		if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4819 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4820 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4821 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4822 		    (r = sshpkt_send(ssh)) != 0)
4823 			fatal_fr(r, "channel %u; send window-change", i);
4824 	}
4825 }
4826 
4827 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4828 static Channel *
4829 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4830 {
4831 	Channel *c;
4832 	int r;
4833 
4834 	c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4835 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4836 	c->host_port = 0;
4837 	c->path = NULL;
4838 
4839 	/*
4840 	 * We need to open the channel before we have a FD,
4841 	 * so that we can get SOCKS header from peer.
4842 	 */
4843 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4844 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4845 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4846 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4847 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4848 		fatal_fr(r, "channel %i; confirm", c->self);
4849 	return c;
4850 }
4851 
4852 /* Return CONNECTING socket to remote host:port or local socket path */
4853 static int
4854 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4855 {
4856 	struct ssh_channels *sc = ssh->chanctxt;
4857 	struct permission_set *pset = &sc->local_perms;
4858 	struct permission *perm;
4859 	struct channel_connect cctx;
4860 	u_int i, permit_adm = 1;
4861 	int sock;
4862 
4863 	if (pset->num_permitted_admin > 0) {
4864 		permit_adm = 0;
4865 		for (i = 0; i < pset->num_permitted_admin; i++) {
4866 			perm = &pset->permitted_admin[i];
4867 			if (open_match(perm, c->path, c->host_port)) {
4868 				permit_adm = 1;
4869 				break;
4870 			}
4871 		}
4872 	}
4873 	if (!permit_adm) {
4874 		debug_f("requested forward not permitted");
4875 		return -1;
4876 	}
4877 
4878 	memset(&cctx, 0, sizeof(cctx));
4879 	sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4880 	    NULL, &cctx, NULL, NULL);
4881 	if (sock == -1)
4882 		channel_connect_ctx_free(&cctx);
4883 	else {
4884 		/* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4885 		c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4886 		c->connect_ctx = cctx;
4887 		channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4888 	}
4889 	return sock;
4890 }
4891 
4892 /* -- X11 forwarding */
4893 
4894 /*
4895  * Creates an internet domain socket for listening for X11 connections.
4896  * Returns 0 and a suitable display number for the DISPLAY variable
4897  * stored in display_numberp , or -1 if an error occurs.
4898  */
4899 int
4900 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4901     int x11_use_localhost, int single_connection,
4902     u_int *display_numberp, int **chanids)
4903 {
4904 	Channel *nc = NULL;
4905 	int display_number, sock;
4906 	u_short port;
4907 	struct addrinfo hints, *ai, *aitop;
4908 	char strport[NI_MAXSERV];
4909 	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4910 
4911 	if (chanids == NULL)
4912 		return -1;
4913 
4914 	for (display_number = x11_display_offset;
4915 	    display_number < MAX_DISPLAYS;
4916 	    display_number++) {
4917 		port = 6000 + display_number;
4918 		memset(&hints, 0, sizeof(hints));
4919 		hints.ai_family = ssh->chanctxt->IPv4or6;
4920 		hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4921 		hints.ai_socktype = SOCK_STREAM;
4922 		snprintf(strport, sizeof strport, "%d", port);
4923 		if ((gaierr = getaddrinfo(NULL, strport,
4924 		    &hints, &aitop)) != 0) {
4925 			error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4926 			return -1;
4927 		}
4928 		for (ai = aitop; ai; ai = ai->ai_next) {
4929 			if (ai->ai_family != AF_INET &&
4930 			    ai->ai_family != AF_INET6)
4931 				continue;
4932 			sock = socket(ai->ai_family, ai->ai_socktype,
4933 			    ai->ai_protocol);
4934 			if (sock == -1) {
4935 				error("socket: %.100s", strerror(errno));
4936 				freeaddrinfo(aitop);
4937 				return -1;
4938 			}
4939 			set_reuseaddr(sock);
4940 			if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4941 				debug2_f("bind port %d: %.100s", port,
4942 				    strerror(errno));
4943 				close(sock);
4944 				for (n = 0; n < num_socks; n++)
4945 					close(socks[n]);
4946 				num_socks = 0;
4947 				break;
4948 			}
4949 			socks[num_socks++] = sock;
4950 			if (num_socks == NUM_SOCKS)
4951 				break;
4952 		}
4953 		freeaddrinfo(aitop);
4954 		if (num_socks > 0)
4955 			break;
4956 	}
4957 	if (display_number >= MAX_DISPLAYS) {
4958 		error("Failed to allocate internet-domain X11 display socket.");
4959 		return -1;
4960 	}
4961 	/* Start listening for connections on the socket. */
4962 	for (n = 0; n < num_socks; n++) {
4963 		sock = socks[n];
4964 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
4965 			error("listen: %.100s", strerror(errno));
4966 			close(sock);
4967 			return -1;
4968 		}
4969 	}
4970 
4971 	/* Allocate a channel for each socket. */
4972 	*chanids = xcalloc(num_socks + 1, sizeof(**chanids));
4973 	for (n = 0; n < num_socks; n++) {
4974 		sock = socks[n];
4975 		nc = channel_new(ssh, "x11-listener",
4976 		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
4977 		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
4978 		    0, "X11 inet listener", 1);
4979 		nc->single_connection = single_connection;
4980 		(*chanids)[n] = nc->self;
4981 	}
4982 	(*chanids)[n] = -1;
4983 
4984 	/* Return the display number for the DISPLAY environment variable. */
4985 	*display_numberp = display_number;
4986 	return 0;
4987 }
4988 
4989 static int
4990 connect_local_xsocket(u_int dnr)
4991 {
4992 	int sock;
4993 	struct sockaddr_un addr;
4994 
4995 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
4996 	if (sock == -1)
4997 		error("socket: %.100s", strerror(errno));
4998 	memset(&addr, 0, sizeof(addr));
4999 	addr.sun_family = AF_UNIX;
5000 	snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
5001 	if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
5002 		return sock;
5003 	close(sock);
5004 	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
5005 	return -1;
5006 }
5007 
5008 int
5009 x11_connect_display(struct ssh *ssh)
5010 {
5011 	u_int display_number;
5012 	const char *display;
5013 	char buf[1024], *cp;
5014 	struct addrinfo hints, *ai, *aitop;
5015 	char strport[NI_MAXSERV];
5016 	int gaierr, sock = 0;
5017 
5018 	/* Try to open a socket for the local X server. */
5019 	display = getenv("DISPLAY");
5020 	if (!display) {
5021 		error("DISPLAY not set.");
5022 		return -1;
5023 	}
5024 	/*
5025 	 * Now we decode the value of the DISPLAY variable and make a
5026 	 * connection to the real X server.
5027 	 */
5028 
5029 	/*
5030 	 * Check if it is a unix domain socket.  Unix domain displays are in
5031 	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
5032 	 */
5033 	if (strncmp(display, "unix:", 5) == 0 ||
5034 	    display[0] == ':') {
5035 		/* Connect to the unix domain socket. */
5036 		if (sscanf(strrchr(display, ':') + 1, "%u",
5037 		    &display_number) != 1) {
5038 			error("Could not parse display number from DISPLAY: "
5039 			    "%.100s", display);
5040 			return -1;
5041 		}
5042 		/* Create a socket. */
5043 		sock = connect_local_xsocket(display_number);
5044 		if (sock < 0)
5045 			return -1;
5046 
5047 		/* OK, we now have a connection to the display. */
5048 		return sock;
5049 	}
5050 	/*
5051 	 * Connect to an inet socket.  The DISPLAY value is supposedly
5052 	 * hostname:d[.s], where hostname may also be numeric IP address.
5053 	 */
5054 	strlcpy(buf, display, sizeof(buf));
5055 	cp = strchr(buf, ':');
5056 	if (!cp) {
5057 		error("Could not find ':' in DISPLAY: %.100s", display);
5058 		return -1;
5059 	}
5060 	*cp = 0;
5061 	/*
5062 	 * buf now contains the host name.  But first we parse the
5063 	 * display number.
5064 	 */
5065 	if (sscanf(cp + 1, "%u", &display_number) != 1) {
5066 		error("Could not parse display number from DISPLAY: %.100s",
5067 		    display);
5068 		return -1;
5069 	}
5070 
5071 	/* Look up the host address */
5072 	memset(&hints, 0, sizeof(hints));
5073 	hints.ai_family = ssh->chanctxt->IPv4or6;
5074 	hints.ai_socktype = SOCK_STREAM;
5075 	snprintf(strport, sizeof strport, "%u", 6000 + display_number);
5076 	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
5077 		error("%.100s: unknown host. (%s)", buf,
5078 		ssh_gai_strerror(gaierr));
5079 		return -1;
5080 	}
5081 	for (ai = aitop; ai; ai = ai->ai_next) {
5082 		/* Create a socket. */
5083 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
5084 		if (sock == -1) {
5085 			debug2("socket: %.100s", strerror(errno));
5086 			continue;
5087 		}
5088 		/* Connect it to the display. */
5089 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
5090 			debug2("connect %.100s port %u: %.100s", buf,
5091 			    6000 + display_number, strerror(errno));
5092 			close(sock);
5093 			continue;
5094 		}
5095 		/* Success */
5096 		break;
5097 	}
5098 	freeaddrinfo(aitop);
5099 	if (!ai) {
5100 		error("connect %.100s port %u: %.100s", buf,
5101 		    6000 + display_number, strerror(errno));
5102 		return -1;
5103 	}
5104 	set_nodelay(sock);
5105 	return sock;
5106 }
5107 
5108 /*
5109  * Requests forwarding of X11 connections, generates fake authentication
5110  * data, and enables authentication spoofing.
5111  * This should be called in the client only.
5112  */
5113 void
5114 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
5115     const char *disp, const char *proto, const char *data, int want_reply)
5116 {
5117 	struct ssh_channels *sc = ssh->chanctxt;
5118 	u_int data_len = (u_int) strlen(data) / 2;
5119 	u_int i, value;
5120 	const char *cp;
5121 	char *new_data;
5122 	int r, screen_number;
5123 
5124 	if (sc->x11_saved_display == NULL)
5125 		sc->x11_saved_display = xstrdup(disp);
5126 	else if (strcmp(disp, sc->x11_saved_display) != 0) {
5127 		error("x11_request_forwarding_with_spoofing: different "
5128 		    "$DISPLAY already forwarded");
5129 		return;
5130 	}
5131 
5132 	cp = strchr(disp, ':');
5133 	if (cp)
5134 		cp = strchr(cp, '.');
5135 	if (cp)
5136 		screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
5137 	else
5138 		screen_number = 0;
5139 
5140 	if (sc->x11_saved_proto == NULL) {
5141 		/* Save protocol name. */
5142 		sc->x11_saved_proto = xstrdup(proto);
5143 
5144 		/* Extract real authentication data. */
5145 		sc->x11_saved_data = xmalloc(data_len);
5146 		for (i = 0; i < data_len; i++) {
5147 			if (sscanf(data + 2 * i, "%2x", &value) != 1) {
5148 				fatal("x11_request_forwarding: bad "
5149 				    "authentication data: %.100s", data);
5150 			}
5151 			sc->x11_saved_data[i] = value;
5152 		}
5153 		sc->x11_saved_data_len = data_len;
5154 
5155 		/* Generate fake data of the same length. */
5156 		sc->x11_fake_data = xmalloc(data_len);
5157 		arc4random_buf(sc->x11_fake_data, data_len);
5158 		sc->x11_fake_data_len = data_len;
5159 	}
5160 
5161 	/* Convert the fake data into hex. */
5162 	new_data = tohex(sc->x11_fake_data, data_len);
5163 
5164 	/* Send the request packet. */
5165 	channel_request_start(ssh, client_session_id, "x11-req", want_reply);
5166 	if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
5167 	    (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
5168 	    (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
5169 	    (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
5170 	    (r = sshpkt_send(ssh)) != 0 ||
5171 	    (r = ssh_packet_write_wait(ssh)) != 0)
5172 		fatal_fr(r, "send x11-req");
5173 	free(new_data);
5174 }
5175