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