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