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