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