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