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