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