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