xref: /titanic_44/usr/src/cmd/ssh/libssh/common/channels.c (revision 1f03f0496b37f42bc76df041144b1cf7e47fcda4)
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 2009 Sun Microsystems, Inc.  All rights reserved.
42  * Use is subject to license terms.
43  */
44 
45 #include "includes.h"
46 RCSID("$OpenBSD: channels.c,v 1.183 2002/09/17 07:47:02 itojun Exp $");
47 
48 #include "ssh.h"
49 #include "ssh1.h"
50 #include "ssh2.h"
51 #include "packet.h"
52 #include "xmalloc.h"
53 #include "log.h"
54 #include "misc.h"
55 #include "channels.h"
56 #include "compat.h"
57 #include "canohost.h"
58 #include "key.h"
59 #include "authfd.h"
60 #include "pathnames.h"
61 #include "bufaux.h"
62 
63 
64 /* -- channel core */
65 
66 /*
67  * Pointer to an array containing all allocated channels.  The array is
68  * dynamically extended as needed.
69  */
70 static Channel **channels = NULL;
71 
72 /*
73  * Size of the channel array.  All slots of the array must always be
74  * initialized (at least the type field); unused slots set to NULL
75  */
76 static int channels_alloc = 0;
77 
78 /*
79  * Maximum file descriptor value used in any of the channels.  This is
80  * updated in channel_new.
81  */
82 static int channel_max_fd = 0;
83 
84 
85 /* -- tcp forwarding */
86 
87 /*
88  * Data structure for storing which hosts are permitted for forward requests.
89  * The local sides of any remote forwards are stored in this array to prevent
90  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
91  * network (which might be behind a firewall).
92  */
93 typedef struct {
94 	char *host_to_connect;		/* Connect to 'host'. */
95 	u_short port_to_connect;	/* Connect to 'port'. */
96 	u_short listen_port;		/* Remote side should listen port number. */
97 } ForwardPermission;
98 
99 /* List of all permitted host/port pairs to connect. */
100 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
101 
102 /* Number of permitted host/port pairs in the array. */
103 static int num_permitted_opens = 0;
104 /*
105  * If this is true, all opens are permitted.  This is the case on the server
106  * on which we have to trust the client anyway, and the user could do
107  * anything after logging in anyway.
108  */
109 static int all_opens_permitted = 0;
110 
111 
112 /* -- X11 forwarding */
113 
114 /* Maximum number of fake X11 displays to try. */
115 #define MAX_DISPLAYS  1000
116 
117 /* Saved X11 authentication protocol name. */
118 static char *x11_saved_proto = NULL;
119 
120 /* Saved X11 authentication data.  This is the real data. */
121 static char *x11_saved_data = NULL;
122 static u_int x11_saved_data_len = 0;
123 
124 /*
125  * Fake X11 authentication data.  This is what the server will be sending us;
126  * we should replace any occurrences of this by the real data.
127  */
128 static u_char *x11_fake_data = NULL;
129 static u_int x11_fake_data_len;
130 
131 
132 /* -- agent forwarding */
133 
134 #define	NUM_SOCKS	10
135 
136 /* AF_UNSPEC or AF_INET or AF_INET6 */
137 static int IPv4or6 = AF_UNSPEC;
138 
139 /* helper */
140 static void port_open_helper(Channel *c, char *rtype);
141 
142 /* -- channel core */
143 
144 Channel *
145 channel_lookup(int id)
146 {
147 	Channel *c;
148 
149 	if (id < 0 || id >= channels_alloc) {
150 		log("channel_lookup: %d: bad id", id);
151 		return NULL;
152 	}
153 	c = channels[id];
154 	if (c == NULL) {
155 		log("channel_lookup: %d: bad id: channel free", id);
156 		return NULL;
157 	}
158 	return c;
159 }
160 
161 /*
162  * Register filedescriptors for a channel, used when allocating a channel or
163  * when the channel consumer/producer is ready, e.g. shell exec'd
164  */
165 
166 static void
167 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
168     int extusage, int nonblock)
169 {
170 	/* Update the maximum file descriptor value. */
171 	channel_max_fd = MAX(channel_max_fd, rfd);
172 	channel_max_fd = MAX(channel_max_fd, wfd);
173 	channel_max_fd = MAX(channel_max_fd, efd);
174 
175 	/* XXX set close-on-exec -markus */
176 
177 	c->rfd = rfd;
178 	c->wfd = wfd;
179 	c->sock = (rfd == wfd) ? rfd : -1;
180 	c->efd = efd;
181 	c->extended_usage = extusage;
182 
183 	/* XXX ugly hack: nonblock is only set by the server */
184 	if (nonblock && isatty(c->rfd)) {
185 		debug("channel %d: rfd %d isatty", c->self, c->rfd);
186 		c->isatty = 1;
187 		if (!isatty(c->wfd)) {
188 			error("channel %d: wfd %d is not a tty?",
189 			    c->self, c->wfd);
190 		}
191 	} else {
192 		c->isatty = 0;
193 	}
194 	c->wfd_isatty = isatty(c->wfd);
195 
196 	/* enable nonblocking mode */
197 	if (nonblock) {
198 		if (rfd != -1)
199 			set_nonblock(rfd);
200 		if (wfd != -1)
201 			set_nonblock(wfd);
202 		if (efd != -1)
203 			set_nonblock(efd);
204 	}
205 }
206 
207 /*
208  * Allocate a new channel object and set its type and socket. This will cause
209  * remote_name to be freed.
210  */
211 
212 Channel *
213 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
214     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
215 {
216 	int i, found;
217 	Channel *c;
218 
219 	/* Do initial allocation if this is the first call. */
220 	if (channels_alloc == 0) {
221 		channels_alloc = 10;
222 		channels = xmalloc(channels_alloc * sizeof(Channel *));
223 		for (i = 0; i < channels_alloc; i++)
224 			channels[i] = NULL;
225 		fatal_add_cleanup((void (*) (void *)) channel_free_all, NULL);
226 	}
227 	/* Try to find a free slot where to put the new channel. */
228 	for (found = -1, i = 0; i < channels_alloc; i++)
229 		if (channels[i] == NULL) {
230 			/* Found a free slot. */
231 			found = i;
232 			break;
233 		}
234 	if (found == -1) {
235 		/* There are no free slots.  Take last+1 slot and expand the array.  */
236 		found = channels_alloc;
237 		if (channels_alloc > 10000)
238 			fatal("channel_new: internal error: channels_alloc %d "
239 			    "too big.", channels_alloc);
240 		channels = xrealloc(channels,
241 		    (channels_alloc + 10) * sizeof(Channel *));
242 		channels_alloc += 10;
243 		debug2("channel: expanding %d", channels_alloc);
244 		for (i = found; i < channels_alloc; i++)
245 			channels[i] = NULL;
246 	}
247 	/* Initialize and return new channel. */
248 	c = channels[found] = xmalloc(sizeof(Channel));
249 	memset(c, 0, sizeof(Channel));
250 	buffer_init(&c->input);
251 	buffer_init(&c->output);
252 	buffer_init(&c->extended);
253 	c->ostate = CHAN_OUTPUT_OPEN;
254 	c->istate = CHAN_INPUT_OPEN;
255 	c->flags = 0;
256 	channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
257 	c->self = found;
258 	c->type = type;
259 	c->ctype = ctype;
260 	c->local_window = window;
261 	c->local_window_max = window;
262 	c->local_consumed = 0;
263 	c->local_maxpacket = maxpack;
264 	c->remote_id = -1;
265 	c->remote_name = remote_name;
266 	c->remote_window = 0;
267 	c->remote_maxpacket = 0;
268 	c->force_drain = 0;
269 	c->single_connection = 0;
270 	c->detach_user = NULL;
271 	c->confirm = NULL;
272 	c->input_filter = NULL;
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 	if (c == NULL) {
602 		log("channel_request_start: %d: unknown channel id", local_id);
603 		return;
604 	}
605 	debug("channel request %d: %s", local_id, service) ;
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 		FD_SET(c->rfd, readset);
728 	if (c->ostate == CHAN_OUTPUT_OPEN ||
729 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
730 		if (buffer_len(&c->output) > 0) {
731 			FD_SET(c->wfd, writeset);
732 		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
733 			if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
734 			       debug2("channel %d: obuf_empty delayed efd %d/(%d)",
735 				   c->self, c->efd, buffer_len(&c->extended));
736 			else
737 				chan_obuf_empty(c);
738 		}
739 	}
740 	/** XXX check close conditions, too */
741 	if (compat20 && c->efd != -1) {
742 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
743 		    buffer_len(&c->extended) > 0)
744 			FD_SET(c->efd, writeset);
745 		else if (!(c->flags & CHAN_EOF_SENT) &&
746 		    c->extended_usage == CHAN_EXTENDED_READ &&
747 		    buffer_len(&c->extended) < c->remote_window)
748 			FD_SET(c->efd, readset);
749 	}
750 }
751 
752 static void
753 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
754 {
755 	if (buffer_len(&c->input) == 0) {
756 		packet_start(SSH_MSG_CHANNEL_CLOSE);
757 		packet_put_int(c->remote_id);
758 		packet_send();
759 		c->type = SSH_CHANNEL_CLOSED;
760 		debug("channel %d: closing after input drain.", c->self);
761 	}
762 }
763 
764 static void
765 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
766 {
767 	if (buffer_len(&c->output) == 0)
768 		chan_mark_dead(c);
769 	else
770 		FD_SET(c->sock, writeset);
771 }
772 
773 /*
774  * This is a special state for X11 authentication spoofing.  An opened X11
775  * connection (when authentication spoofing is being done) remains in this
776  * state until the first packet has been completely read.  The authentication
777  * data in that packet is then substituted by the real data if it matches the
778  * fake data, and the channel is put into normal mode.
779  * XXX All this happens at the client side.
780  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
781  */
782 static int
783 x11_open_helper(Buffer *b)
784 {
785 	u_char *ucp;
786 	u_int proto_len, data_len;
787 
788 	/* Check if the fixed size part of the packet is in buffer. */
789 	if (buffer_len(b) < 12)
790 		return 0;
791 
792 	/* Parse the lengths of variable-length fields. */
793 	ucp = buffer_ptr(b);
794 	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
795 		proto_len = 256 * ucp[6] + ucp[7];
796 		data_len = 256 * ucp[8] + ucp[9];
797 	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
798 		proto_len = ucp[6] + 256 * ucp[7];
799 		data_len = ucp[8] + 256 * ucp[9];
800 	} else {
801 		debug("Initial X11 packet contains bad byte order byte: 0x%x",
802 		    ucp[0]);
803 		return -1;
804 	}
805 
806 	/* Check if the whole packet is in buffer. */
807 	if (buffer_len(b) <
808 	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
809 		return 0;
810 
811 	/* Check if authentication protocol matches. */
812 	if (proto_len != strlen(x11_saved_proto) ||
813 	    memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
814 		debug("X11 connection uses different authentication protocol.");
815 		return -1;
816 	}
817 	/* Check if authentication data matches our fake data. */
818 	if (data_len != x11_fake_data_len ||
819 	    memcmp(ucp + 12 + ((proto_len + 3) & ~3),
820 		x11_fake_data, x11_fake_data_len) != 0) {
821 		debug("X11 auth data does not match fake data.");
822 		return -1;
823 	}
824 	/* Check fake data length */
825 	if (x11_fake_data_len != x11_saved_data_len) {
826 		error("X11 fake_data_len %d != saved_data_len %d",
827 		    x11_fake_data_len, x11_saved_data_len);
828 		return -1;
829 	}
830 	/*
831 	 * Received authentication protocol and data match
832 	 * our fake data. Substitute the fake data with real
833 	 * data.
834 	 */
835 	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
836 	    x11_saved_data, x11_saved_data_len);
837 	return 1;
838 }
839 
840 static void
841 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
842 {
843 	int ret = x11_open_helper(&c->output);
844 
845 	if (ret == 1) {
846 		/* Start normal processing for the channel. */
847 		c->type = SSH_CHANNEL_OPEN;
848 		channel_pre_open_13(c, readset, writeset);
849 	} else if (ret == -1) {
850 		/*
851 		 * We have received an X11 connection that has bad
852 		 * authentication information.
853 		 */
854 		log("X11 connection rejected because of wrong authentication.");
855 		buffer_clear(&c->input);
856 		buffer_clear(&c->output);
857 		channel_close_fd(&c->sock);
858 		c->sock = -1;
859 		c->type = SSH_CHANNEL_CLOSED;
860 		packet_start(SSH_MSG_CHANNEL_CLOSE);
861 		packet_put_int(c->remote_id);
862 		packet_send();
863 	}
864 }
865 
866 static void
867 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
868 {
869 	int ret = x11_open_helper(&c->output);
870 
871 	/* c->force_drain = 1; */
872 
873 	if (ret == 1) {
874 		c->type = SSH_CHANNEL_OPEN;
875 		channel_pre_open(c, readset, writeset);
876 	} else if (ret == -1) {
877 		log("X11 connection rejected because of wrong authentication.");
878 		debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
879 		chan_read_failed(c);
880 		buffer_clear(&c->input);
881 		chan_ibuf_empty(c);
882 		buffer_clear(&c->output);
883 		/* for proto v1, the peer will send an IEOF */
884 		if (compat20)
885 			chan_write_failed(c);
886 		else
887 			c->type = SSH_CHANNEL_OPEN;
888 		debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
889 	}
890 }
891 
892 /* try to decode a socks4 header */
893 static int
894 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
895 {
896 	char *p, *host;
897 	int len, have, i, found;
898 	char username[256];
899 	struct {
900 		u_int8_t version;
901 		u_int8_t command;
902 		u_int16_t dest_port;
903 		struct in_addr dest_addr;
904 	} s4_req, s4_rsp;
905 
906 	debug2("channel %d: decode socks4", c->self);
907 
908 	have = buffer_len(&c->input);
909 	len = sizeof(s4_req);
910 	if (have < len)
911 		return 0;
912 	p = buffer_ptr(&c->input);
913 	for (found = 0, i = len; i < have; i++) {
914 		if (p[i] == '\0') {
915 			found = 1;
916 			break;
917 		}
918 		if (i > 1024) {
919 			/* the peer is probably sending garbage */
920 			debug("channel %d: decode socks4: too long",
921 			    c->self);
922 			return -1;
923 		}
924 	}
925 	if (!found)
926 		return 0;
927 	buffer_get(&c->input, (char *)&s4_req.version, 1);
928 	buffer_get(&c->input, (char *)&s4_req.command, 1);
929 	buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
930 	buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
931 	have = buffer_len(&c->input);
932 	p = buffer_ptr(&c->input);
933 	len = strlen(p);
934 	debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
935 	if (len > have)
936 		fatal("channel %d: decode socks4: len %d > have %d",
937 		    c->self, len, have);
938 	strlcpy(username, p, sizeof(username));
939 	buffer_consume(&c->input, len);
940 	buffer_consume(&c->input, 1);		/* trailing '\0' */
941 
942 	host = inet_ntoa(s4_req.dest_addr);
943 	strlcpy(c->path, host, sizeof(c->path));
944 	c->host_port = ntohs(s4_req.dest_port);
945 
946 	debug("channel %d: dynamic request: socks4 host %s port %u command %u",
947 	    c->self, host, c->host_port, s4_req.command);
948 
949 	if (s4_req.command != 1) {
950 		debug("channel %d: cannot handle: socks4 cn %d",
951 		    c->self, s4_req.command);
952 		return -1;
953 	}
954 	s4_rsp.version = 0;			/* vn: 0 for reply */
955 	s4_rsp.command = 90;			/* cd: req granted */
956 	s4_rsp.dest_port = 0;			/* ignored */
957 	s4_rsp.dest_addr.s_addr = INADDR_ANY;	/* ignored */
958 	buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
959 	return 1;
960 }
961 
962 /* try to decode a socks5 header */
963 #define SSH_SOCKS5_AUTHDONE	0x1000
964 #define SSH_SOCKS5_NOAUTH	0x00
965 #define SSH_SOCKS5_IPV4		0x01
966 #define SSH_SOCKS5_DOMAIN	0x03
967 #define SSH_SOCKS5_IPV6		0x04
968 #define SSH_SOCKS5_CONNECT	0x01
969 #define SSH_SOCKS5_SUCCESS	0x00
970 
971 /* ARGSUSED */
972 static int
973 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
974 {
975 	struct {
976 		u_int8_t version;
977 		u_int8_t command;
978 		u_int8_t reserved;
979 		u_int8_t atyp;
980 	} s5_req, s5_rsp;
981 	u_int16_t dest_port;
982 	u_char *p, dest_addr[255+1];
983 	u_int have, need, i, found, nmethods, addrlen;
984 	struct in_addr bnd_addr;
985 	int af;
986 
987 	debug2("channel %d: decode socks5", c->self);
988 	p = buffer_ptr(&c->input);
989 	if (p[0] != 0x05)
990 		return -1;
991 	have = buffer_len(&c->input);
992 	if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
993 		/* format: ver | nmethods | methods */
994 		if (have < 2)
995 			return 0;
996 		nmethods = p[1];
997 		if (have < nmethods + 2)
998 			return 0;
999 		/* look for method: "NO AUTHENTICATION REQUIRED" */
1000 		for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1001 			if (p[i] == SSH_SOCKS5_NOAUTH) {
1002 				found = 1;
1003 				break;
1004 			}
1005 		}
1006 		if (!found) {
1007 			error("channel %d: socks5 authentication methods not implemented",
1008 			    c->self);
1009 			error("channel %d: forwarding failed: "
1010 			    "SSH_SOCKS5_NOAUTH method not found", c->self);
1011 			return -1;
1012 		}
1013 		buffer_consume(&c->input, nmethods + 2);
1014 		buffer_put_char(&c->output, 0x05);		/* version */
1015 		buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH);	/* method */
1016 		FD_SET(c->sock, writeset);
1017 		c->flags |= SSH_SOCKS5_AUTHDONE;
1018 		debug2("channel %d: socks5 auth done", c->self);
1019 		return 0;				/* need more */
1020 	}
1021 	debug2("channel %d: socks5 post auth", c->self);
1022 	if (have < sizeof(s5_req)+1)
1023 		return 0;			/* need more */
1024 	memcpy(&s5_req, p, sizeof(s5_req));
1025 	if (s5_req.version != 0x05 ||
1026 	    s5_req.command != SSH_SOCKS5_CONNECT ||
1027 	    s5_req.reserved != 0x00) {
1028 		error("channel %d: forwarding failed: "
1029 		    "only socks5 connect is supported", c->self);
1030 		return -1;
1031 	}
1032 	switch (s5_req.atyp){
1033 	case SSH_SOCKS5_IPV4:
1034 		addrlen = 4;
1035 		af = AF_INET;
1036 		break;
1037 	case SSH_SOCKS5_DOMAIN:
1038 		addrlen = p[sizeof(s5_req)];
1039 		af = -1;
1040 		break;
1041 	case SSH_SOCKS5_IPV6:
1042 		addrlen = 16;
1043 		af = AF_INET6;
1044 		break;
1045 	default:
1046 		error("channel %d: forwarding failed: "
1047 		    "bad socks5 atyp %d", c->self, s5_req.atyp);
1048 		return -1;
1049 	}
1050 	need = sizeof(s5_req) + addrlen + 2;
1051 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1052 		need++;
1053 	if (have < need)
1054 		return 0;
1055 	buffer_consume(&c->input, sizeof(s5_req));
1056 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1057 		buffer_consume(&c->input, 1);    /* host string length */
1058 	buffer_get(&c->input, (char *)&dest_addr, addrlen);
1059 	buffer_get(&c->input, (char *)&dest_port, 2);
1060 	dest_addr[addrlen] = '\0';
1061 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1062 		strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1063 	else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1064 		return -1;
1065 	c->host_port = ntohs(dest_port);
1066 
1067 	debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1068 	    c->self, c->path, c->host_port, s5_req.command);
1069 
1070 	s5_rsp.version = 0x05;
1071 	s5_rsp.command = SSH_SOCKS5_SUCCESS;
1072 	s5_rsp.reserved = 0;			/* ignored */
1073 	s5_rsp.atyp = SSH_SOCKS5_IPV4;
1074 	bzero(&bnd_addr, sizeof(bnd_addr));
1075 	bnd_addr.s_addr = htonl(INADDR_ANY);
1076 	dest_port = 0;				/* ignored */
1077 
1078 	buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1079 	buffer_append(&c->output, &bnd_addr, sizeof(struct in_addr));
1080 	buffer_append(&c->output, &dest_port, sizeof(dest_port));
1081 	return 1;
1082 }
1083 
1084 /* dynamic port forwarding */
1085 static void
1086 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
1087 {
1088 	u_char *p;
1089 	int have, ret;
1090 
1091 	have = buffer_len(&c->input);
1092 	c->delayed = 0;
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 			/*
1287 			 * do not call the channel_post handler until
1288 			 * this flag has been reset by a pre-handler.
1289 			 * otherwise the FD_ISSET calls might overflow
1290 			 */
1291 			nc->delayed = 1;
1292 		} else {
1293 			port_open_helper(nc, rtype);
1294 		}
1295 	}
1296 }
1297 
1298 /*
1299  * This is the authentication agent socket listening for connections from
1300  * clients.
1301  */
1302 static void
1303 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
1304 {
1305 	Channel *nc;
1306 	char *name;
1307 	int newsock;
1308 	struct sockaddr addr;
1309 	socklen_t addrlen;
1310 
1311 	if (FD_ISSET(c->sock, readset)) {
1312 		addrlen = sizeof(addr);
1313 		newsock = accept(c->sock, &addr, &addrlen);
1314 		if (newsock < 0) {
1315 			error("accept from auth socket: %.100s", strerror(errno));
1316 			return;
1317 		}
1318 		name = xstrdup("accepted auth socket");
1319 		nc = channel_new("accepted auth socket",
1320 		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1321 		    c->local_window_max, c->local_maxpacket,
1322 		    0, name, 1);
1323 		if (compat20) {
1324 			packet_start(SSH2_MSG_CHANNEL_OPEN);
1325 			packet_put_cstring("auth-agent@openssh.com");
1326 			packet_put_int(nc->self);
1327 			packet_put_int(c->local_window_max);
1328 			packet_put_int(c->local_maxpacket);
1329 		} else {
1330 			packet_start(SSH_SMSG_AGENT_OPEN);
1331 			packet_put_int(nc->self);
1332 		}
1333 		packet_send();
1334 	}
1335 }
1336 
1337 static void
1338 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
1339 {
1340 	int err = 0;
1341 	socklen_t sz = sizeof(err);
1342 
1343 	if (FD_ISSET(c->sock, writeset)) {
1344 		if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1345 			err = errno;
1346 			error("getsockopt SO_ERROR failed");
1347 		}
1348 		if (err == 0) {
1349 			debug("channel %d: connected", c->self);
1350 			c->type = SSH_CHANNEL_OPEN;
1351 			if (compat20) {
1352 				packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1353 				packet_put_int(c->remote_id);
1354 				packet_put_int(c->self);
1355 				packet_put_int(c->local_window);
1356 				packet_put_int(c->local_maxpacket);
1357 			} else {
1358 				packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1359 				packet_put_int(c->remote_id);
1360 				packet_put_int(c->self);
1361 			}
1362 		} else {
1363 			debug("channel %d: not connected: %s",
1364 			    c->self, strerror(err));
1365 			if (compat20) {
1366 				packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1367 				packet_put_int(c->remote_id);
1368 				packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1369 				if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1370 					packet_put_utf8_cstring(strerror(err));
1371 					packet_put_cstring("");
1372 				}
1373 			} else {
1374 				packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1375 				packet_put_int(c->remote_id);
1376 			}
1377 			chan_mark_dead(c);
1378 		}
1379 		packet_send();
1380 	}
1381 }
1382 
1383 static int
1384 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
1385 {
1386 	char buf[16*1024];
1387 	int len;
1388 
1389 	if (c->rfd != -1 &&
1390 	    FD_ISSET(c->rfd, readset)) {
1391 		len = read(c->rfd, buf, sizeof(buf));
1392 		if (len < 0 && (errno == EINTR || errno == EAGAIN))
1393 			return 1;
1394 		if (len <= 0) {
1395 			debug("channel %d: read<=0 rfd %d len %d",
1396 			    c->self, c->rfd, len);
1397 			if (c->type != SSH_CHANNEL_OPEN) {
1398 				debug("channel %d: not open", c->self);
1399 				chan_mark_dead(c);
1400 				return -1;
1401 			} else if (compat13) {
1402 				buffer_clear(&c->output);
1403 				c->type = SSH_CHANNEL_INPUT_DRAINING;
1404 				debug("channel %d: input draining.", c->self);
1405 			} else {
1406 				chan_read_failed(c);
1407 			}
1408 			return -1;
1409 		}
1410 		if (c->input_filter != NULL) {
1411 			if (c->input_filter(c, buf, len) == -1) {
1412 				debug("channel %d: filter stops", c->self);
1413 				chan_read_failed(c);
1414 			}
1415 		} else {
1416 			buffer_append(&c->input, buf, len);
1417 		}
1418 	}
1419 	return 1;
1420 }
1421 static int
1422 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
1423 {
1424 	struct termios tio;
1425 	u_char *data;
1426 	u_int dlen;
1427 	int len;
1428 
1429 	/* Send buffered output data to the socket. */
1430 	if (c->wfd != -1 &&
1431 	    FD_ISSET(c->wfd, writeset) &&
1432 	    buffer_len(&c->output) > 0) {
1433 		data = buffer_ptr(&c->output);
1434 		dlen = buffer_len(&c->output);
1435 #ifdef _AIX
1436 		/* XXX: Later AIX versions can't push as much data to tty */
1437 		if (compat20 && c->wfd_isatty && dlen > 8*1024)
1438 			dlen = 8*1024;
1439 #endif
1440 		len = write(c->wfd, data, dlen);
1441 		if (len < 0 && (errno == EINTR || errno == EAGAIN))
1442 			return 1;
1443 		if (len <= 0) {
1444 			if (c->type != SSH_CHANNEL_OPEN) {
1445 				debug("channel %d: not open", c->self);
1446 				chan_mark_dead(c);
1447 				return -1;
1448 			} else if (compat13) {
1449 				buffer_clear(&c->output);
1450 				debug("channel %d: input draining.", c->self);
1451 				c->type = SSH_CHANNEL_INPUT_DRAINING;
1452 			} else {
1453 				chan_write_failed(c);
1454 			}
1455 			return -1;
1456 		}
1457 		if (compat20 && c->isatty && dlen >= 1 && data[0] != '\r') {
1458 			if (tcgetattr(c->wfd, &tio) == 0 &&
1459 			    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1460 				/*
1461 				 * Simulate echo to reduce the impact of
1462 				 * traffic analysis. We need to match the
1463 				 * size of a SSH2_MSG_CHANNEL_DATA message
1464 				 * (4 byte channel id + data)
1465 				 */
1466 				packet_send_ignore(4 + len);
1467 				packet_send();
1468 			}
1469 		}
1470 		buffer_consume(&c->output, len);
1471 		if (compat20 && len > 0) {
1472 			c->local_consumed += len;
1473 		}
1474 	}
1475 	return 1;
1476 }
1477 static int
1478 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
1479 {
1480 	char buf[16*1024];
1481 	int len;
1482 
1483 /** XXX handle drain efd, too */
1484 	if (c->efd != -1) {
1485 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1486 		    FD_ISSET(c->efd, writeset) &&
1487 		    buffer_len(&c->extended) > 0) {
1488 			len = write(c->efd, buffer_ptr(&c->extended),
1489 			    buffer_len(&c->extended));
1490 			debug2("channel %d: written %d to efd %d",
1491 			    c->self, len, c->efd);
1492 			if (len < 0 && (errno == EINTR || errno == EAGAIN))
1493 				return 1;
1494 			if (len <= 0) {
1495 				debug2("channel %d: closing write-efd %d",
1496 				    c->self, c->efd);
1497 				channel_close_fd(&c->efd);
1498 			} else {
1499 				buffer_consume(&c->extended, len);
1500 				c->local_consumed += len;
1501 			}
1502 		} else if (c->extended_usage == CHAN_EXTENDED_READ &&
1503 		    FD_ISSET(c->efd, readset)) {
1504 			len = read(c->efd, buf, sizeof(buf));
1505 			debug2("channel %d: read %d from efd %d",
1506 			    c->self, len, c->efd);
1507 			if (len < 0 && (errno == EINTR || errno == EAGAIN))
1508 				return 1;
1509 			if (len <= 0) {
1510 				debug2("channel %d: closing read-efd %d",
1511 				    c->self, c->efd);
1512 				channel_close_fd(&c->efd);
1513 			} else {
1514 				buffer_append(&c->extended, buf, len);
1515 			}
1516 		}
1517 	}
1518 	return 1;
1519 }
1520 static int
1521 channel_check_window(Channel *c)
1522 {
1523 	if (c->type == SSH_CHANNEL_OPEN &&
1524 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1525 	    c->local_window < c->local_window_max/2 &&
1526 	    c->local_consumed > 0) {
1527 		packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1528 		packet_put_int(c->remote_id);
1529 		packet_put_int(c->local_consumed);
1530 		packet_send();
1531 		debug2("channel %d: window %d sent adjust %d",
1532 		    c->self, c->local_window,
1533 		    c->local_consumed);
1534 		c->local_window += c->local_consumed;
1535 		c->local_consumed = 0;
1536 	}
1537 	return 1;
1538 }
1539 
1540 static void
1541 channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1542 {
1543 	if (c->delayed)
1544 		return;
1545 	channel_handle_rfd(c, readset, writeset);
1546 	channel_handle_wfd(c, readset, writeset);
1547 	if (!compat20)
1548 		return;
1549 	channel_handle_efd(c, readset, writeset);
1550 	channel_check_window(c);
1551 }
1552 
1553 static void
1554 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1555 {
1556 	int len;
1557 
1558 	/* Send buffered output data to the socket. */
1559 	if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1560 		len = write(c->sock, buffer_ptr(&c->output),
1561 			    buffer_len(&c->output));
1562 		if (len <= 0)
1563 			buffer_clear(&c->output);
1564 		else
1565 			buffer_consume(&c->output, len);
1566 	}
1567 }
1568 
1569 static void
1570 channel_handler_init_20(void)
1571 {
1572 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
1573 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
1574 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1575 	channel_pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
1576 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1577 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1578 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1579 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1580 
1581 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open;
1582 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1583 	channel_post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
1584 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1585 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1586 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1587 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
1588 }
1589 
1590 static void
1591 channel_handler_init_13(void)
1592 {
1593 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_13;
1594 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open_13;
1595 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1596 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1597 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1598 	channel_pre[SSH_CHANNEL_INPUT_DRAINING] =	&channel_pre_input_draining;
1599 	channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_pre_output_draining;
1600 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1601 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1602 
1603 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open;
1604 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1605 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1606 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1607 	channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_post_output_drain_13;
1608 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1609 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
1610 }
1611 
1612 static void
1613 channel_handler_init_15(void)
1614 {
1615 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
1616 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
1617 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1618 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1619 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1620 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1621 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1622 
1623 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1624 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1625 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1626 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open;
1627 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1628 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
1629 }
1630 
1631 static void
1632 channel_handler_init(void)
1633 {
1634 	int i;
1635 
1636 	for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1637 		channel_pre[i] = NULL;
1638 		channel_post[i] = NULL;
1639 	}
1640 	if (compat20)
1641 		channel_handler_init_20();
1642 	else if (compat13)
1643 		channel_handler_init_13();
1644 	else
1645 		channel_handler_init_15();
1646 }
1647 
1648 /* gc dead channels */
1649 static void
1650 channel_garbage_collect(Channel *c)
1651 {
1652 	if (c == NULL)
1653 		return;
1654 	if (c->detach_user != NULL) {
1655 		if (!chan_is_dead(c, 0))
1656 			return;
1657 		debug("channel %d: gc: notify user", c->self);
1658 		c->detach_user(c->self, NULL);
1659 		/* if we still have a callback */
1660 		if (c->detach_user != NULL)
1661 			return;
1662 		debug("channel %d: gc: user detached", c->self);
1663 	}
1664 	if (!c->wait_for_exit && !chan_is_dead(c, 1))
1665 		return;
1666 	debug("channel %d: garbage collecting", c->self);
1667 	channel_free(c);
1668 }
1669 
1670 static void
1671 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1672 {
1673 	static int did_init = 0;
1674 	int i;
1675 	Channel *c;
1676 
1677 	if (!did_init) {
1678 		channel_handler_init();
1679 		did_init = 1;
1680 	}
1681 	for (i = 0; i < channels_alloc; i++) {
1682 		c = channels[i];
1683 		if (c == NULL)
1684 			continue;
1685 		if (ftab[c->type] != NULL)
1686 			(*ftab[c->type])(c, readset, writeset);
1687 		channel_garbage_collect(c);
1688 	}
1689 }
1690 
1691 /*
1692  * Allocate/update select bitmasks and add any bits relevant to channels in
1693  * select bitmasks.
1694  */
1695 void
1696 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1697     int *nallocp, int rekeying)
1698 {
1699 	int n;
1700 	u_int sz;
1701 
1702 	n = MAX(*maxfdp, channel_max_fd);
1703 
1704 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1705 	/* perhaps check sz < nalloc/2 and shrink? */
1706 	if (*readsetp == NULL || sz > *nallocp) {
1707 		*readsetp = xrealloc(*readsetp, sz);
1708 		*writesetp = xrealloc(*writesetp, sz);
1709 		*nallocp = sz;
1710 	}
1711 	*maxfdp = n;
1712 	memset(*readsetp, 0, sz);
1713 	memset(*writesetp, 0, sz);
1714 
1715 	if (!rekeying)
1716 		channel_handler(channel_pre, *readsetp, *writesetp);
1717 }
1718 
1719 /*
1720  * After select, perform any appropriate operations for channels which have
1721  * events pending.
1722  */
1723 void
1724 channel_after_select(fd_set * readset, fd_set * writeset)
1725 {
1726 	channel_handler(channel_post, readset, writeset);
1727 }
1728 
1729 
1730 /* If there is data to send to the connection, enqueue some of it now. */
1731 
1732 void
1733 channel_output_poll(void)
1734 {
1735 	Channel *c;
1736 	int i;
1737 	u_int len;
1738 
1739 	for (i = 0; i < channels_alloc; i++) {
1740 		c = channels[i];
1741 		if (c == NULL)
1742 			continue;
1743 
1744 		/*
1745 		 * We are only interested in channels that can have buffered
1746 		 * incoming data.
1747 		 */
1748 		if (compat13) {
1749 			if (c->type != SSH_CHANNEL_OPEN &&
1750 			    c->type != SSH_CHANNEL_INPUT_DRAINING)
1751 				continue;
1752 		} else {
1753 			if (c->type != SSH_CHANNEL_OPEN)
1754 				continue;
1755 		}
1756 		if (compat20 &&
1757 		    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1758 			/* XXX is this true? */
1759 			debug3("channel %d: will not send data after close", c->self);
1760 			continue;
1761 		}
1762 
1763 		/* Get the amount of buffered data for this channel. */
1764 		if ((c->istate == CHAN_INPUT_OPEN ||
1765 		    c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1766 		    (len = buffer_len(&c->input)) > 0) {
1767 			/*
1768 			 * Send some data for the other side over the secure
1769 			 * connection.
1770 			 */
1771 			if (compat20) {
1772 				if (len > c->remote_window)
1773 					len = c->remote_window;
1774 				if (len > c->remote_maxpacket)
1775 					len = c->remote_maxpacket;
1776 			} else {
1777 				if (packet_is_interactive()) {
1778 					if (len > 1024)
1779 						len = 512;
1780 				} else {
1781 					/* Keep the packets at reasonable size. */
1782 					if (len > packet_get_maxsize()/2)
1783 						len = packet_get_maxsize()/2;
1784 				}
1785 			}
1786 			if (len > 0) {
1787 				packet_start(compat20 ?
1788 				    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1789 				packet_put_int(c->remote_id);
1790 				packet_put_string(buffer_ptr(&c->input), len);
1791 				packet_send();
1792 				buffer_consume(&c->input, len);
1793 				c->remote_window -= len;
1794 			}
1795 		} else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1796 			if (compat13)
1797 				fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1798 			/*
1799 			 * input-buffer is empty and read-socket shutdown:
1800 			 * tell peer, that we will not send more data: send IEOF.
1801 			 * hack for extended data: delay EOF if EFD still in use.
1802 			 */
1803 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
1804 			       debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1805 				   c->self, c->efd, buffer_len(&c->extended));
1806 			else
1807 				chan_ibuf_empty(c);
1808 		}
1809 		/* Send extended data, i.e. stderr */
1810 		if (compat20 &&
1811 		    !(c->flags & CHAN_EOF_SENT) &&
1812 		    c->remote_window > 0 &&
1813 		    (len = buffer_len(&c->extended)) > 0 &&
1814 		    c->extended_usage == CHAN_EXTENDED_READ) {
1815 			debug2("channel %d: rwin %u elen %u euse %d",
1816 			    c->self, c->remote_window, buffer_len(&c->extended),
1817 			    c->extended_usage);
1818 			if (len > c->remote_window)
1819 				len = c->remote_window;
1820 			if (len > c->remote_maxpacket)
1821 				len = c->remote_maxpacket;
1822 			packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1823 			packet_put_int(c->remote_id);
1824 			packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1825 			packet_put_string(buffer_ptr(&c->extended), len);
1826 			packet_send();
1827 			buffer_consume(&c->extended, len);
1828 			c->remote_window -= len;
1829 			debug2("channel %d: sent ext data %d", c->self, len);
1830 		}
1831 	}
1832 }
1833 
1834 
1835 /* -- protocol input */
1836 
1837 void
1838 channel_input_data(int type, u_int32_t seq, void *ctxt)
1839 {
1840 	int id;
1841 	char *data;
1842 	u_int data_len;
1843 	Channel *c;
1844 
1845 	/* Get the channel number and verify it. */
1846 	id = packet_get_int();
1847 	c = channel_lookup(id);
1848 	if (c == NULL)
1849 		packet_disconnect("Received data for nonexistent channel %d.", id);
1850 
1851 	/* Ignore any data for non-open channels (might happen on close) */
1852 	if (c->type != SSH_CHANNEL_OPEN &&
1853 	    c->type != SSH_CHANNEL_X11_OPEN)
1854 		return;
1855 
1856 	/* same for protocol 1.5 if output end is no longer open */
1857 	if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1858 		return;
1859 
1860 	/* Get the data. */
1861 	data = packet_get_string(&data_len);
1862 
1863 	if (compat20) {
1864 		if (data_len > c->local_maxpacket) {
1865 			log("channel %d: rcvd big packet %d, maxpack %d",
1866 			    c->self, data_len, c->local_maxpacket);
1867 		}
1868 		if (data_len > c->local_window) {
1869 			log("channel %d: rcvd too much data %d, win %d",
1870 			    c->self, data_len, c->local_window);
1871 			xfree(data);
1872 			return;
1873 		}
1874 		c->local_window -= data_len;
1875 	}
1876 	packet_check_eom();
1877 	buffer_append(&c->output, data, data_len);
1878 	xfree(data);
1879 }
1880 
1881 void
1882 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1883 {
1884 	int id;
1885 	char *data;
1886 	u_int data_len, tcode;
1887 	Channel *c;
1888 
1889 	/* Get the channel number and verify it. */
1890 	id = packet_get_int();
1891 	c = channel_lookup(id);
1892 
1893 	if (c == NULL)
1894 		packet_disconnect("Received extended_data for bad channel %d.", id);
1895 	if (c->type != SSH_CHANNEL_OPEN) {
1896 		log("channel %d: ext data for non open", id);
1897 		return;
1898 	}
1899 	if (c->flags & CHAN_EOF_RCVD) {
1900 		if (datafellows & SSH_BUG_EXTEOF)
1901 			debug("channel %d: accepting ext data after eof", id);
1902 		else
1903 			packet_disconnect("Received extended_data after EOF "
1904 			    "on channel %d.", id);
1905 	}
1906 	tcode = packet_get_int();
1907 	if (c->efd == -1 ||
1908 	    c->extended_usage != CHAN_EXTENDED_WRITE ||
1909 	    tcode != SSH2_EXTENDED_DATA_STDERR) {
1910 		log("channel %d: bad ext data", c->self);
1911 		return;
1912 	}
1913 	data = packet_get_string(&data_len);
1914 	packet_check_eom();
1915 	if (data_len > c->local_window) {
1916 		log("channel %d: rcvd too much extended_data %d, win %d",
1917 		    c->self, data_len, c->local_window);
1918 		xfree(data);
1919 		return;
1920 	}
1921 	debug2("channel %d: rcvd ext data %d", c->self, data_len);
1922 	c->local_window -= data_len;
1923 	buffer_append(&c->extended, data, data_len);
1924 	xfree(data);
1925 }
1926 
1927 void
1928 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1929 {
1930 	int id;
1931 	Channel *c;
1932 
1933 	id = packet_get_int();
1934 	packet_check_eom();
1935 	c = channel_lookup(id);
1936 	if (c == NULL)
1937 		packet_disconnect("Received ieof for nonexistent channel %d.", id);
1938 	chan_rcvd_ieof(c);
1939 
1940 	/* XXX force input close */
1941 	if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1942 		debug("channel %d: FORCE input drain", c->self);
1943 		c->istate = CHAN_INPUT_WAIT_DRAIN;
1944 		if (buffer_len(&c->input) == 0)
1945 			chan_ibuf_empty(c);
1946 	}
1947 
1948 }
1949 
1950 void
1951 channel_input_close(int type, u_int32_t seq, void *ctxt)
1952 {
1953 	int id;
1954 	Channel *c;
1955 
1956 	id = packet_get_int();
1957 	packet_check_eom();
1958 	c = channel_lookup(id);
1959 	if (c == NULL)
1960 		packet_disconnect("Received close for nonexistent channel %d.", id);
1961 
1962 	/*
1963 	 * Send a confirmation that we have closed the channel and no more
1964 	 * data is coming for it.
1965 	 */
1966 	packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1967 	packet_put_int(c->remote_id);
1968 	packet_send();
1969 
1970 	/*
1971 	 * If the channel is in closed state, we have sent a close request,
1972 	 * and the other side will eventually respond with a confirmation.
1973 	 * Thus, we cannot free the channel here, because then there would be
1974 	 * no-one to receive the confirmation.  The channel gets freed when
1975 	 * the confirmation arrives.
1976 	 */
1977 	if (c->type != SSH_CHANNEL_CLOSED) {
1978 		/*
1979 		 * Not a closed channel - mark it as draining, which will
1980 		 * cause it to be freed later.
1981 		 */
1982 		buffer_clear(&c->input);
1983 		c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1984 	}
1985 }
1986 
1987 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1988 void
1989 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1990 {
1991 	int id = packet_get_int();
1992 	Channel *c = channel_lookup(id);
1993 
1994 	packet_check_eom();
1995 	if (c == NULL)
1996 		packet_disconnect("Received oclose for nonexistent channel %d.", id);
1997 	chan_rcvd_oclose(c);
1998 }
1999 
2000 void
2001 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2002 {
2003 	int id = packet_get_int();
2004 	Channel *c = channel_lookup(id);
2005 
2006 	packet_check_eom();
2007 	if (c == NULL)
2008 		packet_disconnect("Received close confirmation for "
2009 		    "out-of-range channel %d.", id);
2010 	if (c->type != SSH_CHANNEL_CLOSED)
2011 		packet_disconnect("Received close confirmation for "
2012 		    "non-closed channel %d (type %d).", id, c->type);
2013 	channel_free(c);
2014 }
2015 
2016 void
2017 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2018 {
2019 	int id, remote_id;
2020 	Channel *c;
2021 
2022 	id = packet_get_int();
2023 	c = channel_lookup(id);
2024 
2025 	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2026 		packet_disconnect("Received open confirmation for "
2027 		    "non-opening channel %d.", id);
2028 	remote_id = packet_get_int();
2029 	/* Record the remote channel number and mark that the channel is now open. */
2030 	c->remote_id = remote_id;
2031 	c->type = SSH_CHANNEL_OPEN;
2032 
2033 	if (compat20) {
2034 		c->remote_window = packet_get_int();
2035 		c->remote_maxpacket = packet_get_int();
2036 		if (c->confirm) {
2037 			debug2("callback start");
2038 			c->confirm(c->self, NULL);
2039 			debug2("callback done");
2040 		}
2041 		debug("channel %d: open confirm rwindow %u rmax %u", c->self,
2042 		    c->remote_window, c->remote_maxpacket);
2043 	}
2044 	packet_check_eom();
2045 }
2046 
2047 static char *
2048 reason2txt(int reason)
2049 {
2050 	switch (reason) {
2051 	case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2052 		return "administratively prohibited";
2053 	case SSH2_OPEN_CONNECT_FAILED:
2054 		return "connect failed";
2055 	case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2056 		return "unknown channel type";
2057 	case SSH2_OPEN_RESOURCE_SHORTAGE:
2058 		return "resource shortage";
2059 	}
2060 	return "unknown reason";
2061 }
2062 
2063 void
2064 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2065 {
2066 	int id, reason;
2067 	char *msg = NULL, *lang = NULL;
2068 	Channel *c;
2069 
2070 	id = packet_get_int();
2071 	c = channel_lookup(id);
2072 
2073 	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2074 		packet_disconnect("Received open failure for "
2075 		    "non-opening channel %d.", id);
2076 	if (compat20) {
2077 		reason = packet_get_int();
2078 		if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2079 			msg  = packet_get_string(NULL);
2080 			lang = packet_get_string(NULL);
2081 		}
2082 		log("channel %d: open failed: %s%s%s", id,
2083 		    reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2084 		if (msg != NULL)
2085 			xfree(msg);
2086 		if (lang != NULL)
2087 			xfree(lang);
2088 	}
2089 	packet_check_eom();
2090 	/* Free the channel.  This will also close the socket. */
2091 	channel_free(c);
2092 }
2093 
2094 void
2095 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2096 {
2097 	Channel *c;
2098 	int id;
2099 	u_int adjust;
2100 
2101 	if (!compat20)
2102 		return;
2103 
2104 	/* Get the channel number and verify it. */
2105 	id = packet_get_int();
2106 	c = channel_lookup(id);
2107 
2108 	if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
2109 		log("Received window adjust for "
2110 		    "non-open channel %d.", id);
2111 		return;
2112 	}
2113 	adjust = packet_get_int();
2114 	packet_check_eom();
2115 	debug2("channel %d: rcvd adjust %u", id, adjust);
2116 	c->remote_window += adjust;
2117 }
2118 
2119 void
2120 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2121 {
2122 	Channel *c = NULL;
2123 	u_short host_port;
2124 	char *host, *originator_string;
2125 	int remote_id, sock = -1;
2126 
2127 	remote_id = packet_get_int();
2128 	host = packet_get_string(NULL);
2129 	host_port = packet_get_int();
2130 
2131 	if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2132 		originator_string = packet_get_string(NULL);
2133 	} else {
2134 		originator_string = xstrdup("unknown (remote did not supply name)");
2135 	}
2136 	packet_check_eom();
2137 	sock = channel_connect_to(host, host_port);
2138 	if (sock != -1) {
2139 		c = channel_new("connected socket",
2140 		    SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2141 		    originator_string, 1);
2142 		c->remote_id = remote_id;
2143 	}
2144 	if (c == NULL) {
2145 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2146 		packet_put_int(remote_id);
2147 		packet_send();
2148 	}
2149 	xfree(host);
2150 }
2151 
2152 
2153 /* -- tcp forwarding */
2154 
2155 void
2156 channel_set_af(int af)
2157 {
2158 	IPv4or6 = af;
2159 }
2160 
2161 static int
2162 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2163     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2164 {
2165 	Channel *c;
2166 	int sock, r, is_client, on = 1, wildcard = 0, success = 0;
2167 	struct addrinfo hints, *ai, *aitop;
2168 	const char *host, *addr;
2169 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2170 
2171 	host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2172 	    listen_addr : host_to_connect;
2173 	is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2174 
2175 	if (host == NULL) {
2176 		error("No forward host name.");
2177 		return 0;
2178 	}
2179 	if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2180 		error("Forward host name too long.");
2181 		return 0;
2182 	}
2183 
2184 	/*
2185 	 * Determine whether or not a port forward listens to loopback,
2186 	 * specified address or wildcard. On the client, a specified bind
2187 	 * address will always override gateway_ports. On the server, a
2188 	 * gateway_ports of 1 (``yes'') will override the client's
2189 	 * specification and force a wildcard bind, whereas a value of 2
2190 	 * (``clientspecified'') will bind to whatever address the client
2191 	 * asked for.
2192 	 *
2193 	 * Special-case listen_addrs are:
2194 	 *
2195 	 * "0.0.0.0"               -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2196 	 * "" (empty string), "*"  -> wildcard v4/v6
2197 	 * "localhost"             -> loopback v4/v6
2198 	 */
2199 	addr = NULL;
2200 	if (listen_addr == NULL) {
2201 		/* No address specified: default to gateway_ports setting */
2202 		if (gateway_ports)
2203 			wildcard = 1;
2204 	} else if (gateway_ports || is_client) {
2205 		if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2206 		    strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
2207 		    *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2208 		    (!is_client && gateway_ports == 1))
2209 			wildcard = 1;
2210 		else if (strcmp(listen_addr, "localhost") != 0)
2211 			addr = listen_addr;
2212 	}
2213 
2214 	debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2215 	    type, wildcard, (addr == NULL) ? "NULL" : addr);
2216 
2217 	/*
2218 	 * getaddrinfo returns a loopback address if the hostname is
2219 	 * set to NULL and hints.ai_flags is not AI_PASSIVE
2220 	 */
2221 	memset(&hints, 0, sizeof(hints));
2222 	hints.ai_family = IPv4or6;
2223 	hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2224 	hints.ai_socktype = SOCK_STREAM;
2225 	snprintf(strport, sizeof strport, "%d", listen_port);
2226 	if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2227 		if (addr == NULL) {
2228 			/* This really shouldn't happen */
2229 			packet_disconnect("getaddrinfo: fatal error: %s",
2230 			    gai_strerror(r));
2231 		} else {
2232 			error("channel_setup_fwd_listener: "
2233 			    "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
2234 		}
2235 		return 0;
2236 	}
2237 
2238 	for (ai = aitop; ai; ai = ai->ai_next) {
2239 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2240 			continue;
2241 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2242 		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2243 			error("channel_setup_fwd_listener: getnameinfo failed");
2244 			continue;
2245 		}
2246 		/* Create a port to listen for the host. */
2247 		sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2248 		if (sock < 0) {
2249 			/* this is no error since kernel may not support ipv6 */
2250 			verbose("socket: %.100s", strerror(errno));
2251 			continue;
2252 		}
2253 		/*
2254 		 * Set socket options.
2255 		 * Allow local port reuse in TIME_WAIT.
2256 		 */
2257 		if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
2258 		    sizeof(on)) == -1)
2259 			error("setsockopt SO_REUSEADDR: %s", strerror(errno));
2260 
2261 		debug("Local forwarding listening on %s port %s.", ntop, strport);
2262 
2263 		/* Bind the socket to the address. */
2264 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2265 			/* address can be in use ipv6 address is already bound */
2266 			if (!ai->ai_next)
2267 				error("bind: %.100s", strerror(errno));
2268 			else
2269 				verbose("bind: %.100s", strerror(errno));
2270 
2271 			close(sock);
2272 			continue;
2273 		}
2274 		/* Start listening for connections on the socket. */
2275 		if (listen(sock, 5) < 0) {
2276 			error("listen: %.100s", strerror(errno));
2277 			close(sock);
2278 			continue;
2279 		}
2280 		/* Allocate a channel number for the socket. */
2281 		c = channel_new("port listener", type, sock, sock, -1,
2282 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2283 		    0, xstrdup("port listener"), 1);
2284 		strlcpy(c->path, host, sizeof(c->path));
2285 		c->host_port = port_to_connect;
2286 		c->listening_port = listen_port;
2287 		success = 1;
2288 	}
2289 	if (success == 0)
2290 		error("channel_setup_fwd_listener: cannot listen to port: %d",
2291 		    listen_port);
2292 	freeaddrinfo(aitop);
2293 	return success;
2294 }
2295 
2296 int
2297 channel_cancel_rport_listener(const char *host, u_short port)
2298 {
2299 	u_int i;
2300 	int found = 0;
2301 
2302 	for (i = 0; i < channels_alloc; i++) {
2303 		Channel *c = channels[i];
2304 
2305 		if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2306 		    strncmp(c->path, host, sizeof(c->path)) == 0 &&
2307 		    c->listening_port == port) {
2308 			debug2("%s: close channel %d", __func__, i);
2309 			channel_free(c);
2310 			found = 1;
2311 		}
2312 	}
2313 
2314 	return (found);
2315 }
2316 
2317 /* protocol local port fwd, used by ssh (and sshd in v1) */
2318 int
2319 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2320     const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2321 {
2322 	return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2323 	    listen_host, listen_port, host_to_connect, port_to_connect,
2324 	    gateway_ports);
2325 }
2326 
2327 /* protocol v2 remote port fwd, used by sshd */
2328 int
2329 channel_setup_remote_fwd_listener(const char *listen_address,
2330     u_short listen_port, int gateway_ports)
2331 {
2332 	return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2333 	    listen_address, listen_port, NULL, 0, gateway_ports);
2334 }
2335 
2336 /*
2337  * Initiate forwarding of connections to port "port" on remote host through
2338  * the secure channel to host:port from local side.
2339  */
2340 
2341 int
2342 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2343     const char *host_to_connect, u_short port_to_connect)
2344 {
2345 	int type, success = 0;
2346 
2347 	/* Record locally that connection to this host/port is permitted. */
2348 	if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2349 		fatal("channel_request_remote_forwarding: too many forwards");
2350 
2351 	if (listen_host != NULL &&
2352 	    strlen(listen_host) > SSH_CHANNEL_PATH_LEN - 1) {
2353 		error("Binding address too long.");
2354 		return -1;
2355 	}
2356 
2357 	/* Send the forward request to the remote side. */
2358 	if (compat20) {
2359 		const char *address_to_bind;
2360 		if (listen_host == NULL) {
2361 			if (datafellows & SSH_BUG_RFWD_ADDR)
2362 				address_to_bind = "127.0.0.1";
2363 			else
2364 				address_to_bind = "localhost";
2365 		} else if (*listen_host == '\0' ||
2366 			   strcmp(listen_host, "*") == 0) {
2367 			if (datafellows & SSH_BUG_RFWD_ADDR)
2368 				address_to_bind = "0.0.0.0";
2369 			else
2370 				address_to_bind = "";
2371 		} else
2372 			address_to_bind = listen_host;
2373 
2374 		packet_start(SSH2_MSG_GLOBAL_REQUEST);
2375 		packet_put_cstring("tcpip-forward");
2376 		packet_put_char(1);			/* boolean: want reply */
2377 		packet_put_cstring(address_to_bind);
2378 		packet_put_int(listen_port);
2379 		packet_send();
2380 		packet_write_wait();
2381 		/* Assume that server accepts the request */
2382 		success = 1;
2383 	} else {
2384 		packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2385 		packet_put_int(listen_port);
2386 		packet_put_cstring(host_to_connect);
2387 		packet_put_int(port_to_connect);
2388 		packet_send();
2389 		packet_write_wait();
2390 
2391 		/* Wait for response from the remote side. */
2392 		type = packet_read();
2393 		switch (type) {
2394 		case SSH_SMSG_SUCCESS:
2395 			success = 1;
2396 			break;
2397 		case SSH_SMSG_FAILURE:
2398 			log("Warning: Server denied remote port forwarding.");
2399 			break;
2400 		default:
2401 			/* Unknown packet */
2402 			packet_disconnect("Protocol error for port forward request:"
2403 			    "received packet type %d.", type);
2404 		}
2405 	}
2406 	if (success) {
2407 		permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2408 		permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2409 		permitted_opens[num_permitted_opens].listen_port = listen_port;
2410 		num_permitted_opens++;
2411 	}
2412 	return (success ? 0 : -1);
2413 }
2414 
2415 /*
2416  * Request cancellation of remote forwarding of connection host:port from
2417  * local side.
2418  */
2419 void
2420 channel_request_rforward_cancel(const char *host, u_short port)
2421 {
2422 	int i;
2423 
2424 	if (!compat20)
2425 		return;
2426 
2427 	for (i = 0; i < num_permitted_opens; i++) {
2428 		if (permitted_opens[i].host_to_connect != NULL &&
2429 		    permitted_opens[i].listen_port == port)
2430 			break;
2431 	}
2432 	if (i >= num_permitted_opens) {
2433 		debug("%s: requested forward not found", __func__);
2434 		return;
2435 	}
2436 	packet_start(SSH2_MSG_GLOBAL_REQUEST);
2437 	packet_put_cstring("cancel-tcpip-forward");
2438 	packet_put_char(0);
2439 	packet_put_cstring(host == NULL ? "" : host);
2440 	packet_put_int(port);
2441 	packet_send();
2442 
2443 	permitted_opens[i].listen_port = 0;
2444 	permitted_opens[i].port_to_connect = 0;
2445 	xfree(permitted_opens[i].host_to_connect);
2446 	permitted_opens[i].host_to_connect = NULL;
2447 }
2448 
2449 /*
2450  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
2451  * listening for the port, and sends back a success reply (or disconnect
2452  * message if there was an error).  This never returns if there was an error.
2453  */
2454 
2455 void
2456 channel_input_port_forward_request(int is_root, int gateway_ports)
2457 {
2458 	u_short port, host_port;
2459 	char *hostname;
2460 
2461 	/* Get arguments from the packet. */
2462 	port = packet_get_int();
2463 	hostname = packet_get_string(NULL);
2464 	host_port = packet_get_int();
2465 
2466 #ifndef HAVE_CYGWIN
2467 	/*
2468 	 * Check that an unprivileged user is not trying to forward a
2469 	 * privileged port.
2470 	 */
2471 	if (port < IPPORT_RESERVED && !is_root)
2472 		packet_disconnect("Requested forwarding of port %d but user is not root.",
2473 				  port);
2474 #endif
2475 	/* Initiate forwarding */
2476 	channel_setup_local_fwd_listener(NULL, port, hostname,
2477 	    host_port, gateway_ports);
2478 
2479 	/* Free the argument string. */
2480 	xfree(hostname);
2481 }
2482 
2483 /*
2484  * Permits opening to any host/port if permitted_opens[] is empty.  This is
2485  * usually called by the server, because the user could connect to any port
2486  * anyway, and the server has no way to know but to trust the client anyway.
2487  */
2488 void
2489 channel_permit_all_opens(void)
2490 {
2491 	if (num_permitted_opens == 0)
2492 		all_opens_permitted = 1;
2493 }
2494 
2495 void
2496 channel_add_permitted_opens(char *host, int port)
2497 {
2498 	if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2499 		fatal("channel_add_permitted_opens: too many forwards");
2500 	debug("allow port forwarding to host %s port %d", host, port);
2501 
2502 	permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2503 	permitted_opens[num_permitted_opens].port_to_connect = port;
2504 	num_permitted_opens++;
2505 
2506 	all_opens_permitted = 0;
2507 }
2508 
2509 void
2510 channel_clear_permitted_opens(void)
2511 {
2512 	int i;
2513 
2514 	for (i = 0; i < num_permitted_opens; i++)
2515 		xfree(permitted_opens[i].host_to_connect);
2516 	num_permitted_opens = 0;
2517 }
2518 
2519 
2520 /* return socket to remote host, port */
2521 static int
2522 connect_to(const char *host, u_short port)
2523 {
2524 	struct addrinfo hints, *ai, *aitop;
2525 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2526 	int gaierr;
2527 	int sock = -1;
2528 
2529 	memset(&hints, 0, sizeof(hints));
2530 	hints.ai_family = IPv4or6;
2531 	hints.ai_socktype = SOCK_STREAM;
2532 	snprintf(strport, sizeof strport, "%d", port);
2533 	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2534 		error("connect_to %.100s: unknown host (%s)", host,
2535 		    gai_strerror(gaierr));
2536 		return -1;
2537 	}
2538 	for (ai = aitop; ai; ai = ai->ai_next) {
2539 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2540 			continue;
2541 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2542 		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2543 			error("connect_to: getnameinfo failed");
2544 			continue;
2545 		}
2546 		sock = socket(ai->ai_family, SOCK_STREAM, 0);
2547 		if (sock < 0) {
2548 			error("socket: %.100s", strerror(errno));
2549 			continue;
2550 		}
2551 		if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2552 			fatal("connect_to: F_SETFL: %s", strerror(errno));
2553 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2554 		    errno != EINPROGRESS) {
2555 			error("connect_to %.100s port %s: %.100s", ntop, strport,
2556 			    strerror(errno));
2557 			close(sock);
2558 			continue;	/* fail -- try next */
2559 		}
2560 		break; /* success */
2561 
2562 	}
2563 	freeaddrinfo(aitop);
2564 	if (!ai) {
2565 		error("connect_to %.100s port %d: failed.", host, port);
2566 		return -1;
2567 	}
2568 	/* success */
2569 	set_nodelay(sock);
2570 	return sock;
2571 }
2572 
2573 int
2574 channel_connect_by_listen_address(u_short listen_port)
2575 {
2576 	int i;
2577 
2578 	for (i = 0; i < num_permitted_opens; i++)
2579 		if (permitted_opens[i].listen_port == listen_port)
2580 			return connect_to(
2581 			    permitted_opens[i].host_to_connect,
2582 			    permitted_opens[i].port_to_connect);
2583 	error("WARNING: Server requests forwarding for unknown listen_port %d",
2584 	    listen_port);
2585 	return -1;
2586 }
2587 
2588 /* Check if connecting to that port is permitted and connect. */
2589 int
2590 channel_connect_to(const char *host, u_short port)
2591 {
2592 	int i, permit;
2593 
2594 	permit = all_opens_permitted;
2595 	if (!permit) {
2596 		for (i = 0; i < num_permitted_opens; i++)
2597 			if (permitted_opens[i].port_to_connect == port &&
2598 			    strcmp(permitted_opens[i].host_to_connect, host) == 0)
2599 				permit = 1;
2600 
2601 	}
2602 	if (!permit) {
2603 		log("Received request to connect to host %.100s port %d, "
2604 		    "but the request was denied.", host, port);
2605 		return -1;
2606 	}
2607 	return connect_to(host, port);
2608 }
2609 
2610 /* -- X11 forwarding */
2611 
2612 /*
2613  * Creates an internet domain socket for listening for X11 connections.
2614  * Returns 0 and a suitable display number for the DISPLAY variable
2615  * stored in display_numberp , or -1 if an error occurs.
2616  */
2617 int
2618 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2619     int single_connection, u_int *display_numberp)
2620 {
2621 	Channel *nc = NULL;
2622 	int display_number, sock;
2623 	u_short port;
2624 	struct addrinfo hints, *ai, *aitop;
2625 	char strport[NI_MAXSERV];
2626 	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2627 
2628 	for (display_number = x11_display_offset;
2629 	    display_number < MAX_DISPLAYS;
2630 	    display_number++) {
2631 		port = 6000 + display_number;
2632 		memset(&hints, 0, sizeof(hints));
2633 		hints.ai_family = IPv4or6;
2634 		hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2635 		hints.ai_socktype = SOCK_STREAM;
2636 		snprintf(strport, sizeof strport, "%d", port);
2637 		if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2638 			error("getaddrinfo: %.100s", gai_strerror(gaierr));
2639 			return -1;
2640 		}
2641 		for (ai = aitop; ai; ai = ai->ai_next) {
2642 			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2643 				continue;
2644 			sock = socket(ai->ai_family, SOCK_STREAM, 0);
2645 			if (sock < 0) {
2646 				if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2647 					error("socket: %.100s", strerror(errno));
2648 					freeaddrinfo(aitop);
2649 					for (n = 0; n < num_socks; n++)
2650 						close(socks[n]);
2651 					return -1;
2652 				} else {
2653 					debug("x11_create_display_inet: Socket family %d not supported",
2654 						 ai->ai_family);
2655 					continue;
2656 				}
2657 			}
2658 #ifdef IPV6_V6ONLY
2659 			if (ai->ai_family == AF_INET6) {
2660 				int on = 1;
2661 				if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2662 					error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2663 			}
2664 #endif
2665 			if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2666 				/*
2667 				 * If bind() fails  with EADDRNOTAVAIL, we
2668 				 * should not break immediately but rather
2669 				 * try the next address available.
2670 				 */
2671 				if (errno == EADDRNOTAVAIL) {
2672 					close(sock);
2673 					continue;
2674 				}
2675 
2676 				debug("bind port %d: %.100s; skipping this port", port,
2677 				    strerror(errno));
2678 				close(sock);
2679 
2680 				for (n = 0; n < num_socks; n++) {
2681 					close(socks[n]);
2682 				}
2683 				num_socks = 0;
2684 				break;
2685 			}
2686 			socks[num_socks++] = sock;
2687 #ifndef DONT_TRY_OTHER_AF
2688 			if (num_socks == NUM_SOCKS)
2689 				break;
2690 #else
2691 			if (x11_use_localhost) {
2692 				if (num_socks == NUM_SOCKS)
2693 					break;
2694 			} else {
2695 				break;
2696 			}
2697 #endif
2698 		}
2699 		freeaddrinfo(aitop);
2700 		if (num_socks > 0)
2701 			break;
2702 	}
2703 	if (display_number >= MAX_DISPLAYS) {
2704 		error("Failed to allocate internet-domain X11 display socket.");
2705 		return -1;
2706 	}
2707 	/* Start listening for connections on the socket. */
2708 	for (n = 0; n < num_socks; n++) {
2709 		sock = socks[n];
2710 		if (listen(sock, 5) < 0) {
2711 			int i;
2712 			error("listen: %.100s", strerror(errno));
2713 			for (i = 0; i < num_socks; i++)
2714 				close(socks[i]);
2715 			return -1;
2716 		}
2717 	}
2718 
2719 	/* Allocate a channel for each socket. */
2720 	for (n = 0; n < num_socks; n++) {
2721 		sock = socks[n];
2722 		nc = channel_new("x11 listener",
2723 		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2724 		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2725 		    0, xstrdup("X11 inet listener"), 1);
2726 		nc->single_connection = single_connection;
2727 	}
2728 
2729 	/* Return the display number for the DISPLAY environment variable. */
2730 	*display_numberp = display_number;
2731 	return (0);
2732 }
2733 
2734 static int
2735 connect_local_xsocket(u_int dnr)
2736 {
2737 	int sock;
2738 	struct sockaddr_un addr;
2739 
2740 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
2741 	if (sock < 0)
2742 		error("socket: %.100s", strerror(errno));
2743 	memset(&addr, 0, sizeof(addr));
2744 	addr.sun_family = AF_UNIX;
2745 	snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2746 	if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2747 		return sock;
2748 	close(sock);
2749 	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2750 	return -1;
2751 }
2752 
2753 int
2754 x11_connect_display(void)
2755 {
2756 	int display_number, sock = 0;
2757 	const char *display;
2758 	char buf[1024], *cp;
2759 	struct addrinfo hints, *ai, *aitop;
2760 	char strport[NI_MAXSERV];
2761 	int gaierr;
2762 
2763 	/* Try to open a socket for the local X server. */
2764 	display = getenv("DISPLAY");
2765 	if (!display) {
2766 		error("DISPLAY not set.");
2767 		return -1;
2768 	}
2769 	/*
2770 	 * Now we decode the value of the DISPLAY variable and make a
2771 	 * connection to the real X server.
2772 	 */
2773 
2774 	/*
2775 	 * Check if it is a unix domain socket.  Unix domain displays are in
2776 	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2777 	 */
2778 	if (strncmp(display, "unix:", 5) == 0 ||
2779 	    display[0] == ':') {
2780 		/* Connect to the unix domain socket. */
2781 		if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2782 			error("Could not parse display number from DISPLAY: %.100s",
2783 			    display);
2784 			return -1;
2785 		}
2786 		/* Create a socket. */
2787 		sock = connect_local_xsocket(display_number);
2788 		if (sock < 0)
2789 			return -1;
2790 
2791 		/* OK, we now have a connection to the display. */
2792 		return sock;
2793 	}
2794 	/*
2795 	 * Connect to an inet socket.  The DISPLAY value is supposedly
2796 	 * hostname:d[.s], where hostname may also be numeric IP address.
2797 	 */
2798 	strlcpy(buf, display, sizeof(buf));
2799 	cp = strchr(buf, ':');
2800 	if (!cp) {
2801 		error("Could not find ':' in DISPLAY: %.100s", display);
2802 		return -1;
2803 	}
2804 	*cp = 0;
2805 	/* buf now contains the host name.  But first we parse the display number. */
2806 	if (sscanf(cp + 1, "%d", &display_number) != 1) {
2807 		error("Could not parse display number from DISPLAY: %.100s",
2808 		    display);
2809 		return -1;
2810 	}
2811 
2812 	/* Look up the host address */
2813 	memset(&hints, 0, sizeof(hints));
2814 	hints.ai_family = IPv4or6;
2815 	hints.ai_socktype = SOCK_STREAM;
2816 	snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2817 	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2818 		error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2819 		return -1;
2820 	}
2821 	for (ai = aitop; ai; ai = ai->ai_next) {
2822 		/* Create a socket. */
2823 		sock = socket(ai->ai_family, SOCK_STREAM, 0);
2824 		if (sock < 0) {
2825 			debug("socket: %.100s", strerror(errno));
2826 			continue;
2827 		}
2828 		/* Connect it to the display. */
2829 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2830 			debug("connect %.100s port %d: %.100s", buf,
2831 			    6000 + display_number, strerror(errno));
2832 			close(sock);
2833 			continue;
2834 		}
2835 		/* Success */
2836 		break;
2837 	}
2838 	freeaddrinfo(aitop);
2839 	if (!ai) {
2840 		error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2841 		    strerror(errno));
2842 		return -1;
2843 	}
2844 	set_nodelay(sock);
2845 	return sock;
2846 }
2847 
2848 /*
2849  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
2850  * the remote channel number.  We should do whatever we want, and respond
2851  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2852  */
2853 
2854 void
2855 x11_input_open(int type, u_int32_t seq, void *ctxt)
2856 {
2857 	Channel *c = NULL;
2858 	int remote_id, sock = 0;
2859 	char *remote_host;
2860 
2861 	debug("Received X11 open request.");
2862 
2863 	remote_id = packet_get_int();
2864 
2865 	if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2866 		remote_host = packet_get_string(NULL);
2867 	} else {
2868 		remote_host = xstrdup("unknown (remote did not supply name)");
2869 	}
2870 	packet_check_eom();
2871 
2872 	/* Obtain a connection to the real X display. */
2873 	sock = x11_connect_display();
2874 	if (sock != -1) {
2875 		/* Allocate a channel for this connection. */
2876 		c = channel_new("connected x11 socket",
2877 		    SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
2878 		    remote_host, 1);
2879 		c->remote_id = remote_id;
2880 		c->force_drain = 1;
2881 	}
2882 	if (c == NULL) {
2883 		/* Send refusal to the remote host. */
2884 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2885 		packet_put_int(remote_id);
2886 	} else {
2887 		/* Send a confirmation to the remote host. */
2888 		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2889 		packet_put_int(remote_id);
2890 		packet_put_int(c->self);
2891 	}
2892 	packet_send();
2893 }
2894 
2895 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2896 void
2897 deny_input_open(int type, u_int32_t seq, void *ctxt)
2898 {
2899 	int rchan = packet_get_int();
2900 
2901 	switch (type) {
2902 	case SSH_SMSG_AGENT_OPEN:
2903 		error("Warning: ssh server tried agent forwarding.");
2904 		break;
2905 	case SSH_SMSG_X11_OPEN:
2906 		error("Warning: ssh server tried X11 forwarding.");
2907 		break;
2908 	default:
2909 		error("deny_input_open: type %d", type);
2910 		break;
2911 	}
2912 	error("Warning: this is probably a break in attempt by a malicious server.");
2913 	packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2914 	packet_put_int(rchan);
2915 	packet_send();
2916 }
2917 
2918 /*
2919  * Requests forwarding of X11 connections, generates fake authentication
2920  * data, and enables authentication spoofing.
2921  * This should be called in the client only.
2922  */
2923 void
2924 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
2925     const char *proto, const char *data)
2926 {
2927 	u_int data_len = (u_int) strlen(data) / 2;
2928 	u_int i, value;
2929 	char *new_data;
2930 	int screen_number;
2931 	const char *cp;
2932 	u_int32_t rand = 0;
2933 
2934 	cp = disp;
2935 	if (disp)
2936 		cp = strchr(disp, ':');
2937 	if (cp)
2938 		cp = strchr(cp, '.');
2939 	if (cp)
2940 		screen_number = atoi(cp + 1);
2941 	else
2942 		screen_number = 0;
2943 
2944 	/* Save protocol name. */
2945 	x11_saved_proto = xstrdup(proto);
2946 
2947 	/*
2948 	 * Extract real authentication data and generate fake data of the
2949 	 * same length.
2950 	 */
2951 	x11_saved_data = xmalloc(data_len);
2952 	x11_fake_data = xmalloc(data_len);
2953 	for (i = 0; i < data_len; i++) {
2954 		if (sscanf(data + 2 * i, "%2x", &value) != 1)
2955 			fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2956 		if (i % 4 == 0)
2957 			rand = arc4random();
2958 		x11_saved_data[i] = value;
2959 		x11_fake_data[i] = rand & 0xff;
2960 		rand >>= 8;
2961 	}
2962 	x11_saved_data_len = data_len;
2963 	x11_fake_data_len = data_len;
2964 
2965 	/* Convert the fake data into hex. */
2966 	new_data = tohex(x11_fake_data, data_len);
2967 
2968 	/* Send the request packet. */
2969 	if (compat20) {
2970 		channel_request_start(client_session_id, "x11-req", 0);
2971 		packet_put_char(0);	/* XXX bool single connection */
2972 	} else {
2973 		packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2974 	}
2975 	packet_put_cstring(proto);
2976 	packet_put_cstring(new_data);
2977 	packet_put_int(screen_number);
2978 	packet_send();
2979 	packet_write_wait();
2980 	xfree(new_data);
2981 }
2982 
2983 
2984 /* -- agent forwarding */
2985 
2986 /* Sends a message to the server to request authentication fd forwarding. */
2987 
2988 void
2989 auth_request_forwarding(void)
2990 {
2991 	packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2992 	packet_send();
2993 	packet_write_wait();
2994 }
2995 
2996 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2997 
2998 void
2999 auth_input_open_request(int type, u_int32_t seq, void *ctxt)
3000 {
3001 	Channel *c = NULL;
3002 	int remote_id, sock;
3003 	char *name;
3004 
3005 	/* Read the remote channel number from the message. */
3006 	remote_id = packet_get_int();
3007 	packet_check_eom();
3008 
3009 	/*
3010 	 * Get a connection to the local authentication agent (this may again
3011 	 * get forwarded).
3012 	 */
3013 	sock = ssh_get_authentication_socket();
3014 
3015 	/*
3016 	 * If we could not connect the agent, send an error message back to
3017 	 * the server. This should never happen unless the agent dies,
3018 	 * because authentication forwarding is only enabled if we have an
3019 	 * agent.
3020 	 */
3021 	if (sock >= 0) {
3022 		name = xstrdup("authentication agent connection");
3023 		c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
3024 		    -1, 0, 0, 0, name, 1);
3025 		c->remote_id = remote_id;
3026 		c->force_drain = 1;
3027 	}
3028 	if (c == NULL) {
3029 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3030 		packet_put_int(remote_id);
3031 	} else {
3032 		/* Send a confirmation to the remote host. */
3033 		debug("Forwarding authentication connection.");
3034 		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3035 		packet_put_int(remote_id);
3036 		packet_put_int(c->self);
3037 	}
3038 	packet_send();
3039 }
3040