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