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