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