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