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