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