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