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