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