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