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