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