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