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