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