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