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