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