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