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