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