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