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