xref: /freebsd/crypto/openssh/channels.c (revision 9768746b)
1 /* $OpenBSD: channels.c,v 1.427 2023/01/18 02:00:10 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 	u_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 	u_int 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     u_int timeout_secs)
316 {
317 	struct ssh_channels *sc = ssh->chanctxt;
318 
319 	debug2_f("channel type \"%s\" timeout %u 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 u_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 		fcntl(rfd, F_SETFD, FD_CLOEXEC);
391 	if (wfd != -1 && wfd != rfd)
392 		fcntl(wfd, F_SETFD, FD_CLOEXEC);
393 	if (efd != -1 && efd != rfd && efd != wfd)
394 		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 	    (u_int)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, u_short 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, "direct-tcpip");
1655 
1656 	return c;
1657 }
1658 
1659 /* dynamic port forwarding */
1660 static void
1661 channel_pre_dynamic(struct ssh *ssh, Channel *c)
1662 {
1663 	const u_char *p;
1664 	u_int have;
1665 	int ret;
1666 
1667 	c->io_want = 0;
1668 	have = sshbuf_len(c->input);
1669 	debug2("channel %d: pre_dynamic: have %d", c->self, have);
1670 	/* sshbuf_dump(c->input, stderr); */
1671 	/* check if the fixed size part of the packet is in buffer. */
1672 	if (have < 3) {
1673 		/* need more */
1674 		c->io_want |= SSH_CHAN_IO_RFD;
1675 		return;
1676 	}
1677 	/* try to guess the protocol */
1678 	p = sshbuf_ptr(c->input);
1679 	/* XXX sshbuf_peek_u8? */
1680 	switch (p[0]) {
1681 	case 0x04:
1682 		ret = channel_decode_socks4(c, c->input, c->output);
1683 		break;
1684 	case 0x05:
1685 		ret = channel_decode_socks5(c, c->input, c->output);
1686 		break;
1687 	default:
1688 		ret = -1;
1689 		break;
1690 	}
1691 	if (ret < 0) {
1692 		chan_mark_dead(ssh, c);
1693 	} else if (ret == 0) {
1694 		debug2("channel %d: pre_dynamic: need more", c->self);
1695 		/* need more */
1696 		c->io_want |= SSH_CHAN_IO_RFD;
1697 		if (sshbuf_len(c->output))
1698 			c->io_want |= SSH_CHAN_IO_WFD;
1699 	} else {
1700 		/* switch to the next state */
1701 		c->type = SSH_CHANNEL_OPENING;
1702 		port_open_helper(ssh, c, "direct-tcpip");
1703 	}
1704 }
1705 
1706 /* simulate read-error */
1707 static void
1708 rdynamic_close(struct ssh *ssh, Channel *c)
1709 {
1710 	c->type = SSH_CHANNEL_OPEN;
1711 	channel_force_close(ssh, c, 0);
1712 }
1713 
1714 /* reverse dynamic port forwarding */
1715 static void
1716 channel_before_prepare_io_rdynamic(struct ssh *ssh, Channel *c)
1717 {
1718 	const u_char *p;
1719 	u_int have, len;
1720 	int r, ret;
1721 
1722 	have = sshbuf_len(c->output);
1723 	debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1724 	/* sshbuf_dump(c->output, stderr); */
1725 	/* EOF received */
1726 	if (c->flags & CHAN_EOF_RCVD) {
1727 		if ((r = sshbuf_consume(c->output, have)) != 0)
1728 			fatal_fr(r, "channel %d: consume", c->self);
1729 		rdynamic_close(ssh, c);
1730 		return;
1731 	}
1732 	/* check if the fixed size part of the packet is in buffer. */
1733 	if (have < 3)
1734 		return;
1735 	/* try to guess the protocol */
1736 	p = sshbuf_ptr(c->output);
1737 	switch (p[0]) {
1738 	case 0x04:
1739 		/* switch input/output for reverse forwarding */
1740 		ret = channel_decode_socks4(c, c->output, c->input);
1741 		break;
1742 	case 0x05:
1743 		ret = channel_decode_socks5(c, c->output, c->input);
1744 		break;
1745 	default:
1746 		ret = -1;
1747 		break;
1748 	}
1749 	if (ret < 0) {
1750 		rdynamic_close(ssh, c);
1751 	} else if (ret == 0) {
1752 		debug2("channel %d: pre_rdynamic: need more", c->self);
1753 		/* send socks request to peer */
1754 		len = sshbuf_len(c->input);
1755 		if (len > 0 && len < c->remote_window) {
1756 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1757 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1758 			    (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1759 			    (r = sshpkt_send(ssh)) != 0) {
1760 				fatal_fr(r, "channel %i: rdynamic", c->self);
1761 			}
1762 			if ((r = sshbuf_consume(c->input, len)) != 0)
1763 				fatal_fr(r, "channel %d: consume", c->self);
1764 			c->remote_window -= len;
1765 		}
1766 	} else if (rdynamic_connect_finish(ssh, c) < 0) {
1767 		/* the connect failed */
1768 		rdynamic_close(ssh, c);
1769 	}
1770 }
1771 
1772 /* This is our fake X11 server socket. */
1773 static void
1774 channel_post_x11_listener(struct ssh *ssh, Channel *c)
1775 {
1776 	Channel *nc;
1777 	struct sockaddr_storage addr;
1778 	int r, newsock, oerrno, remote_port;
1779 	socklen_t addrlen;
1780 	char buf[16384], *remote_ipaddr;
1781 
1782 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1783 		return;
1784 
1785 	debug("X11 connection requested.");
1786 	addrlen = sizeof(addr);
1787 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1788 	if (c->single_connection) {
1789 		oerrno = errno;
1790 		debug2("single_connection: closing X11 listener.");
1791 		channel_close_fd(ssh, c, &c->sock);
1792 		chan_mark_dead(ssh, c);
1793 		errno = oerrno;
1794 	}
1795 	if (newsock == -1) {
1796 		if (errno != EINTR && errno != EWOULDBLOCK &&
1797 		    errno != ECONNABORTED)
1798 			error("accept: %.100s", strerror(errno));
1799 		if (errno == EMFILE || errno == ENFILE)
1800 			c->notbefore = monotime() + 1;
1801 		return;
1802 	}
1803 	set_nodelay(newsock);
1804 	remote_ipaddr = get_peer_ipaddr(newsock);
1805 	remote_port = get_peer_port(newsock);
1806 	snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1807 	    remote_ipaddr, remote_port);
1808 
1809 	nc = channel_new(ssh, "x11-connection",
1810 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1811 	    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1812 	open_preamble(ssh, __func__, nc, "x11");
1813 	if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1814 	    (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1815 		fatal_fr(r, "channel %i: reply", c->self);
1816 	}
1817 	if ((r = sshpkt_send(ssh)) != 0)
1818 		fatal_fr(r, "channel %i: send", c->self);
1819 	free(remote_ipaddr);
1820 }
1821 
1822 static void
1823 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1824 {
1825 	char *local_ipaddr = get_local_ipaddr(c->sock);
1826 	int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1827 	char *remote_ipaddr = get_peer_ipaddr(c->sock);
1828 	int remote_port = get_peer_port(c->sock);
1829 	int r;
1830 
1831 	if (remote_port == -1) {
1832 		/* Fake addr/port to appease peers that validate it (Tectia) */
1833 		free(remote_ipaddr);
1834 		remote_ipaddr = xstrdup("127.0.0.1");
1835 		remote_port = 65535;
1836 	}
1837 
1838 	free(c->remote_name);
1839 	xasprintf(&c->remote_name,
1840 	    "%s: listening port %d for %.100s port %d, "
1841 	    "connect from %.200s port %d to %.100s port %d",
1842 	    rtype, c->listening_port, c->path, c->host_port,
1843 	    remote_ipaddr, remote_port, local_ipaddr, local_port);
1844 
1845 	open_preamble(ssh, __func__, c, rtype);
1846 	if (strcmp(rtype, "direct-tcpip") == 0) {
1847 		/* target host, port */
1848 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1849 		    (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1850 			fatal_fr(r, "channel %i: reply", c->self);
1851 	} else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1852 		/* target path */
1853 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1854 			fatal_fr(r, "channel %i: reply", c->self);
1855 	} else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1856 		/* listen path */
1857 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1858 			fatal_fr(r, "channel %i: reply", c->self);
1859 	} else {
1860 		/* listen address, port */
1861 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1862 		    (r = sshpkt_put_u32(ssh, local_port)) != 0)
1863 			fatal_fr(r, "channel %i: reply", c->self);
1864 	}
1865 	if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1866 		/* reserved for future owner/mode info */
1867 		if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1868 			fatal_fr(r, "channel %i: reply", c->self);
1869 	} else {
1870 		/* originator host and port */
1871 		if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1872 		    (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1873 			fatal_fr(r, "channel %i: reply", c->self);
1874 	}
1875 	if ((r = sshpkt_send(ssh)) != 0)
1876 		fatal_fr(r, "channel %i: send", c->self);
1877 	free(remote_ipaddr);
1878 	free(local_ipaddr);
1879 }
1880 
1881 void
1882 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1883 {
1884 	ssh->chanctxt->x11_refuse_time = refuse_time;
1885 }
1886 
1887 /*
1888  * This socket is listening for connections to a forwarded TCP/IP port.
1889  */
1890 static void
1891 channel_post_port_listener(struct ssh *ssh, Channel *c)
1892 {
1893 	Channel *nc;
1894 	struct sockaddr_storage addr;
1895 	int newsock, nextstate;
1896 	socklen_t addrlen;
1897 	char *rtype;
1898 
1899 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1900 		return;
1901 
1902 	debug("Connection to port %d forwarding to %.100s port %d requested.",
1903 	    c->listening_port, c->path, c->host_port);
1904 
1905 	if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1906 		nextstate = SSH_CHANNEL_OPENING;
1907 		rtype = "forwarded-tcpip";
1908 	} else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1909 		nextstate = SSH_CHANNEL_OPENING;
1910 		rtype = "forwarded-streamlocal@openssh.com";
1911 	} else if (c->host_port == PORT_STREAMLOCAL) {
1912 		nextstate = SSH_CHANNEL_OPENING;
1913 		rtype = "direct-streamlocal@openssh.com";
1914 	} else if (c->host_port == 0) {
1915 		nextstate = SSH_CHANNEL_DYNAMIC;
1916 		rtype = "dynamic-tcpip";
1917 	} else {
1918 		nextstate = SSH_CHANNEL_OPENING;
1919 		rtype = "direct-tcpip";
1920 	}
1921 
1922 	addrlen = sizeof(addr);
1923 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1924 	if (newsock == -1) {
1925 		if (errno != EINTR && errno != EWOULDBLOCK &&
1926 		    errno != ECONNABORTED)
1927 			error("accept: %.100s", strerror(errno));
1928 		if (errno == EMFILE || errno == ENFILE)
1929 			c->notbefore = monotime() + 1;
1930 		return;
1931 	}
1932 	if (c->host_port != PORT_STREAMLOCAL)
1933 		set_nodelay(newsock);
1934 	nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1935 	    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1936 	nc->listening_port = c->listening_port;
1937 	nc->host_port = c->host_port;
1938 	if (c->path != NULL)
1939 		nc->path = xstrdup(c->path);
1940 
1941 	if (nextstate != SSH_CHANNEL_DYNAMIC)
1942 		port_open_helper(ssh, nc, rtype);
1943 }
1944 
1945 /*
1946  * This is the authentication agent socket listening for connections from
1947  * clients.
1948  */
1949 static void
1950 channel_post_auth_listener(struct ssh *ssh, Channel *c)
1951 {
1952 	Channel *nc;
1953 	int r, newsock;
1954 	struct sockaddr_storage addr;
1955 	socklen_t addrlen;
1956 
1957 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
1958 		return;
1959 
1960 	addrlen = sizeof(addr);
1961 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1962 	if (newsock == -1) {
1963 		error("accept from auth socket: %.100s", strerror(errno));
1964 		if (errno == EMFILE || errno == ENFILE)
1965 			c->notbefore = monotime() + 1;
1966 		return;
1967 	}
1968 	nc = channel_new(ssh, "agent-connection",
1969 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1970 	    c->local_window_max, c->local_maxpacket,
1971 	    0, "accepted auth socket", 1);
1972 	open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1973 	if ((r = sshpkt_send(ssh)) != 0)
1974 		fatal_fr(r, "channel %i", c->self);
1975 }
1976 
1977 static void
1978 channel_post_connecting(struct ssh *ssh, Channel *c)
1979 {
1980 	int err = 0, sock, isopen, r;
1981 	socklen_t sz = sizeof(err);
1982 
1983 	if ((c->io_ready & SSH_CHAN_IO_SOCK_W) == 0)
1984 		return;
1985 	if (!c->have_remote_id)
1986 		fatal_f("channel %d: no remote id", c->self);
1987 	/* for rdynamic the OPEN_CONFIRMATION has been sent already */
1988 	isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1989 	if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1990 		err = errno;
1991 		error("getsockopt SO_ERROR failed");
1992 	}
1993 	if (err == 0) {
1994 		debug("channel %d: connected to %s port %d",
1995 		    c->self, c->connect_ctx.host, c->connect_ctx.port);
1996 		channel_connect_ctx_free(&c->connect_ctx);
1997 		c->type = SSH_CHANNEL_OPEN;
1998 		c->lastused = monotime();
1999 		if (isopen) {
2000 			/* no message necessary */
2001 		} else {
2002 			if ((r = sshpkt_start(ssh,
2003 			    SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
2004 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2005 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
2006 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
2007 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
2008 			    (r = sshpkt_send(ssh)) != 0)
2009 				fatal_fr(r, "channel %i open confirm", c->self);
2010 		}
2011 	} else {
2012 		debug("channel %d: connection failed: %s",
2013 		    c->self, strerror(err));
2014 		/* Try next address, if any */
2015 		if ((sock = connect_next(&c->connect_ctx)) > 0) {
2016 			close(c->sock);
2017 			c->sock = c->rfd = c->wfd = sock;
2018 			return;
2019 		}
2020 		/* Exhausted all addresses */
2021 		error("connect_to %.100s port %d: failed.",
2022 		    c->connect_ctx.host, c->connect_ctx.port);
2023 		channel_connect_ctx_free(&c->connect_ctx);
2024 		if (isopen) {
2025 			rdynamic_close(ssh, c);
2026 		} else {
2027 			if ((r = sshpkt_start(ssh,
2028 			    SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
2029 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2030 			    (r = sshpkt_put_u32(ssh,
2031 			    SSH2_OPEN_CONNECT_FAILED)) != 0 ||
2032 			    (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
2033 			    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
2034 			    (r = sshpkt_send(ssh)) != 0)
2035 				fatal_fr(r, "channel %i: failure", c->self);
2036 			chan_mark_dead(ssh, c);
2037 		}
2038 	}
2039 }
2040 
2041 static int
2042 channel_handle_rfd(struct ssh *ssh, Channel *c)
2043 {
2044 	char buf[CHAN_RBUF];
2045 	ssize_t len;
2046 	int r, force;
2047 	size_t nr = 0, have, avail, maxlen = CHANNEL_MAX_READ;
2048 	int pty_zeroread = 0;
2049 
2050 #ifdef PTY_ZEROREAD
2051 	/* Bug on AIX: read(1) can return 0 for a non-closed fd */
2052 	pty_zeroread = c->isatty;
2053 #endif
2054 
2055 	force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2056 
2057 	if (!force && (c->io_ready & SSH_CHAN_IO_RFD) == 0)
2058 		return 1;
2059 	if ((avail = sshbuf_avail(c->input)) == 0)
2060 		return 1; /* Shouldn't happen */
2061 
2062 	/*
2063 	 * For "simple" channels (i.e. not datagram or filtered), we can
2064 	 * read directly to the channel buffer.
2065 	 */
2066 	if (!pty_zeroread && c->input_filter == NULL && !c->datagram) {
2067 		/* Only OPEN channels have valid rwin */
2068 		if (c->type == SSH_CHANNEL_OPEN) {
2069 			if ((have = sshbuf_len(c->input)) >= c->remote_window)
2070 				return 1; /* shouldn't happen */
2071 			if (maxlen > c->remote_window - have)
2072 				maxlen = c->remote_window - have;
2073 		}
2074 		if (maxlen > avail)
2075 			maxlen = avail;
2076 		if ((r = sshbuf_read(c->rfd, c->input, maxlen, &nr)) != 0) {
2077 			if (errno == EINTR || (!force &&
2078 			    (errno == EAGAIN || errno == EWOULDBLOCK)))
2079 				return 1;
2080 			debug2("channel %d: read failed rfd %d maxlen %zu: %s",
2081 			    c->self, c->rfd, maxlen, ssh_err(r));
2082 			goto rfail;
2083 		}
2084 		if (nr != 0)
2085 			c->lastused = monotime();
2086 		return 1;
2087 	}
2088 
2089 	errno = 0;
2090 	len = read(c->rfd, buf, sizeof(buf));
2091 	/* fixup AIX zero-length read with errno set to look more like errors */
2092 	if (pty_zeroread && len == 0 && errno != 0)
2093 		len = -1;
2094 	if (len == -1 && (errno == EINTR ||
2095 	    ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
2096 		return 1;
2097 	if (len < 0 || (!pty_zeroread && len == 0)) {
2098 		debug2("channel %d: read<=0 rfd %d len %zd: %s",
2099 		    c->self, c->rfd, len,
2100 		    len == 0 ? "closed" : strerror(errno));
2101  rfail:
2102 		if (c->type != SSH_CHANNEL_OPEN) {
2103 			debug2("channel %d: not open", c->self);
2104 			chan_mark_dead(ssh, c);
2105 			return -1;
2106 		} else {
2107 			chan_read_failed(ssh, c);
2108 		}
2109 		return -1;
2110 	}
2111 	c->lastused = monotime();
2112 	if (c->input_filter != NULL) {
2113 		if (c->input_filter(ssh, c, buf, len) == -1) {
2114 			debug2("channel %d: filter stops", c->self);
2115 			chan_read_failed(ssh, c);
2116 		}
2117 	} else if (c->datagram) {
2118 		if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
2119 			fatal_fr(r, "channel %i: put datagram", c->self);
2120 	} else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2121 		fatal_fr(r, "channel %i: put data", c->self);
2122 
2123 	return 1;
2124 }
2125 
2126 static int
2127 channel_handle_wfd(struct ssh *ssh, Channel *c)
2128 {
2129 	struct termios tio;
2130 	u_char *data = NULL, *buf; /* XXX const; need filter API change */
2131 	size_t dlen, olen = 0;
2132 	int r, len;
2133 
2134 	if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2135 		return 1;
2136 	if (sshbuf_len(c->output) == 0)
2137 		return 1;
2138 
2139 	/* Send buffered output data to the socket. */
2140 	olen = sshbuf_len(c->output);
2141 	if (c->output_filter != NULL) {
2142 		if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
2143 			debug2("channel %d: filter stops", c->self);
2144 			if (c->type != SSH_CHANNEL_OPEN)
2145 				chan_mark_dead(ssh, c);
2146 			else
2147 				chan_write_failed(ssh, c);
2148 			return -1;
2149 		}
2150 	} else if (c->datagram) {
2151 		if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
2152 			fatal_fr(r, "channel %i: get datagram", c->self);
2153 		buf = data;
2154 	} else {
2155 		buf = data = sshbuf_mutable_ptr(c->output);
2156 		dlen = sshbuf_len(c->output);
2157 	}
2158 
2159 	if (c->datagram) {
2160 		/* ignore truncated writes, datagrams might get lost */
2161 		len = write(c->wfd, buf, dlen);
2162 		free(data);
2163 		if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2164 		    errno == EWOULDBLOCK))
2165 			return 1;
2166 		if (len <= 0)
2167 			goto write_fail;
2168 		goto out;
2169 	}
2170 
2171 #ifdef _AIX
2172 	/* XXX: Later AIX versions can't push as much data to tty */
2173 	if (c->wfd_isatty)
2174 		dlen = MINIMUM(dlen, 8*1024);
2175 #endif
2176 
2177 	len = write(c->wfd, buf, dlen);
2178 	if (len == -1 &&
2179 	    (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2180 		return 1;
2181 	if (len <= 0) {
2182  write_fail:
2183 		if (c->type != SSH_CHANNEL_OPEN) {
2184 			debug2("channel %d: not open", c->self);
2185 			chan_mark_dead(ssh, c);
2186 			return -1;
2187 		} else {
2188 			chan_write_failed(ssh, c);
2189 		}
2190 		return -1;
2191 	}
2192 	c->lastused = monotime();
2193 #ifndef BROKEN_TCGETATTR_ICANON
2194 	if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2195 		if (tcgetattr(c->wfd, &tio) == 0 &&
2196 		    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2197 			/*
2198 			 * Simulate echo to reduce the impact of
2199 			 * traffic analysis. We need to match the
2200 			 * size of a SSH2_MSG_CHANNEL_DATA message
2201 			 * (4 byte channel id + buf)
2202 			 */
2203 			if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2204 			    (r = sshpkt_send(ssh)) != 0)
2205 				fatal_fr(r, "channel %i: ignore", c->self);
2206 		}
2207 	}
2208 #endif /* BROKEN_TCGETATTR_ICANON */
2209 	if ((r = sshbuf_consume(c->output, len)) != 0)
2210 		fatal_fr(r, "channel %i: consume", c->self);
2211  out:
2212 	c->local_consumed += olen - sshbuf_len(c->output);
2213 
2214 	return 1;
2215 }
2216 
2217 static int
2218 channel_handle_efd_write(struct ssh *ssh, Channel *c)
2219 {
2220 	int r;
2221 	ssize_t len;
2222 
2223 	if ((c->io_ready & SSH_CHAN_IO_EFD_W) == 0)
2224 		return 1;
2225 	if (sshbuf_len(c->extended) == 0)
2226 		return 1;
2227 
2228 	len = write(c->efd, sshbuf_ptr(c->extended),
2229 	    sshbuf_len(c->extended));
2230 	debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2231 	if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2232 	    errno == EWOULDBLOCK))
2233 		return 1;
2234 	if (len <= 0) {
2235 		debug2("channel %d: closing write-efd %d", c->self, c->efd);
2236 		channel_close_fd(ssh, c, &c->efd);
2237 	} else {
2238 		if ((r = sshbuf_consume(c->extended, len)) != 0)
2239 			fatal_fr(r, "channel %i: consume", c->self);
2240 		c->local_consumed += len;
2241 		c->lastused = monotime();
2242 	}
2243 	return 1;
2244 }
2245 
2246 static int
2247 channel_handle_efd_read(struct ssh *ssh, Channel *c)
2248 {
2249 	char buf[CHAN_RBUF];
2250 	ssize_t len;
2251 	int r, force;
2252 
2253 	force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2254 
2255 	if (!force && (c->io_ready & SSH_CHAN_IO_EFD_R) == 0)
2256 		return 1;
2257 
2258 	len = read(c->efd, buf, sizeof(buf));
2259 	debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2260 	if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
2261 	    errno == EWOULDBLOCK) && !force)))
2262 		return 1;
2263 	if (len <= 0) {
2264 		debug2("channel %d: closing read-efd %d", c->self, c->efd);
2265 		channel_close_fd(ssh, c, &c->efd);
2266 		return 1;
2267 	}
2268 	c->lastused = monotime();
2269 	if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2270 		debug3("channel %d: discard efd", c->self);
2271 	else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2272 		fatal_fr(r, "channel %i: append", c->self);
2273 	return 1;
2274 }
2275 
2276 static int
2277 channel_handle_efd(struct ssh *ssh, Channel *c)
2278 {
2279 	if (c->efd == -1)
2280 		return 1;
2281 
2282 	/** XXX handle drain efd, too */
2283 
2284 	if (c->extended_usage == CHAN_EXTENDED_WRITE)
2285 		return channel_handle_efd_write(ssh, c);
2286 	else if (c->extended_usage == CHAN_EXTENDED_READ ||
2287 	    c->extended_usage == CHAN_EXTENDED_IGNORE)
2288 		return channel_handle_efd_read(ssh, c);
2289 
2290 	return 1;
2291 }
2292 
2293 static int
2294 channel_check_window(struct ssh *ssh, Channel *c)
2295 {
2296 	int r;
2297 
2298 	if (c->type == SSH_CHANNEL_OPEN &&
2299 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2300 	    ((c->local_window_max - c->local_window >
2301 	    c->local_maxpacket*3) ||
2302 	    c->local_window < c->local_window_max/2) &&
2303 	    c->local_consumed > 0) {
2304 		if (!c->have_remote_id)
2305 			fatal_f("channel %d: no remote id", c->self);
2306 		if ((r = sshpkt_start(ssh,
2307 		    SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2308 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2309 		    (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2310 		    (r = sshpkt_send(ssh)) != 0) {
2311 			fatal_fr(r, "channel %i", c->self);
2312 		}
2313 		debug2("channel %d: window %d sent adjust %d", c->self,
2314 		    c->local_window, c->local_consumed);
2315 		c->local_window += c->local_consumed;
2316 		c->local_consumed = 0;
2317 	}
2318 	return 1;
2319 }
2320 
2321 static void
2322 channel_post_open(struct ssh *ssh, Channel *c)
2323 {
2324 	channel_handle_rfd(ssh, c);
2325 	channel_handle_wfd(ssh, c);
2326 	channel_handle_efd(ssh, c);
2327 	channel_check_window(ssh, c);
2328 }
2329 
2330 static u_int
2331 read_mux(struct ssh *ssh, Channel *c, u_int need)
2332 {
2333 	char buf[CHAN_RBUF];
2334 	ssize_t len;
2335 	u_int rlen;
2336 	int r;
2337 
2338 	if (sshbuf_len(c->input) < need) {
2339 		rlen = need - sshbuf_len(c->input);
2340 		len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2341 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
2342 			return sshbuf_len(c->input);
2343 		if (len <= 0) {
2344 			debug2("channel %d: ctl read<=0 rfd %d len %zd",
2345 			    c->self, c->rfd, len);
2346 			chan_read_failed(ssh, c);
2347 			return 0;
2348 		} else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2349 			fatal_fr(r, "channel %i: append", c->self);
2350 	}
2351 	return sshbuf_len(c->input);
2352 }
2353 
2354 static void
2355 channel_post_mux_client_read(struct ssh *ssh, Channel *c)
2356 {
2357 	u_int need;
2358 
2359 	if ((c->io_ready & SSH_CHAN_IO_RFD) == 0)
2360 		return;
2361 	if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2362 		return;
2363 	if (c->mux_pause)
2364 		return;
2365 
2366 	/*
2367 	 * Don't not read past the precise end of packets to
2368 	 * avoid disrupting fd passing.
2369 	 */
2370 	if (read_mux(ssh, c, 4) < 4) /* read header */
2371 		return;
2372 	/* XXX sshbuf_peek_u32 */
2373 	need = PEEK_U32(sshbuf_ptr(c->input));
2374 #define CHANNEL_MUX_MAX_PACKET	(256 * 1024)
2375 	if (need > CHANNEL_MUX_MAX_PACKET) {
2376 		debug2("channel %d: packet too big %u > %u",
2377 		    c->self, CHANNEL_MUX_MAX_PACKET, need);
2378 		chan_rcvd_oclose(ssh, c);
2379 		return;
2380 	}
2381 	if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2382 		return;
2383 	if (c->mux_rcb(ssh, c) != 0) {
2384 		debug("channel %d: mux_rcb failed", c->self);
2385 		chan_mark_dead(ssh, c);
2386 		return;
2387 	}
2388 }
2389 
2390 static void
2391 channel_post_mux_client_write(struct ssh *ssh, Channel *c)
2392 {
2393 	ssize_t len;
2394 	int r;
2395 
2396 	if ((c->io_ready & SSH_CHAN_IO_WFD) == 0)
2397 		return;
2398 	if (sshbuf_len(c->output) == 0)
2399 		return;
2400 
2401 	len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2402 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2403 		return;
2404 	if (len <= 0) {
2405 		chan_mark_dead(ssh, c);
2406 		return;
2407 	}
2408 	if ((r = sshbuf_consume(c->output, len)) != 0)
2409 		fatal_fr(r, "channel %i: consume", c->self);
2410 }
2411 
2412 static void
2413 channel_post_mux_client(struct ssh *ssh, Channel *c)
2414 {
2415 	channel_post_mux_client_read(ssh, c);
2416 	channel_post_mux_client_write(ssh, c);
2417 }
2418 
2419 static void
2420 channel_post_mux_listener(struct ssh *ssh, Channel *c)
2421 {
2422 	Channel *nc;
2423 	struct sockaddr_storage addr;
2424 	socklen_t addrlen;
2425 	int newsock;
2426 	uid_t euid;
2427 	gid_t egid;
2428 
2429 	if ((c->io_ready & SSH_CHAN_IO_SOCK_R) == 0)
2430 		return;
2431 
2432 	debug("multiplexing control connection");
2433 
2434 	/*
2435 	 * Accept connection on control socket
2436 	 */
2437 	memset(&addr, 0, sizeof(addr));
2438 	addrlen = sizeof(addr);
2439 	if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2440 	    &addrlen)) == -1) {
2441 		error_f("accept: %s", strerror(errno));
2442 		if (errno == EMFILE || errno == ENFILE)
2443 			c->notbefore = monotime() + 1;
2444 		return;
2445 	}
2446 
2447 	if (getpeereid(newsock, &euid, &egid) == -1) {
2448 		error_f("getpeereid failed: %s", strerror(errno));
2449 		close(newsock);
2450 		return;
2451 	}
2452 	if ((euid != 0) && (getuid() != euid)) {
2453 		error("multiplex uid mismatch: peer euid %u != uid %u",
2454 		    (u_int)euid, (u_int)getuid());
2455 		close(newsock);
2456 		return;
2457 	}
2458 	nc = channel_new(ssh, "mux-control", SSH_CHANNEL_MUX_CLIENT,
2459 	    newsock, newsock, -1, c->local_window_max,
2460 	    c->local_maxpacket, 0, "mux-control", 1);
2461 	nc->mux_rcb = c->mux_rcb;
2462 	debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2463 	/* establish state */
2464 	nc->mux_rcb(ssh, nc);
2465 	/* mux state transitions must not elicit protocol messages */
2466 	nc->flags |= CHAN_LOCAL;
2467 }
2468 
2469 static void
2470 channel_handler_init(struct ssh_channels *sc)
2471 {
2472 	chan_fn **pre, **post;
2473 
2474 	if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2475 	    (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2476 		fatal_f("allocation failed");
2477 
2478 	pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
2479 	pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
2480 	pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
2481 	pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
2482 	pre[SSH_CHANNEL_UNIX_LISTENER] =	&channel_pre_listener;
2483 	pre[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_pre_listener;
2484 	pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
2485 	pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
2486 	pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
2487 	pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
2488 	pre[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_pre_connecting;
2489 	pre[SSH_CHANNEL_MUX_LISTENER] =		&channel_pre_listener;
2490 	pre[SSH_CHANNEL_MUX_CLIENT] =		&channel_pre_mux_client;
2491 
2492 	post[SSH_CHANNEL_OPEN] =		&channel_post_open;
2493 	post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
2494 	post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
2495 	post[SSH_CHANNEL_UNIX_LISTENER] =	&channel_post_port_listener;
2496 	post[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_post_port_listener;
2497 	post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
2498 	post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
2499 	post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
2500 	post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
2501 	post[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_post_connecting;
2502 	post[SSH_CHANNEL_MUX_LISTENER] =	&channel_post_mux_listener;
2503 	post[SSH_CHANNEL_MUX_CLIENT] =		&channel_post_mux_client;
2504 
2505 	sc->channel_pre = pre;
2506 	sc->channel_post = post;
2507 }
2508 
2509 /* gc dead channels */
2510 static void
2511 channel_garbage_collect(struct ssh *ssh, Channel *c)
2512 {
2513 	if (c == NULL)
2514 		return;
2515 	if (c->detach_user != NULL) {
2516 		if (!chan_is_dead(ssh, c, c->detach_close))
2517 			return;
2518 
2519 		debug2("channel %d: gc: notify user", c->self);
2520 		c->detach_user(ssh, c->self, 0, NULL);
2521 		/* if we still have a callback */
2522 		if (c->detach_user != NULL)
2523 			return;
2524 		debug2("channel %d: gc: user detached", c->self);
2525 	}
2526 	if (!chan_is_dead(ssh, c, 1))
2527 		return;
2528 	debug2("channel %d: garbage collecting", c->self);
2529 	channel_free(ssh, c);
2530 }
2531 
2532 enum channel_table { CHAN_PRE, CHAN_POST };
2533 
2534 static void
2535 channel_handler(struct ssh *ssh, int table, struct timespec *timeout)
2536 {
2537 	struct ssh_channels *sc = ssh->chanctxt;
2538 	chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2539 	u_int i, oalloc;
2540 	Channel *c;
2541 	time_t now;
2542 
2543 	now = monotime();
2544 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2545 		c = sc->channels[i];
2546 		if (c == NULL)
2547 			continue;
2548 		/* Try to keep IO going while rekeying */
2549 		if (ssh_packet_is_rekeying(ssh) && c->type != SSH_CHANNEL_OPEN)
2550 			continue;
2551 		if (c->delayed) {
2552 			if (table == CHAN_PRE)
2553 				c->delayed = 0;
2554 			else
2555 				continue;
2556 		}
2557 		if (ftab[c->type] != NULL) {
2558 			if (table == CHAN_PRE &&
2559 			    c->type == SSH_CHANNEL_OPEN &&
2560 			    c->inactive_deadline != 0 && c->lastused != 0 &&
2561 			    now >= c->lastused + c->inactive_deadline) {
2562 				/* channel closed for inactivity */
2563 				verbose("channel %d: closing after %u seconds "
2564 				    "of inactivity", c->self,
2565 				    c->inactive_deadline);
2566 				channel_force_close(ssh, c, 1);
2567 			} else if (c->notbefore <= now) {
2568 				/* Run handlers that are not paused. */
2569 				(*ftab[c->type])(ssh, c);
2570 				/* inactivity timeouts must interrupt poll() */
2571 				if (timeout != NULL &&
2572 				    c->type == SSH_CHANNEL_OPEN &&
2573 				    c->lastused != 0 &&
2574 				    c->inactive_deadline != 0) {
2575 					ptimeout_deadline_monotime(timeout,
2576 					    c->lastused + c->inactive_deadline);
2577 				}
2578 			} else if (timeout != NULL) {
2579 				/*
2580 				 * Arrange for poll() wakeup when channel pause
2581 				 * timer expires.
2582 				 */
2583 				ptimeout_deadline_monotime(timeout,
2584 				    c->notbefore);
2585 			}
2586 		}
2587 		channel_garbage_collect(ssh, c);
2588 	}
2589 }
2590 
2591 /*
2592  * Create sockets before preparing IO.
2593  * This is necessary for things that need to happen after reading
2594  * the network-input but need to be completed before IO event setup, e.g.
2595  * because they may create new channels.
2596  */
2597 static void
2598 channel_before_prepare_io(struct ssh *ssh)
2599 {
2600 	struct ssh_channels *sc = ssh->chanctxt;
2601 	Channel *c;
2602 	u_int i, oalloc;
2603 
2604 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2605 		c = sc->channels[i];
2606 		if (c == NULL)
2607 			continue;
2608 		if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2609 			channel_before_prepare_io_rdynamic(ssh, c);
2610 	}
2611 }
2612 
2613 static void
2614 dump_channel_poll(const char *func, const char *what, Channel *c,
2615     u_int pollfd_offset, struct pollfd *pfd)
2616 {
2617 #ifdef DEBUG_CHANNEL_POLL
2618 	debug3("%s: channel %d: %s r%d w%d e%d s%d c->pfds [ %d %d %d %d ] "
2619 	    "io_want 0x%02x io_ready 0x%02x pfd[%u].fd=%d "
2620 	    "pfd.ev 0x%02x pfd.rev 0x%02x", func, c->self, what,
2621 	    c->rfd, c->wfd, c->efd, c->sock,
2622 	    c->pfds[0], c->pfds[1], c->pfds[2], c->pfds[3],
2623 	    c->io_want, c->io_ready,
2624 	    pollfd_offset, pfd->fd, pfd->events, pfd->revents);
2625 #endif
2626 }
2627 
2628 /* Prepare pollfd entries for a single channel */
2629 static void
2630 channel_prepare_pollfd(Channel *c, u_int *next_pollfd,
2631     struct pollfd *pfd, u_int npfd)
2632 {
2633 	u_int ev, p = *next_pollfd;
2634 
2635 	if (c == NULL)
2636 		return;
2637 	if (p + 4 > npfd) {
2638 		/* Shouldn't happen */
2639 		fatal_f("channel %d: bad pfd offset %u (max %u)",
2640 		    c->self, p, npfd);
2641 	}
2642 	c->pfds[0] = c->pfds[1] = c->pfds[2] = c->pfds[3] = -1;
2643 	/*
2644 	 * prepare c->rfd
2645 	 *
2646 	 * This is a special case, since c->rfd might be the same as
2647 	 * c->wfd, c->efd and/or c->sock. Handle those here if they want
2648 	 * IO too.
2649 	 */
2650 	if (c->rfd != -1) {
2651 		ev = 0;
2652 		if ((c->io_want & SSH_CHAN_IO_RFD) != 0)
2653 			ev |= POLLIN;
2654 		/* rfd == wfd */
2655 		if (c->wfd == c->rfd) {
2656 			if ((c->io_want & SSH_CHAN_IO_WFD) != 0)
2657 				ev |= POLLOUT;
2658 		}
2659 		/* rfd == efd */
2660 		if (c->efd == c->rfd) {
2661 			if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2662 				ev |= POLLIN;
2663 			if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2664 				ev |= POLLOUT;
2665 		}
2666 		/* rfd == sock */
2667 		if (c->sock == c->rfd) {
2668 			if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2669 				ev |= POLLIN;
2670 			if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2671 				ev |= POLLOUT;
2672 		}
2673 		/* Pack a pfd entry if any event armed for this fd */
2674 		if (ev != 0) {
2675 			c->pfds[0] = p;
2676 			pfd[p].fd = c->rfd;
2677 			pfd[p].events = ev;
2678 			dump_channel_poll(__func__, "rfd", c, p, &pfd[p]);
2679 			p++;
2680 		}
2681 	}
2682 	/* prepare c->wfd if wanting IO and not already handled above */
2683 	if (c->wfd != -1 && c->rfd != c->wfd) {
2684 		ev = 0;
2685 		if ((c->io_want & SSH_CHAN_IO_WFD))
2686 			ev |= POLLOUT;
2687 		/* Pack a pfd entry if any event armed for this fd */
2688 		if (ev != 0) {
2689 			c->pfds[1] = p;
2690 			pfd[p].fd = c->wfd;
2691 			pfd[p].events = ev;
2692 			dump_channel_poll(__func__, "wfd", c, p, &pfd[p]);
2693 			p++;
2694 		}
2695 	}
2696 	/* prepare c->efd if wanting IO and not already handled above */
2697 	if (c->efd != -1 && c->rfd != c->efd) {
2698 		ev = 0;
2699 		if ((c->io_want & SSH_CHAN_IO_EFD_R) != 0)
2700 			ev |= POLLIN;
2701 		if ((c->io_want & SSH_CHAN_IO_EFD_W) != 0)
2702 			ev |= POLLOUT;
2703 		/* Pack a pfd entry if any event armed for this fd */
2704 		if (ev != 0) {
2705 			c->pfds[2] = p;
2706 			pfd[p].fd = c->efd;
2707 			pfd[p].events = ev;
2708 			dump_channel_poll(__func__, "efd", c, p, &pfd[p]);
2709 			p++;
2710 		}
2711 	}
2712 	/* prepare c->sock if wanting IO and not already handled above */
2713 	if (c->sock != -1 && c->rfd != c->sock) {
2714 		ev = 0;
2715 		if ((c->io_want & SSH_CHAN_IO_SOCK_R) != 0)
2716 			ev |= POLLIN;
2717 		if ((c->io_want & SSH_CHAN_IO_SOCK_W) != 0)
2718 			ev |= POLLOUT;
2719 		/* Pack a pfd entry if any event armed for this fd */
2720 		if (ev != 0) {
2721 			c->pfds[3] = p;
2722 			pfd[p].fd = c->sock;
2723 			pfd[p].events = 0;
2724 			dump_channel_poll(__func__, "sock", c, p, &pfd[p]);
2725 			p++;
2726 		}
2727 	}
2728 	*next_pollfd = p;
2729 }
2730 
2731 /* * Allocate/prepare poll structure */
2732 void
2733 channel_prepare_poll(struct ssh *ssh, struct pollfd **pfdp, u_int *npfd_allocp,
2734     u_int *npfd_activep, u_int npfd_reserved, struct timespec *timeout)
2735 {
2736 	struct ssh_channels *sc = ssh->chanctxt;
2737 	u_int i, oalloc, p, npfd = npfd_reserved;
2738 
2739 	channel_before_prepare_io(ssh); /* might create a new channel */
2740 	/* clear out I/O flags from last poll */
2741 	for (i = 0; i < sc->channels_alloc; i++) {
2742 		if (sc->channels[i] == NULL)
2743 			continue;
2744 		sc->channels[i]->io_want = sc->channels[i]->io_ready = 0;
2745 	}
2746 	/* Allocate 4x pollfd for each channel (rfd, wfd, efd, sock) */
2747 	if (sc->channels_alloc >= (INT_MAX / 4) - npfd_reserved)
2748 		fatal_f("too many channels"); /* shouldn't happen */
2749 	npfd += sc->channels_alloc * 4;
2750 	if (npfd > *npfd_allocp) {
2751 		*pfdp = xrecallocarray(*pfdp, *npfd_allocp,
2752 		    npfd, sizeof(**pfdp));
2753 		*npfd_allocp = npfd;
2754 	}
2755 	*npfd_activep = npfd_reserved;
2756 	oalloc = sc->channels_alloc;
2757 
2758 	channel_handler(ssh, CHAN_PRE, timeout);
2759 
2760 	if (oalloc != sc->channels_alloc) {
2761 		/* shouldn't happen */
2762 		fatal_f("channels_alloc changed during CHAN_PRE "
2763 		    "(was %u, now %u)", oalloc, sc->channels_alloc);
2764 	}
2765 
2766 	/* Prepare pollfd */
2767 	p = npfd_reserved;
2768 	for (i = 0; i < sc->channels_alloc; i++)
2769 		channel_prepare_pollfd(sc->channels[i], &p, *pfdp, npfd);
2770 	*npfd_activep = p;
2771 }
2772 
2773 static void
2774 fd_ready(Channel *c, int p, struct pollfd *pfds, u_int npfd, int fd,
2775     const char *what, u_int revents_mask, u_int ready)
2776 {
2777 	struct pollfd *pfd = &pfds[p];
2778 
2779 	if (fd == -1)
2780 		return;
2781 	if (p == -1 || (u_int)p >= npfd)
2782 		fatal_f("channel %d: bad pfd %d (max %u)", c->self, p, npfd);
2783 	dump_channel_poll(__func__, what, c, p, pfd);
2784 	if (pfd->fd != fd) {
2785 		fatal("channel %d: inconsistent %s fd=%d pollfd[%u].fd %d "
2786 		    "r%d w%d e%d s%d", c->self, what, fd, p, pfd->fd,
2787 		    c->rfd, c->wfd, c->efd, c->sock);
2788 	}
2789 	if ((pfd->revents & POLLNVAL) != 0) {
2790 		fatal("channel %d: invalid %s pollfd[%u].fd %d r%d w%d e%d s%d",
2791 		    c->self, what, p, pfd->fd, c->rfd, c->wfd, c->efd, c->sock);
2792 	}
2793 	if ((pfd->revents & (revents_mask|POLLHUP|POLLERR)) != 0)
2794 		c->io_ready |= ready & c->io_want;
2795 }
2796 
2797 /*
2798  * After poll, perform any appropriate operations for channels which have
2799  * events pending.
2800  */
2801 void
2802 channel_after_poll(struct ssh *ssh, struct pollfd *pfd, u_int npfd)
2803 {
2804 	struct ssh_channels *sc = ssh->chanctxt;
2805 	u_int i;
2806 	int p;
2807 	Channel *c;
2808 
2809 #ifdef DEBUG_CHANNEL_POLL
2810 	for (p = 0; p < (int)npfd; p++) {
2811 		if (pfd[p].revents == 0)
2812 			continue;
2813 		debug_f("pfd[%u].fd %d rev 0x%04x",
2814 		    p, pfd[p].fd, pfd[p].revents);
2815 	}
2816 #endif
2817 
2818 	/* Convert pollfd into c->io_ready */
2819 	for (i = 0; i < sc->channels_alloc; i++) {
2820 		c = sc->channels[i];
2821 		if (c == NULL)
2822 			continue;
2823 		/* if rfd is shared with efd/sock then wfd should be too */
2824 		if (c->rfd != -1 && c->wfd != -1 && c->rfd != c->wfd &&
2825 		    (c->rfd == c->efd || c->rfd == c->sock)) {
2826 			/* Shouldn't happen */
2827 			fatal_f("channel %d: unexpected fds r%d w%d e%d s%d",
2828 			    c->self, c->rfd, c->wfd, c->efd, c->sock);
2829 		}
2830 		c->io_ready = 0;
2831 		/* rfd, potentially shared with wfd, efd and sock */
2832 		if (c->rfd != -1 && (p = c->pfds[0]) != -1) {
2833 			fd_ready(c, p, pfd, npfd, c->rfd,
2834 			    "rfd", POLLIN, SSH_CHAN_IO_RFD);
2835 			if (c->rfd == c->wfd) {
2836 				fd_ready(c, p, pfd, npfd, c->wfd,
2837 				    "wfd/r", POLLOUT, SSH_CHAN_IO_WFD);
2838 			}
2839 			if (c->rfd == c->efd) {
2840 				fd_ready(c, p, pfd, npfd, c->efd,
2841 				    "efdr/r", POLLIN, SSH_CHAN_IO_EFD_R);
2842 				fd_ready(c, p, pfd, npfd, c->efd,
2843 				    "efdw/r", POLLOUT, SSH_CHAN_IO_EFD_W);
2844 			}
2845 			if (c->rfd == c->sock) {
2846 				fd_ready(c, p, pfd, npfd, c->sock,
2847 				    "sockr/r", POLLIN, SSH_CHAN_IO_SOCK_R);
2848 				fd_ready(c, p, pfd, npfd, c->sock,
2849 				    "sockw/r", POLLOUT, SSH_CHAN_IO_SOCK_W);
2850 			}
2851 			dump_channel_poll(__func__, "rfd", c, p, pfd);
2852 		}
2853 		/* wfd */
2854 		if (c->wfd != -1 && c->wfd != c->rfd &&
2855 		    (p = c->pfds[1]) != -1) {
2856 			fd_ready(c, p, pfd, npfd, c->wfd,
2857 			    "wfd", POLLOUT, SSH_CHAN_IO_WFD);
2858 			dump_channel_poll(__func__, "wfd", c, p, pfd);
2859 		}
2860 		/* efd */
2861 		if (c->efd != -1 && c->efd != c->rfd &&
2862 		    (p = c->pfds[2]) != -1) {
2863 			fd_ready(c, p, pfd, npfd, c->efd,
2864 			    "efdr", POLLIN, SSH_CHAN_IO_EFD_R);
2865 			fd_ready(c, p, pfd, npfd, c->efd,
2866 			    "efdw", POLLOUT, SSH_CHAN_IO_EFD_W);
2867 			dump_channel_poll(__func__, "efd", c, p, pfd);
2868 		}
2869 		/* sock */
2870 		if (c->sock != -1 && c->sock != c->rfd &&
2871 		    (p = c->pfds[3]) != -1) {
2872 			fd_ready(c, p, pfd, npfd, c->sock,
2873 			    "sockr", POLLIN, SSH_CHAN_IO_SOCK_R);
2874 			fd_ready(c, p, pfd, npfd, c->sock,
2875 			    "sockw", POLLOUT, SSH_CHAN_IO_SOCK_W);
2876 			dump_channel_poll(__func__, "sock", c, p, pfd);
2877 		}
2878 	}
2879 	channel_handler(ssh, CHAN_POST, NULL);
2880 }
2881 
2882 /*
2883  * Enqueue data for channels with open or draining c->input.
2884  */
2885 static void
2886 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2887 {
2888 	size_t len, plen;
2889 	const u_char *pkt;
2890 	int r;
2891 
2892 	if ((len = sshbuf_len(c->input)) == 0) {
2893 		if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2894 			/*
2895 			 * input-buffer is empty and read-socket shutdown:
2896 			 * tell peer, that we will not send more data:
2897 			 * send IEOF.
2898 			 * hack for extended data: delay EOF if EFD still
2899 			 * in use.
2900 			 */
2901 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
2902 				debug2("channel %d: "
2903 				    "ibuf_empty delayed efd %d/(%zu)",
2904 				    c->self, c->efd, sshbuf_len(c->extended));
2905 			else
2906 				chan_ibuf_empty(ssh, c);
2907 		}
2908 		return;
2909 	}
2910 
2911 	if (!c->have_remote_id)
2912 		fatal_f("channel %d: no remote id", c->self);
2913 
2914 	if (c->datagram) {
2915 		/* Check datagram will fit; drop if not */
2916 		if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2917 			fatal_fr(r, "channel %i: get datagram", c->self);
2918 		/*
2919 		 * XXX this does tail-drop on the datagram queue which is
2920 		 * usually suboptimal compared to head-drop. Better to have
2921 		 * backpressure at read time? (i.e. read + discard)
2922 		 */
2923 		if (plen > c->remote_window || plen > c->remote_maxpacket) {
2924 			debug("channel %d: datagram too big", c->self);
2925 			return;
2926 		}
2927 		/* Enqueue it */
2928 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2929 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2930 		    (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2931 		    (r = sshpkt_send(ssh)) != 0)
2932 			fatal_fr(r, "channel %i: send datagram", c->self);
2933 		c->remote_window -= plen;
2934 		return;
2935 	}
2936 
2937 	/* Enqueue packet for buffered data. */
2938 	if (len > c->remote_window)
2939 		len = c->remote_window;
2940 	if (len > c->remote_maxpacket)
2941 		len = c->remote_maxpacket;
2942 	if (len == 0)
2943 		return;
2944 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2945 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2946 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2947 	    (r = sshpkt_send(ssh)) != 0)
2948 		fatal_fr(r, "channel %i: send data", c->self);
2949 	if ((r = sshbuf_consume(c->input, len)) != 0)
2950 		fatal_fr(r, "channel %i: consume", c->self);
2951 	c->remote_window -= len;
2952 }
2953 
2954 /*
2955  * Enqueue data for channels with open c->extended in read mode.
2956  */
2957 static void
2958 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2959 {
2960 	size_t len;
2961 	int r;
2962 
2963 	if ((len = sshbuf_len(c->extended)) == 0)
2964 		return;
2965 
2966 	debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2967 	    c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2968 	if (len > c->remote_window)
2969 		len = c->remote_window;
2970 	if (len > c->remote_maxpacket)
2971 		len = c->remote_maxpacket;
2972 	if (len == 0)
2973 		return;
2974 	if (!c->have_remote_id)
2975 		fatal_f("channel %d: no remote id", c->self);
2976 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2977 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2978 	    (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2979 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2980 	    (r = sshpkt_send(ssh)) != 0)
2981 		fatal_fr(r, "channel %i: data", c->self);
2982 	if ((r = sshbuf_consume(c->extended, len)) != 0)
2983 		fatal_fr(r, "channel %i: consume", c->self);
2984 	c->remote_window -= len;
2985 	debug2("channel %d: sent ext data %zu", c->self, len);
2986 }
2987 
2988 /* If there is data to send to the connection, enqueue some of it now. */
2989 void
2990 channel_output_poll(struct ssh *ssh)
2991 {
2992 	struct ssh_channels *sc = ssh->chanctxt;
2993 	Channel *c;
2994 	u_int i;
2995 
2996 	for (i = 0; i < sc->channels_alloc; i++) {
2997 		c = sc->channels[i];
2998 		if (c == NULL)
2999 			continue;
3000 
3001 		/*
3002 		 * We are only interested in channels that can have buffered
3003 		 * incoming data.
3004 		 */
3005 		if (c->type != SSH_CHANNEL_OPEN)
3006 			continue;
3007 		if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
3008 			/* XXX is this true? */
3009 			debug3("channel %d: will not send data after close",
3010 			    c->self);
3011 			continue;
3012 		}
3013 
3014 		/* Get the amount of buffered data for this channel. */
3015 		if (c->istate == CHAN_INPUT_OPEN ||
3016 		    c->istate == CHAN_INPUT_WAIT_DRAIN)
3017 			channel_output_poll_input_open(ssh, c);
3018 		/* Send extended data, i.e. stderr */
3019 		if (!(c->flags & CHAN_EOF_SENT) &&
3020 		    c->extended_usage == CHAN_EXTENDED_READ)
3021 			channel_output_poll_extended_read(ssh, c);
3022 	}
3023 }
3024 
3025 /* -- mux proxy support  */
3026 
3027 /*
3028  * When multiplexing channel messages for mux clients we have to deal
3029  * with downstream messages from the mux client and upstream messages
3030  * from the ssh server:
3031  * 1) Handling downstream messages is straightforward and happens
3032  *    in channel_proxy_downstream():
3033  *    - We forward all messages (mostly) unmodified to the server.
3034  *    - However, in order to route messages from upstream to the correct
3035  *      downstream client, we have to replace the channel IDs used by the
3036  *      mux clients with a unique channel ID because the mux clients might
3037  *      use conflicting channel IDs.
3038  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
3039  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
3040  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
3041  *      with the newly allocated channel ID.
3042  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
3043  *    channels and processed by channel_proxy_upstream(). The local channel ID
3044  *    is then translated back to the original mux client ID.
3045  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
3046  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
3047  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
3048  *    downstream mux client are removed.
3049  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
3050  *    requires more work, because they are not addressed to a specific
3051  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
3052  *    out whether the request is addressed to the local client or a
3053  *    specific downstream client based on the listen-address/port.
3054  * 6) Agent and X11-Forwarding have a similar problem and are currently
3055  *    not supported as the matching session/channel cannot be identified
3056  *    easily.
3057  */
3058 
3059 /*
3060  * receive packets from downstream mux clients:
3061  * channel callback fired on read from mux client, creates
3062  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
3063  * on channel creation.
3064  */
3065 int
3066 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
3067 {
3068 	Channel *c = NULL;
3069 	struct sshbuf *original = NULL, *modified = NULL;
3070 	const u_char *cp;
3071 	char *ctype = NULL, *listen_host = NULL;
3072 	u_char type;
3073 	size_t have;
3074 	int ret = -1, r;
3075 	u_int id, remote_id, listen_port;
3076 
3077 	/* sshbuf_dump(downstream->input, stderr); */
3078 	if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
3079 	    != 0) {
3080 		error_fr(r, "parse");
3081 		return -1;
3082 	}
3083 	if (have < 2) {
3084 		error_f("short message");
3085 		return -1;
3086 	}
3087 	type = cp[1];
3088 	/* skip padlen + type */
3089 	cp += 2;
3090 	have -= 2;
3091 	if (ssh_packet_log_type(type))
3092 		debug3_f("channel %u: down->up: type %u",
3093 		    downstream->self, type);
3094 
3095 	switch (type) {
3096 	case SSH2_MSG_CHANNEL_OPEN:
3097 		if ((original = sshbuf_from(cp, have)) == NULL ||
3098 		    (modified = sshbuf_new()) == NULL) {
3099 			error_f("alloc");
3100 			goto out;
3101 		}
3102 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
3103 		    (r = sshbuf_get_u32(original, &id)) != 0) {
3104 			error_fr(r, "parse");
3105 			goto out;
3106 		}
3107 		c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3108 		    -1, -1, -1, 0, 0, 0, ctype, 1);
3109 		c->mux_ctx = downstream;	/* point to mux client */
3110 		c->mux_downstream_id = id;	/* original downstream id */
3111 		if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
3112 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3113 		    (r = sshbuf_putb(modified, original)) != 0) {
3114 			error_fr(r, "compose");
3115 			channel_free(ssh, c);
3116 			goto out;
3117 		}
3118 		break;
3119 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3120 		/*
3121 		 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
3122 		 * need to parse 'remote_id' instead of 'ctype'.
3123 		 */
3124 		if ((original = sshbuf_from(cp, have)) == NULL ||
3125 		    (modified = sshbuf_new()) == NULL) {
3126 			error_f("alloc");
3127 			goto out;
3128 		}
3129 		if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
3130 		    (r = sshbuf_get_u32(original, &id)) != 0) {
3131 			error_fr(r, "parse");
3132 			goto out;
3133 		}
3134 		c = channel_new(ssh, "mux-proxy", SSH_CHANNEL_MUX_PROXY,
3135 		    -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
3136 		c->mux_ctx = downstream;	/* point to mux client */
3137 		c->mux_downstream_id = id;
3138 		c->remote_id = remote_id;
3139 		c->have_remote_id = 1;
3140 		if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
3141 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
3142 		    (r = sshbuf_putb(modified, original)) != 0) {
3143 			error_fr(r, "compose");
3144 			channel_free(ssh, c);
3145 			goto out;
3146 		}
3147 		break;
3148 	case SSH2_MSG_GLOBAL_REQUEST:
3149 		if ((original = sshbuf_from(cp, have)) == NULL) {
3150 			error_f("alloc");
3151 			goto out;
3152 		}
3153 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
3154 			error_fr(r, "parse");
3155 			goto out;
3156 		}
3157 		if (strcmp(ctype, "tcpip-forward") != 0) {
3158 			error_f("unsupported request %s", ctype);
3159 			goto out;
3160 		}
3161 		if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
3162 		    (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
3163 		    (r = sshbuf_get_u32(original, &listen_port)) != 0) {
3164 			error_fr(r, "parse");
3165 			goto out;
3166 		}
3167 		if (listen_port > 65535) {
3168 			error_f("tcpip-forward for %s: bad port %u",
3169 			    listen_host, listen_port);
3170 			goto out;
3171 		}
3172 		/* Record that connection to this host/port is permitted. */
3173 		permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
3174 		    listen_host, NULL, (int)listen_port, downstream);
3175 		listen_host = NULL;
3176 		break;
3177 	case SSH2_MSG_CHANNEL_CLOSE:
3178 		if (have < 4)
3179 			break;
3180 		remote_id = PEEK_U32(cp);
3181 		if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
3182 			if (c->flags & CHAN_CLOSE_RCVD)
3183 				channel_free(ssh, c);
3184 			else
3185 				c->flags |= CHAN_CLOSE_SENT;
3186 		}
3187 		break;
3188 	}
3189 	if (modified) {
3190 		if ((r = sshpkt_start(ssh, type)) != 0 ||
3191 		    (r = sshpkt_putb(ssh, modified)) != 0 ||
3192 		    (r = sshpkt_send(ssh)) != 0) {
3193 			error_fr(r, "send");
3194 			goto out;
3195 		}
3196 	} else {
3197 		if ((r = sshpkt_start(ssh, type)) != 0 ||
3198 		    (r = sshpkt_put(ssh, cp, have)) != 0 ||
3199 		    (r = sshpkt_send(ssh)) != 0) {
3200 			error_fr(r, "send");
3201 			goto out;
3202 		}
3203 	}
3204 	ret = 0;
3205  out:
3206 	free(ctype);
3207 	free(listen_host);
3208 	sshbuf_free(original);
3209 	sshbuf_free(modified);
3210 	return ret;
3211 }
3212 
3213 /*
3214  * receive packets from upstream server and de-multiplex packets
3215  * to correct downstream:
3216  * implemented as a helper for channel input handlers,
3217  * replaces local (proxy) channel ID with downstream channel ID.
3218  */
3219 int
3220 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
3221 {
3222 	struct sshbuf *b = NULL;
3223 	Channel *downstream;
3224 	const u_char *cp = NULL;
3225 	size_t len;
3226 	int r;
3227 
3228 	/*
3229 	 * When receiving packets from the peer we need to check whether we
3230 	 * need to forward the packets to the mux client. In this case we
3231 	 * restore the original channel id and keep track of CLOSE messages,
3232 	 * so we can cleanup the channel.
3233 	 */
3234 	if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
3235 		return 0;
3236 	if ((downstream = c->mux_ctx) == NULL)
3237 		return 0;
3238 	switch (type) {
3239 	case SSH2_MSG_CHANNEL_CLOSE:
3240 	case SSH2_MSG_CHANNEL_DATA:
3241 	case SSH2_MSG_CHANNEL_EOF:
3242 	case SSH2_MSG_CHANNEL_EXTENDED_DATA:
3243 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3244 	case SSH2_MSG_CHANNEL_OPEN_FAILURE:
3245 	case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
3246 	case SSH2_MSG_CHANNEL_SUCCESS:
3247 	case SSH2_MSG_CHANNEL_FAILURE:
3248 	case SSH2_MSG_CHANNEL_REQUEST:
3249 		break;
3250 	default:
3251 		debug2_f("channel %u: unsupported type %u", c->self, type);
3252 		return 0;
3253 	}
3254 	if ((b = sshbuf_new()) == NULL) {
3255 		error_f("alloc reply");
3256 		goto out;
3257 	}
3258 	/* get remaining payload (after id) */
3259 	cp = sshpkt_ptr(ssh, &len);
3260 	if (cp == NULL) {
3261 		error_f("no packet");
3262 		goto out;
3263 	}
3264 	/* translate id and send to muxclient */
3265 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* padlen */
3266 	    (r = sshbuf_put_u8(b, type)) != 0 ||
3267 	    (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
3268 	    (r = sshbuf_put(b, cp, len)) != 0 ||
3269 	    (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
3270 		error_fr(r, "compose muxclient");
3271 		goto out;
3272 	}
3273 	/* sshbuf_dump(b, stderr); */
3274 	if (ssh_packet_log_type(type))
3275 		debug3_f("channel %u: up->down: type %u", c->self, type);
3276  out:
3277 	/* update state */
3278 	switch (type) {
3279 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
3280 		/* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
3281 		if (cp && len > 4) {
3282 			c->remote_id = PEEK_U32(cp);
3283 			c->have_remote_id = 1;
3284 		}
3285 		break;
3286 	case SSH2_MSG_CHANNEL_CLOSE:
3287 		if (c->flags & CHAN_CLOSE_SENT)
3288 			channel_free(ssh, c);
3289 		else
3290 			c->flags |= CHAN_CLOSE_RCVD;
3291 		break;
3292 	}
3293 	sshbuf_free(b);
3294 	return 1;
3295 }
3296 
3297 /* -- protocol input */
3298 
3299 /* Parse a channel ID from the current packet */
3300 static int
3301 channel_parse_id(struct ssh *ssh, const char *where, const char *what)
3302 {
3303 	u_int32_t id;
3304 	int r;
3305 
3306 	if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
3307 		error_r(r, "%s: parse id", where);
3308 		ssh_packet_disconnect(ssh, "Invalid %s message", what);
3309 	}
3310 	if (id > INT_MAX) {
3311 		error_r(r, "%s: bad channel id %u", where, id);
3312 		ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
3313 	}
3314 	return (int)id;
3315 }
3316 
3317 /* Lookup a channel from an ID in the current packet */
3318 static Channel *
3319 channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
3320 {
3321 	int id = channel_parse_id(ssh, where, what);
3322 	Channel *c;
3323 
3324 	if ((c = channel_lookup(ssh, id)) == NULL) {
3325 		ssh_packet_disconnect(ssh,
3326 		    "%s packet referred to nonexistent channel %d", what, id);
3327 	}
3328 	return c;
3329 }
3330 
3331 int
3332 channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
3333 {
3334 	const u_char *data;
3335 	size_t data_len, win_len;
3336 	Channel *c = channel_from_packet_id(ssh, __func__, "data");
3337 	int r;
3338 
3339 	if (channel_proxy_upstream(c, type, seq, ssh))
3340 		return 0;
3341 
3342 	/* Ignore any data for non-open channels (might happen on close) */
3343 	if (c->type != SSH_CHANNEL_OPEN &&
3344 	    c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
3345 	    c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
3346 	    c->type != SSH_CHANNEL_X11_OPEN)
3347 		return 0;
3348 
3349 	/* Get the data. */
3350 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3351             (r = sshpkt_get_end(ssh)) != 0)
3352 		fatal_fr(r, "channel %i: get data", c->self);
3353 
3354 	win_len = data_len;
3355 	if (c->datagram)
3356 		win_len += 4;  /* string length header */
3357 
3358 	/*
3359 	 * The sending side reduces its window as it sends data, so we
3360 	 * must 'fake' consumption of the data in order to ensure that window
3361 	 * updates are sent back. Otherwise the connection might deadlock.
3362 	 */
3363 	if (c->ostate != CHAN_OUTPUT_OPEN) {
3364 		c->local_window -= win_len;
3365 		c->local_consumed += win_len;
3366 		return 0;
3367 	}
3368 
3369 	if (win_len > c->local_maxpacket) {
3370 		logit("channel %d: rcvd big packet %zu, maxpack %u",
3371 		    c->self, win_len, c->local_maxpacket);
3372 		return 0;
3373 	}
3374 	if (win_len > c->local_window) {
3375 		logit("channel %d: rcvd too much data %zu, win %u",
3376 		    c->self, win_len, c->local_window);
3377 		return 0;
3378 	}
3379 	c->local_window -= win_len;
3380 
3381 	if (c->datagram) {
3382 		if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
3383 			fatal_fr(r, "channel %i: append datagram", c->self);
3384 	} else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
3385 		fatal_fr(r, "channel %i: append data", c->self);
3386 
3387 	return 0;
3388 }
3389 
3390 int
3391 channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
3392 {
3393 	const u_char *data;
3394 	size_t data_len;
3395 	u_int32_t tcode;
3396 	Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
3397 	int r;
3398 
3399 	if (channel_proxy_upstream(c, type, seq, ssh))
3400 		return 0;
3401 	if (c->type != SSH_CHANNEL_OPEN) {
3402 		logit("channel %d: ext data for non open", c->self);
3403 		return 0;
3404 	}
3405 	if (c->flags & CHAN_EOF_RCVD) {
3406 		if (ssh->compat & SSH_BUG_EXTEOF)
3407 			debug("channel %d: accepting ext data after eof",
3408 			    c->self);
3409 		else
3410 			ssh_packet_disconnect(ssh, "Received extended_data "
3411 			    "after EOF on channel %d.", c->self);
3412 	}
3413 
3414 	if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
3415 		error_fr(r, "parse tcode");
3416 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
3417 	}
3418 	if (c->efd == -1 ||
3419 	    c->extended_usage != CHAN_EXTENDED_WRITE ||
3420 	    tcode != SSH2_EXTENDED_DATA_STDERR) {
3421 		logit("channel %d: bad ext data", c->self);
3422 		return 0;
3423 	}
3424 	if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
3425             (r = sshpkt_get_end(ssh)) != 0) {
3426 		error_fr(r, "parse data");
3427 		ssh_packet_disconnect(ssh, "Invalid extended_data message");
3428 	}
3429 
3430 	if (data_len > c->local_window) {
3431 		logit("channel %d: rcvd too much extended_data %zu, win %u",
3432 		    c->self, data_len, c->local_window);
3433 		return 0;
3434 	}
3435 	debug2("channel %d: rcvd ext data %zu", c->self, data_len);
3436 	/* XXX sshpkt_getb? */
3437 	if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
3438 		error_fr(r, "append");
3439 	c->local_window -= data_len;
3440 	return 0;
3441 }
3442 
3443 int
3444 channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
3445 {
3446 	Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
3447 	int r;
3448 
3449         if ((r = sshpkt_get_end(ssh)) != 0) {
3450 		error_fr(r, "parse data");
3451 		ssh_packet_disconnect(ssh, "Invalid ieof message");
3452 	}
3453 
3454 	if (channel_proxy_upstream(c, type, seq, ssh))
3455 		return 0;
3456 	chan_rcvd_ieof(ssh, c);
3457 
3458 	/* XXX force input close */
3459 	if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
3460 		debug("channel %d: FORCE input drain", c->self);
3461 		c->istate = CHAN_INPUT_WAIT_DRAIN;
3462 		if (sshbuf_len(c->input) == 0)
3463 			chan_ibuf_empty(ssh, c);
3464 	}
3465 	return 0;
3466 }
3467 
3468 int
3469 channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
3470 {
3471 	Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
3472 	int r;
3473 
3474 	if (channel_proxy_upstream(c, type, seq, ssh))
3475 		return 0;
3476         if ((r = sshpkt_get_end(ssh)) != 0) {
3477 		error_fr(r, "parse data");
3478 		ssh_packet_disconnect(ssh, "Invalid oclose message");
3479 	}
3480 	chan_rcvd_oclose(ssh, c);
3481 	return 0;
3482 }
3483 
3484 int
3485 channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
3486 {
3487 	Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
3488 	u_int32_t remote_window, remote_maxpacket;
3489 	int r;
3490 
3491 	if (channel_proxy_upstream(c, type, seq, ssh))
3492 		return 0;
3493 	if (c->type != SSH_CHANNEL_OPENING)
3494 		ssh_packet_disconnect(ssh, "Received open confirmation for "
3495 		    "non-opening channel %d.", c->self);
3496 	/*
3497 	 * Record the remote channel number and mark that the channel
3498 	 * is now open.
3499 	 */
3500 	if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
3501 	    (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
3502 	    (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
3503             (r = sshpkt_get_end(ssh)) != 0) {
3504 		error_fr(r, "window/maxpacket");
3505 		ssh_packet_disconnect(ssh, "Invalid open confirmation message");
3506 	}
3507 
3508 	c->have_remote_id = 1;
3509 	c->remote_window = remote_window;
3510 	c->remote_maxpacket = remote_maxpacket;
3511 	c->type = SSH_CHANNEL_OPEN;
3512 	if (c->open_confirm) {
3513 		debug2_f("channel %d: callback start", c->self);
3514 		c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
3515 		debug2_f("channel %d: callback done", c->self);
3516 	}
3517 	c->lastused = monotime();
3518 	debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
3519 	    c->remote_window, c->remote_maxpacket);
3520 	return 0;
3521 }
3522 
3523 static char *
3524 reason2txt(int reason)
3525 {
3526 	switch (reason) {
3527 	case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
3528 		return "administratively prohibited";
3529 	case SSH2_OPEN_CONNECT_FAILED:
3530 		return "connect failed";
3531 	case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
3532 		return "unknown channel type";
3533 	case SSH2_OPEN_RESOURCE_SHORTAGE:
3534 		return "resource shortage";
3535 	}
3536 	return "unknown reason";
3537 }
3538 
3539 int
3540 channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
3541 {
3542 	Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
3543 	u_int32_t reason;
3544 	char *msg = NULL;
3545 	int r;
3546 
3547 	if (channel_proxy_upstream(c, type, seq, ssh))
3548 		return 0;
3549 	if (c->type != SSH_CHANNEL_OPENING)
3550 		ssh_packet_disconnect(ssh, "Received open failure for "
3551 		    "non-opening channel %d.", c->self);
3552 	if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
3553 		error_fr(r, "parse reason");
3554 		ssh_packet_disconnect(ssh, "Invalid open failure message");
3555 	}
3556 	/* skip language */
3557 	if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
3558 	    (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
3559             (r = sshpkt_get_end(ssh)) != 0) {
3560 		error_fr(r, "parse msg/lang");
3561 		ssh_packet_disconnect(ssh, "Invalid open failure message");
3562 	}
3563 	logit("channel %d: open failed: %s%s%s", c->self,
3564 	    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
3565 	free(msg);
3566 	if (c->open_confirm) {
3567 		debug2_f("channel %d: callback start", c->self);
3568 		c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
3569 		debug2_f("channel %d: callback done", c->self);
3570 	}
3571 	/* Schedule the channel for cleanup/deletion. */
3572 	chan_mark_dead(ssh, c);
3573 	return 0;
3574 }
3575 
3576 int
3577 channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
3578 {
3579 	int id = channel_parse_id(ssh, __func__, "window adjust");
3580 	Channel *c;
3581 	u_int32_t adjust;
3582 	u_int new_rwin;
3583 	int r;
3584 
3585 	if ((c = channel_lookup(ssh, id)) == NULL) {
3586 		logit("Received window adjust for non-open channel %d.", id);
3587 		return 0;
3588 	}
3589 
3590 	if (channel_proxy_upstream(c, type, seq, ssh))
3591 		return 0;
3592 	if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
3593             (r = sshpkt_get_end(ssh)) != 0) {
3594 		error_fr(r, "parse adjust");
3595 		ssh_packet_disconnect(ssh, "Invalid window adjust message");
3596 	}
3597 	debug2("channel %d: rcvd adjust %u", c->self, adjust);
3598 	if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
3599 		fatal("channel %d: adjust %u overflows remote window %u",
3600 		    c->self, adjust, c->remote_window);
3601 	}
3602 	c->remote_window = new_rwin;
3603 	return 0;
3604 }
3605 
3606 int
3607 channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
3608 {
3609 	int id = channel_parse_id(ssh, __func__, "status confirm");
3610 	Channel *c;
3611 	struct channel_confirm *cc;
3612 
3613 	/* Reset keepalive timeout */
3614 	ssh_packet_set_alive_timeouts(ssh, 0);
3615 
3616 	debug2_f("type %d id %d", type, id);
3617 
3618 	if ((c = channel_lookup(ssh, id)) == NULL) {
3619 		logit_f("%d: unknown", id);
3620 		return 0;
3621 	}
3622 	if (channel_proxy_upstream(c, type, seq, ssh))
3623 		return 0;
3624         if (sshpkt_get_end(ssh) != 0)
3625 		ssh_packet_disconnect(ssh, "Invalid status confirm message");
3626 	if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
3627 		return 0;
3628 	cc->cb(ssh, type, c, cc->ctx);
3629 	TAILQ_REMOVE(&c->status_confirms, cc, entry);
3630 	freezero(cc, sizeof(*cc));
3631 	return 0;
3632 }
3633 
3634 /* -- tcp forwarding */
3635 
3636 void
3637 channel_set_af(struct ssh *ssh, int af)
3638 {
3639 	ssh->chanctxt->IPv4or6 = af;
3640 }
3641 
3642 
3643 /*
3644  * Determine whether or not a port forward listens to loopback, the
3645  * specified address or wildcard. On the client, a specified bind
3646  * address will always override gateway_ports. On the server, a
3647  * gateway_ports of 1 (``yes'') will override the client's specification
3648  * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
3649  * will bind to whatever address the client asked for.
3650  *
3651  * Special-case listen_addrs are:
3652  *
3653  * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
3654  * "" (empty string), "*"  -> wildcard v4/v6
3655  * "localhost"             -> loopback v4/v6
3656  * "127.0.0.1" / "::1"     -> accepted even if gateway_ports isn't set
3657  */
3658 static const char *
3659 channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
3660     int is_client, struct ForwardOptions *fwd_opts)
3661 {
3662 	const char *addr = NULL;
3663 	int wildcard = 0;
3664 
3665 	if (listen_addr == NULL) {
3666 		/* No address specified: default to gateway_ports setting */
3667 		if (fwd_opts->gateway_ports)
3668 			wildcard = 1;
3669 	} else if (fwd_opts->gateway_ports || is_client) {
3670 		if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
3671 		    strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
3672 		    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
3673 		    (!is_client && fwd_opts->gateway_ports == 1)) {
3674 			wildcard = 1;
3675 			/*
3676 			 * Notify client if they requested a specific listen
3677 			 * address and it was overridden.
3678 			 */
3679 			if (*listen_addr != '\0' &&
3680 			    strcmp(listen_addr, "0.0.0.0") != 0 &&
3681 			    strcmp(listen_addr, "*") != 0) {
3682 				ssh_packet_send_debug(ssh,
3683 				    "Forwarding listen address "
3684 				    "\"%s\" overridden by server "
3685 				    "GatewayPorts", listen_addr);
3686 			}
3687 		} else if (strcmp(listen_addr, "localhost") != 0 ||
3688 		    strcmp(listen_addr, "127.0.0.1") == 0 ||
3689 		    strcmp(listen_addr, "::1") == 0) {
3690 			/*
3691 			 * Accept explicit localhost address when
3692 			 * GatewayPorts=yes. The "localhost" hostname is
3693 			 * deliberately skipped here so it will listen on all
3694 			 * available local address families.
3695 			 */
3696 			addr = listen_addr;
3697 		}
3698 	} else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
3699 	    strcmp(listen_addr, "::1") == 0) {
3700 		/*
3701 		 * If a specific IPv4/IPv6 localhost address has been
3702 		 * requested then accept it even if gateway_ports is in
3703 		 * effect. This allows the client to prefer IPv4 or IPv6.
3704 		 */
3705 		addr = listen_addr;
3706 	}
3707 	if (wildcardp != NULL)
3708 		*wildcardp = wildcard;
3709 	return addr;
3710 }
3711 
3712 static int
3713 channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
3714     struct Forward *fwd, int *allocated_listen_port,
3715     struct ForwardOptions *fwd_opts)
3716 {
3717 	Channel *c;
3718 	int sock, r, success = 0, wildcard = 0, is_client;
3719 	struct addrinfo hints, *ai, *aitop;
3720 	const char *host, *addr;
3721 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3722 	in_port_t *lport_p;
3723 
3724 	is_client = (type == SSH_CHANNEL_PORT_LISTENER);
3725 
3726 	if (is_client && fwd->connect_path != NULL) {
3727 		host = fwd->connect_path;
3728 	} else {
3729 		host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
3730 		    fwd->listen_host : fwd->connect_host;
3731 		if (host == NULL) {
3732 			error("No forward host name.");
3733 			return 0;
3734 		}
3735 		if (strlen(host) >= NI_MAXHOST) {
3736 			error("Forward host name too long.");
3737 			return 0;
3738 		}
3739 	}
3740 
3741 	/* Determine the bind address, cf. channel_fwd_bind_addr() comment */
3742 	addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
3743 	    is_client, fwd_opts);
3744 	debug3_f("type %d wildcard %d addr %s", type, wildcard,
3745 	    (addr == NULL) ? "NULL" : addr);
3746 
3747 	/*
3748 	 * getaddrinfo returns a loopback address if the hostname is
3749 	 * set to NULL and hints.ai_flags is not AI_PASSIVE
3750 	 */
3751 	memset(&hints, 0, sizeof(hints));
3752 	hints.ai_family = ssh->chanctxt->IPv4or6;
3753 	hints.ai_flags = wildcard ? AI_PASSIVE : 0;
3754 	hints.ai_socktype = SOCK_STREAM;
3755 	snprintf(strport, sizeof strport, "%d", fwd->listen_port);
3756 	if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
3757 		if (addr == NULL) {
3758 			/* This really shouldn't happen */
3759 			ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
3760 			    ssh_gai_strerror(r));
3761 		} else {
3762 			error_f("getaddrinfo(%.64s): %s", addr,
3763 			    ssh_gai_strerror(r));
3764 		}
3765 		return 0;
3766 	}
3767 	if (allocated_listen_port != NULL)
3768 		*allocated_listen_port = 0;
3769 	for (ai = aitop; ai; ai = ai->ai_next) {
3770 		switch (ai->ai_family) {
3771 		case AF_INET:
3772 			lport_p = &((struct sockaddr_in *)ai->ai_addr)->
3773 			    sin_port;
3774 			break;
3775 		case AF_INET6:
3776 			lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
3777 			    sin6_port;
3778 			break;
3779 		default:
3780 			continue;
3781 		}
3782 		/*
3783 		 * If allocating a port for -R forwards, then use the
3784 		 * same port for all address families.
3785 		 */
3786 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
3787 		    fwd->listen_port == 0 && allocated_listen_port != NULL &&
3788 		    *allocated_listen_port > 0)
3789 			*lport_p = htons(*allocated_listen_port);
3790 
3791 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
3792 		    strport, sizeof(strport),
3793 		    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3794 			error_f("getnameinfo failed");
3795 			continue;
3796 		}
3797 		/* Create a port to listen for the host. */
3798 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3799 		if (sock == -1) {
3800 			/* this is no error since kernel may not support ipv6 */
3801 			verbose("socket [%s]:%s: %.100s", ntop, strport,
3802 			    strerror(errno));
3803 			continue;
3804 		}
3805 
3806 		set_reuseaddr(sock);
3807 		if (ai->ai_family == AF_INET6)
3808 			sock_set_v6only(sock);
3809 
3810 		debug("Local forwarding listening on %s port %s.",
3811 		    ntop, strport);
3812 
3813 		/* Bind the socket to the address. */
3814 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
3815 			/*
3816 			 * address can be in if use ipv6 address is
3817 			 * already bound
3818 			 */
3819 			if (!ai->ai_next)
3820 				error("bind [%s]:%s: %.100s",
3821 				    ntop, strport, strerror(errno));
3822 			else
3823 				verbose("bind [%s]:%s: %.100s",
3824 				    ntop, strport, strerror(errno));
3825 
3826 			close(sock);
3827 			continue;
3828 		}
3829 		/* Start listening for connections on the socket. */
3830 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
3831 			error("listen [%s]:%s: %.100s", ntop, strport,
3832 			    strerror(errno));
3833 			close(sock);
3834 			continue;
3835 		}
3836 
3837 		/*
3838 		 * fwd->listen_port == 0 requests a dynamically allocated port -
3839 		 * record what we got.
3840 		 */
3841 		if (type == SSH_CHANNEL_RPORT_LISTENER &&
3842 		    fwd->listen_port == 0 &&
3843 		    allocated_listen_port != NULL &&
3844 		    *allocated_listen_port == 0) {
3845 			*allocated_listen_port = get_local_port(sock);
3846 			debug("Allocated listen port %d",
3847 			    *allocated_listen_port);
3848 		}
3849 
3850 		/* Allocate a channel number for the socket. */
3851 		c = channel_new(ssh, "port-listener", type, sock, sock, -1,
3852 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3853 		    0, "port listener", 1);
3854 		c->path = xstrdup(host);
3855 		c->host_port = fwd->connect_port;
3856 		c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
3857 		if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
3858 		    !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
3859 			c->listening_port = *allocated_listen_port;
3860 		else
3861 			c->listening_port = fwd->listen_port;
3862 		success = 1;
3863 	}
3864 	if (success == 0)
3865 		error_f("cannot listen to port: %d", fwd->listen_port);
3866 	freeaddrinfo(aitop);
3867 	return success;
3868 }
3869 
3870 static int
3871 channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
3872     struct Forward *fwd, struct ForwardOptions *fwd_opts)
3873 {
3874 	struct sockaddr_un sunaddr;
3875 	const char *path;
3876 	Channel *c;
3877 	int port, sock;
3878 	mode_t omask;
3879 
3880 	switch (type) {
3881 	case SSH_CHANNEL_UNIX_LISTENER:
3882 		if (fwd->connect_path != NULL) {
3883 			if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
3884 				error("Local connecting path too long: %s",
3885 				    fwd->connect_path);
3886 				return 0;
3887 			}
3888 			path = fwd->connect_path;
3889 			port = PORT_STREAMLOCAL;
3890 		} else {
3891 			if (fwd->connect_host == NULL) {
3892 				error("No forward host name.");
3893 				return 0;
3894 			}
3895 			if (strlen(fwd->connect_host) >= NI_MAXHOST) {
3896 				error("Forward host name too long.");
3897 				return 0;
3898 			}
3899 			path = fwd->connect_host;
3900 			port = fwd->connect_port;
3901 		}
3902 		break;
3903 	case SSH_CHANNEL_RUNIX_LISTENER:
3904 		path = fwd->listen_path;
3905 		port = PORT_STREAMLOCAL;
3906 		break;
3907 	default:
3908 		error_f("unexpected channel type %d", type);
3909 		return 0;
3910 	}
3911 
3912 	if (fwd->listen_path == NULL) {
3913 		error("No forward path name.");
3914 		return 0;
3915 	}
3916 	if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
3917 		error("Local listening path too long: %s", fwd->listen_path);
3918 		return 0;
3919 	}
3920 
3921 	debug3_f("type %d path %s", type, fwd->listen_path);
3922 
3923 	/* Start a Unix domain listener. */
3924 	omask = umask(fwd_opts->streamlocal_bind_mask);
3925 	sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
3926 	    fwd_opts->streamlocal_bind_unlink);
3927 	umask(omask);
3928 	if (sock < 0)
3929 		return 0;
3930 
3931 	debug("Local forwarding listening on path %s.", fwd->listen_path);
3932 
3933 	/* Allocate a channel number for the socket. */
3934 	c = channel_new(ssh, "unix-listener", type, sock, sock, -1,
3935 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
3936 	    0, "unix listener", 1);
3937 	c->path = xstrdup(path);
3938 	c->host_port = port;
3939 	c->listening_port = PORT_STREAMLOCAL;
3940 	c->listening_addr = xstrdup(fwd->listen_path);
3941 	return 1;
3942 }
3943 
3944 static int
3945 channel_cancel_rport_listener_tcpip(struct ssh *ssh,
3946     const char *host, u_short port)
3947 {
3948 	u_int i;
3949 	int found = 0;
3950 
3951 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3952 		Channel *c = ssh->chanctxt->channels[i];
3953 		if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
3954 			continue;
3955 		if (strcmp(c->path, host) == 0 && c->listening_port == port) {
3956 			debug2_f("close channel %d", i);
3957 			channel_free(ssh, c);
3958 			found = 1;
3959 		}
3960 	}
3961 
3962 	return found;
3963 }
3964 
3965 static int
3966 channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
3967 {
3968 	u_int i;
3969 	int found = 0;
3970 
3971 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
3972 		Channel *c = ssh->chanctxt->channels[i];
3973 		if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
3974 			continue;
3975 		if (c->path == NULL)
3976 			continue;
3977 		if (strcmp(c->path, path) == 0) {
3978 			debug2_f("close channel %d", i);
3979 			channel_free(ssh, c);
3980 			found = 1;
3981 		}
3982 	}
3983 
3984 	return found;
3985 }
3986 
3987 int
3988 channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
3989 {
3990 	if (fwd->listen_path != NULL) {
3991 		return channel_cancel_rport_listener_streamlocal(ssh,
3992 		    fwd->listen_path);
3993 	} else {
3994 		return channel_cancel_rport_listener_tcpip(ssh,
3995 		    fwd->listen_host, fwd->listen_port);
3996 	}
3997 }
3998 
3999 static int
4000 channel_cancel_lport_listener_tcpip(struct ssh *ssh,
4001     const char *lhost, u_short lport, int cport,
4002     struct ForwardOptions *fwd_opts)
4003 {
4004 	u_int i;
4005 	int found = 0;
4006 	const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
4007 
4008 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4009 		Channel *c = ssh->chanctxt->channels[i];
4010 		if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
4011 			continue;
4012 		if (c->listening_port != lport)
4013 			continue;
4014 		if (cport == CHANNEL_CANCEL_PORT_STATIC) {
4015 			/* skip dynamic forwardings */
4016 			if (c->host_port == 0)
4017 				continue;
4018 		} else {
4019 			if (c->host_port != cport)
4020 				continue;
4021 		}
4022 		if ((c->listening_addr == NULL && addr != NULL) ||
4023 		    (c->listening_addr != NULL && addr == NULL))
4024 			continue;
4025 		if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
4026 			debug2_f("close channel %d", i);
4027 			channel_free(ssh, c);
4028 			found = 1;
4029 		}
4030 	}
4031 
4032 	return found;
4033 }
4034 
4035 static int
4036 channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
4037 {
4038 	u_int i;
4039 	int found = 0;
4040 
4041 	if (path == NULL) {
4042 		error_f("no path specified.");
4043 		return 0;
4044 	}
4045 
4046 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
4047 		Channel *c = ssh->chanctxt->channels[i];
4048 		if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
4049 			continue;
4050 		if (c->listening_addr == NULL)
4051 			continue;
4052 		if (strcmp(c->listening_addr, path) == 0) {
4053 			debug2_f("close channel %d", i);
4054 			channel_free(ssh, c);
4055 			found = 1;
4056 		}
4057 	}
4058 
4059 	return found;
4060 }
4061 
4062 int
4063 channel_cancel_lport_listener(struct ssh *ssh,
4064     struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
4065 {
4066 	if (fwd->listen_path != NULL) {
4067 		return channel_cancel_lport_listener_streamlocal(ssh,
4068 		    fwd->listen_path);
4069 	} else {
4070 		return channel_cancel_lport_listener_tcpip(ssh,
4071 		    fwd->listen_host, fwd->listen_port, cport, fwd_opts);
4072 	}
4073 }
4074 
4075 /* protocol local port fwd, used by ssh */
4076 int
4077 channel_setup_local_fwd_listener(struct ssh *ssh,
4078     struct Forward *fwd, struct ForwardOptions *fwd_opts)
4079 {
4080 	if (fwd->listen_path != NULL) {
4081 		return channel_setup_fwd_listener_streamlocal(ssh,
4082 		    SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
4083 	} else {
4084 		return channel_setup_fwd_listener_tcpip(ssh,
4085 		    SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
4086 	}
4087 }
4088 
4089 /* Matches a remote forwarding permission against a requested forwarding */
4090 static int
4091 remote_open_match(struct permission *allowed_open, struct Forward *fwd)
4092 {
4093 	int ret;
4094 	char *lhost;
4095 
4096 	/* XXX add ACLs for streamlocal */
4097 	if (fwd->listen_path != NULL)
4098 		return 1;
4099 
4100 	if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
4101 		return 0;
4102 
4103 	if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
4104 	    allowed_open->listen_port != fwd->listen_port)
4105 		return 0;
4106 
4107 	/* Match hostnames case-insensitively */
4108 	lhost = xstrdup(fwd->listen_host);
4109 	lowercase(lhost);
4110 	ret = match_pattern(lhost, allowed_open->listen_host);
4111 	free(lhost);
4112 
4113 	return ret;
4114 }
4115 
4116 /* Checks whether a requested remote forwarding is permitted */
4117 static int
4118 check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
4119 {
4120 	struct ssh_channels *sc = ssh->chanctxt;
4121 	struct permission_set *pset = &sc->remote_perms;
4122 	u_int i, permit, permit_adm = 1;
4123 	struct permission *perm;
4124 
4125 	/* XXX apply GatewayPorts override before checking? */
4126 
4127 	permit = pset->all_permitted;
4128 	if (!permit) {
4129 		for (i = 0; i < pset->num_permitted_user; i++) {
4130 			perm = &pset->permitted_user[i];
4131 			if (remote_open_match(perm, fwd)) {
4132 				permit = 1;
4133 				break;
4134 			}
4135 		}
4136 	}
4137 
4138 	if (pset->num_permitted_admin > 0) {
4139 		permit_adm = 0;
4140 		for (i = 0; i < pset->num_permitted_admin; i++) {
4141 			perm = &pset->permitted_admin[i];
4142 			if (remote_open_match(perm, fwd)) {
4143 				permit_adm = 1;
4144 				break;
4145 			}
4146 		}
4147 	}
4148 
4149 	return permit && permit_adm;
4150 }
4151 
4152 /* protocol v2 remote port fwd, used by sshd */
4153 int
4154 channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
4155     int *allocated_listen_port, struct ForwardOptions *fwd_opts)
4156 {
4157 	if (!check_rfwd_permission(ssh, fwd)) {
4158 		ssh_packet_send_debug(ssh, "port forwarding refused");
4159 		if (fwd->listen_path != NULL)
4160 			/* XXX always allowed, see remote_open_match() */
4161 			logit("Received request from %.100s port %d to "
4162 			    "remote forward to path \"%.100s\", "
4163 			    "but the request was denied.",
4164 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4165 			    fwd->listen_path);
4166 		else if(fwd->listen_host != NULL)
4167 			logit("Received request from %.100s port %d to "
4168 			    "remote forward to host %.100s port %d, "
4169 			    "but the request was denied.",
4170 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
4171 			    fwd->listen_host, fwd->listen_port );
4172 		else
4173 			logit("Received request from %.100s port %d to remote "
4174 			    "forward, but the request was denied.",
4175 			    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
4176 		return 0;
4177 	}
4178 	if (fwd->listen_path != NULL) {
4179 		return channel_setup_fwd_listener_streamlocal(ssh,
4180 		    SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
4181 	} else {
4182 		return channel_setup_fwd_listener_tcpip(ssh,
4183 		    SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
4184 		    fwd_opts);
4185 	}
4186 }
4187 
4188 /*
4189  * Translate the requested rfwd listen host to something usable for
4190  * this server.
4191  */
4192 static const char *
4193 channel_rfwd_bind_host(const char *listen_host)
4194 {
4195 	if (listen_host == NULL) {
4196 		return "localhost";
4197 	} else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
4198 		return "";
4199 	} else
4200 		return listen_host;
4201 }
4202 
4203 /*
4204  * Initiate forwarding of connections to port "port" on remote host through
4205  * the secure channel to host:port from local side.
4206  * Returns handle (index) for updating the dynamic listen port with
4207  * channel_update_permission().
4208  */
4209 int
4210 channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
4211 {
4212 	int r, success = 0, idx = -1;
4213 	const char *host_to_connect, *listen_host, *listen_path;
4214 	int port_to_connect, listen_port;
4215 
4216 	/* Send the forward request to the remote side. */
4217 	if (fwd->listen_path != NULL) {
4218 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4219 		    (r = sshpkt_put_cstring(ssh,
4220 		    "streamlocal-forward@openssh.com")) != 0 ||
4221 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4222 		    (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
4223 		    (r = sshpkt_send(ssh)) != 0 ||
4224 		    (r = ssh_packet_write_wait(ssh)) != 0)
4225 			fatal_fr(r, "request streamlocal");
4226 	} else {
4227 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4228 		    (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
4229 		    (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
4230 		    (r = sshpkt_put_cstring(ssh,
4231 		    channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
4232 		    (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
4233 		    (r = sshpkt_send(ssh)) != 0 ||
4234 		    (r = ssh_packet_write_wait(ssh)) != 0)
4235 			fatal_fr(r, "request tcpip-forward");
4236 	}
4237 	/* Assume that server accepts the request */
4238 	success = 1;
4239 	if (success) {
4240 		/* Record that connection to this host/port is permitted. */
4241 		host_to_connect = listen_host = listen_path = NULL;
4242 		port_to_connect = listen_port = 0;
4243 		if (fwd->connect_path != NULL) {
4244 			host_to_connect = fwd->connect_path;
4245 			port_to_connect = PORT_STREAMLOCAL;
4246 		} else {
4247 			host_to_connect = fwd->connect_host;
4248 			port_to_connect = fwd->connect_port;
4249 		}
4250 		if (fwd->listen_path != NULL) {
4251 			listen_path = fwd->listen_path;
4252 			listen_port = PORT_STREAMLOCAL;
4253 		} else {
4254 			listen_host = fwd->listen_host;
4255 			listen_port = fwd->listen_port;
4256 		}
4257 		idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
4258 		    host_to_connect, port_to_connect,
4259 		    listen_host, listen_path, listen_port, NULL);
4260 	}
4261 	return idx;
4262 }
4263 
4264 static int
4265 open_match(struct permission *allowed_open, const char *requestedhost,
4266     int requestedport)
4267 {
4268 	if (allowed_open->host_to_connect == NULL)
4269 		return 0;
4270 	if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
4271 	    allowed_open->port_to_connect != requestedport)
4272 		return 0;
4273 	if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
4274 	    strcmp(allowed_open->host_to_connect, requestedhost) != 0)
4275 		return 0;
4276 	return 1;
4277 }
4278 
4279 /*
4280  * Note that in the listen host/port case
4281  * we don't support FWD_PERMIT_ANY_PORT and
4282  * need to translate between the configured-host (listen_host)
4283  * and what we've sent to the remote server (channel_rfwd_bind_host)
4284  */
4285 static int
4286 open_listen_match_tcpip(struct permission *allowed_open,
4287     const char *requestedhost, u_short requestedport, int translate)
4288 {
4289 	const char *allowed_host;
4290 
4291 	if (allowed_open->host_to_connect == NULL)
4292 		return 0;
4293 	if (allowed_open->listen_port != requestedport)
4294 		return 0;
4295 	if (!translate && allowed_open->listen_host == NULL &&
4296 	    requestedhost == NULL)
4297 		return 1;
4298 	allowed_host = translate ?
4299 	    channel_rfwd_bind_host(allowed_open->listen_host) :
4300 	    allowed_open->listen_host;
4301 	if (allowed_host == NULL || requestedhost == NULL ||
4302 	    strcmp(allowed_host, requestedhost) != 0)
4303 		return 0;
4304 	return 1;
4305 }
4306 
4307 static int
4308 open_listen_match_streamlocal(struct permission *allowed_open,
4309     const char *requestedpath)
4310 {
4311 	if (allowed_open->host_to_connect == NULL)
4312 		return 0;
4313 	if (allowed_open->listen_port != PORT_STREAMLOCAL)
4314 		return 0;
4315 	if (allowed_open->listen_path == NULL ||
4316 	    strcmp(allowed_open->listen_path, requestedpath) != 0)
4317 		return 0;
4318 	return 1;
4319 }
4320 
4321 /*
4322  * Request cancellation of remote forwarding of connection host:port from
4323  * local side.
4324  */
4325 static int
4326 channel_request_rforward_cancel_tcpip(struct ssh *ssh,
4327     const char *host, u_short port)
4328 {
4329 	struct ssh_channels *sc = ssh->chanctxt;
4330 	struct permission_set *pset = &sc->local_perms;
4331 	int r;
4332 	u_int i;
4333 	struct permission *perm = NULL;
4334 
4335 	for (i = 0; i < pset->num_permitted_user; i++) {
4336 		perm = &pset->permitted_user[i];
4337 		if (open_listen_match_tcpip(perm, host, port, 0))
4338 			break;
4339 		perm = NULL;
4340 	}
4341 	if (perm == NULL) {
4342 		debug_f("requested forward not found");
4343 		return -1;
4344 	}
4345 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4346 	    (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
4347 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4348 	    (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
4349 	    (r = sshpkt_put_u32(ssh, port)) != 0 ||
4350 	    (r = sshpkt_send(ssh)) != 0)
4351 		fatal_fr(r, "send cancel");
4352 
4353 	fwd_perm_clear(perm); /* unregister */
4354 
4355 	return 0;
4356 }
4357 
4358 /*
4359  * Request cancellation of remote forwarding of Unix domain socket
4360  * path from local side.
4361  */
4362 static int
4363 channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
4364 {
4365 	struct ssh_channels *sc = ssh->chanctxt;
4366 	struct permission_set *pset = &sc->local_perms;
4367 	int r;
4368 	u_int i;
4369 	struct permission *perm = NULL;
4370 
4371 	for (i = 0; i < pset->num_permitted_user; i++) {
4372 		perm = &pset->permitted_user[i];
4373 		if (open_listen_match_streamlocal(perm, path))
4374 			break;
4375 		perm = NULL;
4376 	}
4377 	if (perm == NULL) {
4378 		debug_f("requested forward not found");
4379 		return -1;
4380 	}
4381 	if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
4382 	    (r = sshpkt_put_cstring(ssh,
4383 	    "cancel-streamlocal-forward@openssh.com")) != 0 ||
4384 	    (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
4385 	    (r = sshpkt_put_cstring(ssh, path)) != 0 ||
4386 	    (r = sshpkt_send(ssh)) != 0)
4387 		fatal_fr(r, "send cancel");
4388 
4389 	fwd_perm_clear(perm); /* unregister */
4390 
4391 	return 0;
4392 }
4393 
4394 /*
4395  * Request cancellation of remote forwarding of a connection from local side.
4396  */
4397 int
4398 channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
4399 {
4400 	if (fwd->listen_path != NULL) {
4401 		return channel_request_rforward_cancel_streamlocal(ssh,
4402 		    fwd->listen_path);
4403 	} else {
4404 		return channel_request_rforward_cancel_tcpip(ssh,
4405 		    fwd->listen_host,
4406 		    fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
4407 	}
4408 }
4409 
4410 /*
4411  * Permits opening to any host/port if permitted_user[] is empty.  This is
4412  * usually called by the server, because the user could connect to any port
4413  * anyway, and the server has no way to know but to trust the client anyway.
4414  */
4415 void
4416 channel_permit_all(struct ssh *ssh, int where)
4417 {
4418 	struct permission_set *pset = permission_set_get(ssh, where);
4419 
4420 	if (pset->num_permitted_user == 0)
4421 		pset->all_permitted = 1;
4422 }
4423 
4424 /*
4425  * Permit the specified host/port for forwarding.
4426  */
4427 void
4428 channel_add_permission(struct ssh *ssh, int who, int where,
4429     char *host, int port)
4430 {
4431 	int local = where == FORWARD_LOCAL;
4432 	struct permission_set *pset = permission_set_get(ssh, where);
4433 
4434 	debug("allow %s forwarding to host %s port %d",
4435 	    fwd_ident(who, where), host, port);
4436 	/*
4437 	 * Remote forwards set listen_host/port, local forwards set
4438 	 * host/port_to_connect.
4439 	 */
4440 	permission_set_add(ssh, who, where,
4441 	    local ? host : 0, local ? port : 0,
4442 	    local ? NULL : host, NULL, local ? 0 : port, NULL);
4443 	pset->all_permitted = 0;
4444 }
4445 
4446 /*
4447  * Administratively disable forwarding.
4448  */
4449 void
4450 channel_disable_admin(struct ssh *ssh, int where)
4451 {
4452 	channel_clear_permission(ssh, FORWARD_ADM, where);
4453 	permission_set_add(ssh, FORWARD_ADM, where,
4454 	    NULL, 0, NULL, NULL, 0, NULL);
4455 }
4456 
4457 /*
4458  * Clear a list of permitted opens.
4459  */
4460 void
4461 channel_clear_permission(struct ssh *ssh, int who, int where)
4462 {
4463 	struct permission **permp;
4464 	u_int *npermp;
4465 
4466 	permission_set_get_array(ssh, who, where, &permp, &npermp);
4467 	*permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
4468 	*npermp = 0;
4469 }
4470 
4471 /*
4472  * Update the listen port for a dynamic remote forward, after
4473  * the actual 'newport' has been allocated. If 'newport' < 0 is
4474  * passed then they entry will be invalidated.
4475  */
4476 void
4477 channel_update_permission(struct ssh *ssh, int idx, int newport)
4478 {
4479 	struct permission_set *pset = &ssh->chanctxt->local_perms;
4480 
4481 	if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
4482 		debug_f("index out of range: %d num_permitted_user %d",
4483 		    idx, pset->num_permitted_user);
4484 		return;
4485 	}
4486 	debug("%s allowed port %d for forwarding to host %s port %d",
4487 	    newport > 0 ? "Updating" : "Removing",
4488 	    newport,
4489 	    pset->permitted_user[idx].host_to_connect,
4490 	    pset->permitted_user[idx].port_to_connect);
4491 	if (newport <= 0)
4492 		fwd_perm_clear(&pset->permitted_user[idx]);
4493 	else {
4494 		pset->permitted_user[idx].listen_port =
4495 		    (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
4496 	}
4497 }
4498 
4499 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
4500 int
4501 permitopen_port(const char *p)
4502 {
4503 	int port;
4504 
4505 	if (strcmp(p, "*") == 0)
4506 		return FWD_PERMIT_ANY_PORT;
4507 	if ((port = a2port(p)) > 0)
4508 		return port;
4509 	return -1;
4510 }
4511 
4512 /* Try to start non-blocking connect to next host in cctx list */
4513 static int
4514 connect_next(struct channel_connect *cctx)
4515 {
4516 	int sock, saved_errno;
4517 	struct sockaddr_un *sunaddr;
4518 	char ntop[NI_MAXHOST];
4519 	char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
4520 
4521 	for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
4522 		switch (cctx->ai->ai_family) {
4523 		case AF_UNIX:
4524 			/* unix:pathname instead of host:port */
4525 			sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
4526 			strlcpy(ntop, "unix", sizeof(ntop));
4527 			strlcpy(strport, sunaddr->sun_path, sizeof(strport));
4528 			break;
4529 		case AF_INET:
4530 		case AF_INET6:
4531 			if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
4532 			    ntop, sizeof(ntop), strport, sizeof(strport),
4533 			    NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
4534 				error_f("getnameinfo failed");
4535 				continue;
4536 			}
4537 			break;
4538 		default:
4539 			continue;
4540 		}
4541 		debug_f("start for host %.100s ([%.100s]:%s)",
4542 		    cctx->host, ntop, strport);
4543 		if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
4544 		    cctx->ai->ai_protocol)) == -1) {
4545 			if (cctx->ai->ai_next == NULL)
4546 				error("socket: %.100s", strerror(errno));
4547 			else
4548 				verbose("socket: %.100s", strerror(errno));
4549 			continue;
4550 		}
4551 		if (set_nonblock(sock) == -1)
4552 			fatal_f("set_nonblock(%d)", sock);
4553 		if (connect(sock, cctx->ai->ai_addr,
4554 		    cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
4555 			debug_f("host %.100s ([%.100s]:%s): %.100s",
4556 			    cctx->host, ntop, strport, strerror(errno));
4557 			saved_errno = errno;
4558 			close(sock);
4559 			errno = saved_errno;
4560 			continue;	/* fail -- try next */
4561 		}
4562 		if (cctx->ai->ai_family != AF_UNIX)
4563 			set_nodelay(sock);
4564 		debug_f("connect host %.100s ([%.100s]:%s) in progress, fd=%d",
4565 		    cctx->host, ntop, strport, sock);
4566 		cctx->ai = cctx->ai->ai_next;
4567 		return sock;
4568 	}
4569 	return -1;
4570 }
4571 
4572 static void
4573 channel_connect_ctx_free(struct channel_connect *cctx)
4574 {
4575 	free(cctx->host);
4576 	if (cctx->aitop) {
4577 		if (cctx->aitop->ai_family == AF_UNIX)
4578 			free(cctx->aitop);
4579 		else
4580 			freeaddrinfo(cctx->aitop);
4581 	}
4582 	memset(cctx, 0, sizeof(*cctx));
4583 }
4584 
4585 /*
4586  * Return connecting socket to remote host:port or local socket path,
4587  * passing back the failure reason if appropriate.
4588  */
4589 static int
4590 connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
4591     char *ctype, char *rname, struct channel_connect *cctx,
4592     int *reason, const char **errmsg)
4593 {
4594 	struct addrinfo hints;
4595 	int gaierr;
4596 	int sock = -1;
4597 	char strport[NI_MAXSERV];
4598 
4599 	if (port == PORT_STREAMLOCAL) {
4600 		struct sockaddr_un *sunaddr;
4601 		struct addrinfo *ai;
4602 
4603 		if (strlen(name) > sizeof(sunaddr->sun_path)) {
4604 			error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
4605 			return -1;
4606 		}
4607 
4608 		/*
4609 		 * Fake up a struct addrinfo for AF_UNIX connections.
4610 		 * channel_connect_ctx_free() must check ai_family
4611 		 * and use free() not freeaddirinfo() for AF_UNIX.
4612 		 */
4613 		ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
4614 		memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
4615 		ai->ai_addr = (struct sockaddr *)(ai + 1);
4616 		ai->ai_addrlen = sizeof(*sunaddr);
4617 		ai->ai_family = AF_UNIX;
4618 		ai->ai_socktype = socktype;
4619 		ai->ai_protocol = PF_UNSPEC;
4620 		sunaddr = (struct sockaddr_un *)ai->ai_addr;
4621 		sunaddr->sun_family = AF_UNIX;
4622 		strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
4623 		cctx->aitop = ai;
4624 	} else {
4625 		memset(&hints, 0, sizeof(hints));
4626 		hints.ai_family = ssh->chanctxt->IPv4or6;
4627 		hints.ai_socktype = socktype;
4628 		snprintf(strport, sizeof strport, "%d", port);
4629 		if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
4630 		    != 0) {
4631 			if (errmsg != NULL)
4632 				*errmsg = ssh_gai_strerror(gaierr);
4633 			if (reason != NULL)
4634 				*reason = SSH2_OPEN_CONNECT_FAILED;
4635 			error("connect_to %.100s: unknown host (%s)", name,
4636 			    ssh_gai_strerror(gaierr));
4637 			return -1;
4638 		}
4639 	}
4640 
4641 	cctx->host = xstrdup(name);
4642 	cctx->port = port;
4643 	cctx->ai = cctx->aitop;
4644 
4645 	if ((sock = connect_next(cctx)) == -1) {
4646 		error("connect to %.100s port %d failed: %s",
4647 		    name, port, strerror(errno));
4648 		return -1;
4649 	}
4650 
4651 	return sock;
4652 }
4653 
4654 /* Return CONNECTING channel to remote host:port or local socket path */
4655 static Channel *
4656 connect_to(struct ssh *ssh, const char *host, int port,
4657     char *ctype, char *rname)
4658 {
4659 	struct channel_connect cctx;
4660 	Channel *c;
4661 	int sock;
4662 
4663 	memset(&cctx, 0, sizeof(cctx));
4664 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4665 	    &cctx, NULL, NULL);
4666 	if (sock == -1) {
4667 		channel_connect_ctx_free(&cctx);
4668 		return NULL;
4669 	}
4670 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4671 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4672 	c->host_port = port;
4673 	c->path = xstrdup(host);
4674 	c->connect_ctx = cctx;
4675 
4676 	return c;
4677 }
4678 
4679 /*
4680  * returns either the newly connected channel or the downstream channel
4681  * that needs to deal with this connection.
4682  */
4683 Channel *
4684 channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
4685     u_short listen_port, char *ctype, char *rname)
4686 {
4687 	struct ssh_channels *sc = ssh->chanctxt;
4688 	struct permission_set *pset = &sc->local_perms;
4689 	u_int i;
4690 	struct permission *perm;
4691 
4692 	for (i = 0; i < pset->num_permitted_user; i++) {
4693 		perm = &pset->permitted_user[i];
4694 		if (open_listen_match_tcpip(perm,
4695 		    listen_host, listen_port, 1)) {
4696 			if (perm->downstream)
4697 				return perm->downstream;
4698 			if (perm->port_to_connect == 0)
4699 				return rdynamic_connect_prepare(ssh,
4700 				    ctype, rname);
4701 			return connect_to(ssh,
4702 			    perm->host_to_connect, perm->port_to_connect,
4703 			    ctype, rname);
4704 		}
4705 	}
4706 	error("WARNING: Server requests forwarding for unknown listen_port %d",
4707 	    listen_port);
4708 	return NULL;
4709 }
4710 
4711 Channel *
4712 channel_connect_by_listen_path(struct ssh *ssh, const char *path,
4713     char *ctype, char *rname)
4714 {
4715 	struct ssh_channels *sc = ssh->chanctxt;
4716 	struct permission_set *pset = &sc->local_perms;
4717 	u_int i;
4718 	struct permission *perm;
4719 
4720 	for (i = 0; i < pset->num_permitted_user; i++) {
4721 		perm = &pset->permitted_user[i];
4722 		if (open_listen_match_streamlocal(perm, path)) {
4723 			return connect_to(ssh,
4724 			    perm->host_to_connect, perm->port_to_connect,
4725 			    ctype, rname);
4726 		}
4727 	}
4728 	error("WARNING: Server requests forwarding for unknown path %.100s",
4729 	    path);
4730 	return NULL;
4731 }
4732 
4733 /* Check if connecting to that port is permitted and connect. */
4734 Channel *
4735 channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
4736     char *ctype, char *rname, int *reason, const char **errmsg)
4737 {
4738 	struct ssh_channels *sc = ssh->chanctxt;
4739 	struct permission_set *pset = &sc->local_perms;
4740 	struct channel_connect cctx;
4741 	Channel *c;
4742 	u_int i, permit, permit_adm = 1;
4743 	int sock;
4744 	struct permission *perm;
4745 
4746 	permit = pset->all_permitted;
4747 	if (!permit) {
4748 		for (i = 0; i < pset->num_permitted_user; i++) {
4749 			perm = &pset->permitted_user[i];
4750 			if (open_match(perm, host, port)) {
4751 				permit = 1;
4752 				break;
4753 			}
4754 		}
4755 	}
4756 
4757 	if (pset->num_permitted_admin > 0) {
4758 		permit_adm = 0;
4759 		for (i = 0; i < pset->num_permitted_admin; i++) {
4760 			perm = &pset->permitted_admin[i];
4761 			if (open_match(perm, host, port)) {
4762 				permit_adm = 1;
4763 				break;
4764 			}
4765 		}
4766 	}
4767 
4768 	if (!permit || !permit_adm) {
4769 		logit("Received request from %.100s port %d to connect to "
4770 		    "host %.100s port %d, but the request was denied.",
4771 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
4772 		if (reason != NULL)
4773 			*reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
4774 		return NULL;
4775 	}
4776 
4777 	memset(&cctx, 0, sizeof(cctx));
4778 	sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
4779 	    &cctx, reason, errmsg);
4780 	if (sock == -1) {
4781 		channel_connect_ctx_free(&cctx);
4782 		return NULL;
4783 	}
4784 
4785 	c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
4786 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4787 	c->host_port = port;
4788 	c->path = xstrdup(host);
4789 	c->connect_ctx = cctx;
4790 
4791 	return c;
4792 }
4793 
4794 /* Check if connecting to that path is permitted and connect. */
4795 Channel *
4796 channel_connect_to_path(struct ssh *ssh, const char *path,
4797     char *ctype, char *rname)
4798 {
4799 	struct ssh_channels *sc = ssh->chanctxt;
4800 	struct permission_set *pset = &sc->local_perms;
4801 	u_int i, permit, permit_adm = 1;
4802 	struct permission *perm;
4803 
4804 	permit = pset->all_permitted;
4805 	if (!permit) {
4806 		for (i = 0; i < pset->num_permitted_user; i++) {
4807 			perm = &pset->permitted_user[i];
4808 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
4809 				permit = 1;
4810 				break;
4811 			}
4812 		}
4813 	}
4814 
4815 	if (pset->num_permitted_admin > 0) {
4816 		permit_adm = 0;
4817 		for (i = 0; i < pset->num_permitted_admin; i++) {
4818 			perm = &pset->permitted_admin[i];
4819 			if (open_match(perm, path, PORT_STREAMLOCAL)) {
4820 				permit_adm = 1;
4821 				break;
4822 			}
4823 		}
4824 	}
4825 
4826 	if (!permit || !permit_adm) {
4827 		logit("Received request to connect to path %.100s, "
4828 		    "but the request was denied.", path);
4829 		return NULL;
4830 	}
4831 	return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
4832 }
4833 
4834 void
4835 channel_send_window_changes(struct ssh *ssh)
4836 {
4837 	struct ssh_channels *sc = ssh->chanctxt;
4838 	struct winsize ws;
4839 	int r;
4840 	u_int i;
4841 
4842 	for (i = 0; i < sc->channels_alloc; i++) {
4843 		if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
4844 		    sc->channels[i]->type != SSH_CHANNEL_OPEN)
4845 			continue;
4846 		if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
4847 			continue;
4848 		channel_request_start(ssh, i, "window-change", 0);
4849 		if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
4850 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
4851 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
4852 		    (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
4853 		    (r = sshpkt_send(ssh)) != 0)
4854 			fatal_fr(r, "channel %u; send window-change", i);
4855 	}
4856 }
4857 
4858 /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
4859 static Channel *
4860 rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
4861 {
4862 	Channel *c;
4863 	int r;
4864 
4865 	c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
4866 	    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
4867 	c->host_port = 0;
4868 	c->path = NULL;
4869 
4870 	/*
4871 	 * We need to open the channel before we have a FD,
4872 	 * so that we can get SOCKS header from peer.
4873 	 */
4874 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
4875 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
4876 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
4877 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
4878 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0)
4879 		fatal_fr(r, "channel %i; confirm", c->self);
4880 	return c;
4881 }
4882 
4883 /* Return CONNECTING socket to remote host:port or local socket path */
4884 static int
4885 rdynamic_connect_finish(struct ssh *ssh, Channel *c)
4886 {
4887 	struct ssh_channels *sc = ssh->chanctxt;
4888 	struct permission_set *pset = &sc->local_perms;
4889 	struct permission *perm;
4890 	struct channel_connect cctx;
4891 	u_int i, permit_adm = 1;
4892 	int sock;
4893 
4894 	if (pset->num_permitted_admin > 0) {
4895 		permit_adm = 0;
4896 		for (i = 0; i < pset->num_permitted_admin; i++) {
4897 			perm = &pset->permitted_admin[i];
4898 			if (open_match(perm, c->path, c->host_port)) {
4899 				permit_adm = 1;
4900 				break;
4901 			}
4902 		}
4903 	}
4904 	if (!permit_adm) {
4905 		debug_f("requested forward not permitted");
4906 		return -1;
4907 	}
4908 
4909 	memset(&cctx, 0, sizeof(cctx));
4910 	sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
4911 	    NULL, &cctx, NULL, NULL);
4912 	if (sock == -1)
4913 		channel_connect_ctx_free(&cctx);
4914 	else {
4915 		/* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
4916 		c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
4917 		c->connect_ctx = cctx;
4918 		channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
4919 	}
4920 	return sock;
4921 }
4922 
4923 /* -- X11 forwarding */
4924 
4925 /*
4926  * Creates an internet domain socket for listening for X11 connections.
4927  * Returns 0 and a suitable display number for the DISPLAY variable
4928  * stored in display_numberp , or -1 if an error occurs.
4929  */
4930 int
4931 x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
4932     int x11_use_localhost, int single_connection,
4933     u_int *display_numberp, int **chanids)
4934 {
4935 	Channel *nc = NULL;
4936 	int display_number, sock;
4937 	u_short port;
4938 	struct addrinfo hints, *ai, *aitop;
4939 	char strport[NI_MAXSERV];
4940 	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
4941 
4942 	if (chanids == NULL)
4943 		return -1;
4944 
4945 	for (display_number = x11_display_offset;
4946 	    display_number < MAX_DISPLAYS;
4947 	    display_number++) {
4948 		port = 6000 + display_number;
4949 		memset(&hints, 0, sizeof(hints));
4950 		hints.ai_family = ssh->chanctxt->IPv4or6;
4951 		hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
4952 		hints.ai_socktype = SOCK_STREAM;
4953 		snprintf(strport, sizeof strport, "%d", port);
4954 		if ((gaierr = getaddrinfo(NULL, strport,
4955 		    &hints, &aitop)) != 0) {
4956 			error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
4957 			return -1;
4958 		}
4959 		for (ai = aitop; ai; ai = ai->ai_next) {
4960 			if (ai->ai_family != AF_INET &&
4961 			    ai->ai_family != AF_INET6)
4962 				continue;
4963 			sock = socket(ai->ai_family, ai->ai_socktype,
4964 			    ai->ai_protocol);
4965 			if (sock == -1) {
4966 				if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
4967 #ifdef EPFNOSUPPORT
4968 				    && (errno != EPFNOSUPPORT)
4969 #endif
4970 				    ) {
4971 					error("socket: %.100s", strerror(errno));
4972 					freeaddrinfo(aitop);
4973 					return -1;
4974 				} else {
4975 					debug("x11_create_display_inet: Socket family %d not supported",
4976 						 ai->ai_family);
4977 					continue;
4978 				}
4979 			}
4980 			if (ai->ai_family == AF_INET6)
4981 				sock_set_v6only(sock);
4982 			if (x11_use_localhost)
4983 				set_reuseaddr(sock);
4984 			if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
4985 				debug2_f("bind port %d: %.100s", port,
4986 				    strerror(errno));
4987 				close(sock);
4988 				for (n = 0; n < num_socks; n++)
4989 					close(socks[n]);
4990 				num_socks = 0;
4991 				break;
4992 			}
4993 			socks[num_socks++] = sock;
4994 			if (num_socks == NUM_SOCKS)
4995 				break;
4996 		}
4997 		freeaddrinfo(aitop);
4998 		if (num_socks > 0)
4999 			break;
5000 	}
5001 	if (display_number >= MAX_DISPLAYS) {
5002 		error("Failed to allocate internet-domain X11 display socket.");
5003 		return -1;
5004 	}
5005 	/* Start listening for connections on the socket. */
5006 	for (n = 0; n < num_socks; n++) {
5007 		sock = socks[n];
5008 		if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
5009 			error("listen: %.100s", strerror(errno));
5010 			close(sock);
5011 			return -1;
5012 		}
5013 	}
5014 
5015 	/* Allocate a channel for each socket. */
5016 	*chanids = xcalloc(num_socks + 1, sizeof(**chanids));
5017 	for (n = 0; n < num_socks; n++) {
5018 		sock = socks[n];
5019 		nc = channel_new(ssh, "x11-listener",
5020 		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
5021 		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
5022 		    0, "X11 inet listener", 1);
5023 		nc->single_connection = single_connection;
5024 		(*chanids)[n] = nc->self;
5025 	}
5026 	(*chanids)[n] = -1;
5027 
5028 	/* Return the display number for the DISPLAY environment variable. */
5029 	*display_numberp = display_number;
5030 	return 0;
5031 }
5032 
5033 static int
5034 connect_local_xsocket_path(const char *pathname)
5035 {
5036 	int sock;
5037 	struct sockaddr_un addr;
5038 
5039 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
5040 	if (sock == -1)
5041 		error("socket: %.100s", strerror(errno));
5042 	memset(&addr, 0, sizeof(addr));
5043 	addr.sun_family = AF_UNIX;
5044 	strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
5045 	if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
5046 		return sock;
5047 	close(sock);
5048 	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
5049 	return -1;
5050 }
5051 
5052 static int
5053 connect_local_xsocket(u_int dnr)
5054 {
5055 	char buf[1024];
5056 	snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
5057 	return connect_local_xsocket_path(buf);
5058 }
5059 
5060 #ifdef __APPLE__
5061 static int
5062 is_path_to_xsocket(const char *display, char *path, size_t pathlen)
5063 {
5064 	struct stat sbuf;
5065 
5066 	if (strlcpy(path, display, pathlen) >= pathlen) {
5067 		error("%s: display path too long", __func__);
5068 		return 0;
5069 	}
5070 	if (display[0] != '/')
5071 		return 0;
5072 	if (stat(path, &sbuf) == 0) {
5073 		return 1;
5074 	} else {
5075 		char *dot = strrchr(path, '.');
5076 		if (dot != NULL) {
5077 			*dot = '\0';
5078 			if (stat(path, &sbuf) == 0) {
5079 				return 1;
5080 			}
5081 		}
5082 	}
5083 	return 0;
5084 }
5085 #endif
5086 
5087 int
5088 x11_connect_display(struct ssh *ssh)
5089 {
5090 	u_int display_number;
5091 	const char *display;
5092 	char buf[1024], *cp;
5093 	struct addrinfo hints, *ai, *aitop;
5094 	char strport[NI_MAXSERV];
5095 	int gaierr, sock = 0;
5096 
5097 	/* Try to open a socket for the local X server. */
5098 	display = getenv("DISPLAY");
5099 	if (!display) {
5100 		error("DISPLAY not set.");
5101 		return -1;
5102 	}
5103 	/*
5104 	 * Now we decode the value of the DISPLAY variable and make a
5105 	 * connection to the real X server.
5106 	 */
5107 
5108 #ifdef __APPLE__
5109 	/* Check if display is a path to a socket (as set by launchd). */
5110 	{
5111 		char path[PATH_MAX];
5112 
5113 		if (is_path_to_xsocket(display, path, sizeof(path))) {
5114 			debug("x11_connect_display: $DISPLAY is launchd");
5115 
5116 			/* Create a socket. */
5117 			sock = connect_local_xsocket_path(path);
5118 			if (sock < 0)
5119 				return -1;
5120 
5121 			/* OK, we now have a connection to the display. */
5122 			return sock;
5123 		}
5124 	}
5125 #endif
5126 	/*
5127 	 * Check if it is a unix domain socket.  Unix domain displays are in
5128 	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
5129 	 */
5130 	if (strncmp(display, "unix:", 5) == 0 ||
5131 	    display[0] == ':') {
5132 		/* Connect to the unix domain socket. */
5133 		if (sscanf(strrchr(display, ':') + 1, "%u",
5134 		    &display_number) != 1) {
5135 			error("Could not parse display number from DISPLAY: "
5136 			    "%.100s", display);
5137 			return -1;
5138 		}
5139 		/* Create a socket. */
5140 		sock = connect_local_xsocket(display_number);
5141 		if (sock < 0)
5142 			return -1;
5143 
5144 		/* OK, we now have a connection to the display. */
5145 		return sock;
5146 	}
5147 	/*
5148 	 * Connect to an inet socket.  The DISPLAY value is supposedly
5149 	 * hostname:d[.s], where hostname may also be numeric IP address.
5150 	 */
5151 	strlcpy(buf, display, sizeof(buf));
5152 	cp = strchr(buf, ':');
5153 	if (!cp) {
5154 		error("Could not find ':' in DISPLAY: %.100s", display);
5155 		return -1;
5156 	}
5157 	*cp = 0;
5158 	/*
5159 	 * buf now contains the host name.  But first we parse the
5160 	 * display number.
5161 	 */
5162 	if (sscanf(cp + 1, "%u", &display_number) != 1) {
5163 		error("Could not parse display number from DISPLAY: %.100s",
5164 		    display);
5165 		return -1;
5166 	}
5167 
5168 	/* Look up the host address */
5169 	memset(&hints, 0, sizeof(hints));
5170 	hints.ai_family = ssh->chanctxt->IPv4or6;
5171 	hints.ai_socktype = SOCK_STREAM;
5172 	snprintf(strport, sizeof strport, "%u", 6000 + display_number);
5173 	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
5174 		error("%.100s: unknown host. (%s)", buf,
5175 		ssh_gai_strerror(gaierr));
5176 		return -1;
5177 	}
5178 	for (ai = aitop; ai; ai = ai->ai_next) {
5179 		/* Create a socket. */
5180 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
5181 		if (sock == -1) {
5182 			debug2("socket: %.100s", strerror(errno));
5183 			continue;
5184 		}
5185 		/* Connect it to the display. */
5186 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
5187 			debug2("connect %.100s port %u: %.100s", buf,
5188 			    6000 + display_number, strerror(errno));
5189 			close(sock);
5190 			continue;
5191 		}
5192 		/* Success */
5193 		break;
5194 	}
5195 	freeaddrinfo(aitop);
5196 	if (!ai) {
5197 		error("connect %.100s port %u: %.100s", buf,
5198 		    6000 + display_number, strerror(errno));
5199 		return -1;
5200 	}
5201 	set_nodelay(sock);
5202 	return sock;
5203 }
5204 
5205 /*
5206  * Requests forwarding of X11 connections, generates fake authentication
5207  * data, and enables authentication spoofing.
5208  * This should be called in the client only.
5209  */
5210 void
5211 x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
5212     const char *disp, const char *proto, const char *data, int want_reply)
5213 {
5214 	struct ssh_channels *sc = ssh->chanctxt;
5215 	u_int data_len = (u_int) strlen(data) / 2;
5216 	u_int i, value;
5217 	const char *cp;
5218 	char *new_data;
5219 	int r, screen_number;
5220 
5221 	if (sc->x11_saved_display == NULL)
5222 		sc->x11_saved_display = xstrdup(disp);
5223 	else if (strcmp(disp, sc->x11_saved_display) != 0) {
5224 		error("x11_request_forwarding_with_spoofing: different "
5225 		    "$DISPLAY already forwarded");
5226 		return;
5227 	}
5228 
5229 	cp = strchr(disp, ':');
5230 	if (cp)
5231 		cp = strchr(cp, '.');
5232 	if (cp)
5233 		screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
5234 	else
5235 		screen_number = 0;
5236 
5237 	if (sc->x11_saved_proto == NULL) {
5238 		/* Save protocol name. */
5239 		sc->x11_saved_proto = xstrdup(proto);
5240 
5241 		/* Extract real authentication data. */
5242 		sc->x11_saved_data = xmalloc(data_len);
5243 		for (i = 0; i < data_len; i++) {
5244 			if (sscanf(data + 2 * i, "%2x", &value) != 1) {
5245 				fatal("x11_request_forwarding: bad "
5246 				    "authentication data: %.100s", data);
5247 			}
5248 			sc->x11_saved_data[i] = value;
5249 		}
5250 		sc->x11_saved_data_len = data_len;
5251 
5252 		/* Generate fake data of the same length. */
5253 		sc->x11_fake_data = xmalloc(data_len);
5254 		arc4random_buf(sc->x11_fake_data, data_len);
5255 		sc->x11_fake_data_len = data_len;
5256 	}
5257 
5258 	/* Convert the fake data into hex. */
5259 	new_data = tohex(sc->x11_fake_data, data_len);
5260 
5261 	/* Send the request packet. */
5262 	channel_request_start(ssh, client_session_id, "x11-req", want_reply);
5263 	if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
5264 	    (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
5265 	    (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
5266 	    (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
5267 	    (r = sshpkt_send(ssh)) != 0 ||
5268 	    (r = ssh_packet_write_wait(ssh)) != 0)
5269 		fatal_fr(r, "send x11-req");
5270 	free(new_data);
5271 }
5272