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