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