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