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