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