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