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