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