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