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