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