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