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