xref: /openssh-portable/channels.c (revision 816036f1)
1 /* $OpenBSD: channels.c,v 1.403 2020/10/18 11:32:01 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This file contains functions for generic socket connection forwarding.
7  * There is also code for initiating connection forwarding for X11 connections,
8  * arbitrary tcp/ip connections, and the authentication agent connection.
9  *
10  * As far as I am concerned, the code I have written for this software
11  * can be used freely for any purpose.  Any derived versions of this
12  * software must be clearly marked as such, and if the derived work is
13  * incompatible with the protocol description in the RFC file, it must be
14  * called by a name other than "ssh" or "Secure Shell".
15  *
16  * SSH2 support added by Markus Friedl.
17  * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl.  All rights reserved.
18  * Copyright (c) 1999 Dug Song.  All rights reserved.
19  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 #include "includes.h"
43 
44 #include <sys/types.h>
45 #include <sys/stat.h>
46 #include <sys/ioctl.h>
47 #include <sys/un.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
51 #endif
52 
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 
56 #include <errno.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <netdb.h>
60 #include <stdarg.h>
61 #ifdef HAVE_STDINT_H
62 # include <stdint.h>
63 #endif
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <termios.h>
68 #include <unistd.h>
69 
70 #include "openbsd-compat/sys-queue.h"
71 #include "xmalloc.h"
72 #include "ssh.h"
73 #include "ssh2.h"
74 #include "ssherr.h"
75 #include "sshbuf.h"
76 #include "packet.h"
77 #include "log.h"
78 #include "misc.h"
79 #include "channels.h"
80 #include "compat.h"
81 #include "canohost.h"
82 #include "sshkey.h"
83 #include "authfd.h"
84 #include "pathnames.h"
85 #include "match.h"
86 
87 /* -- agent forwarding */
88 #define	NUM_SOCKS	10
89 
90 /* -- tcp forwarding */
91 /* special-case port number meaning allow any port */
92 #define FWD_PERMIT_ANY_PORT	0
93 
94 /* special-case wildcard meaning allow any host */
95 #define FWD_PERMIT_ANY_HOST	"*"
96 
97 /* -- X11 forwarding */
98 /* Maximum number of fake X11 displays to try. */
99 #define MAX_DISPLAYS  1000
100 
101 /* Per-channel callback for pre/post select() actions */
102 typedef void chan_fn(struct ssh *, Channel *c,
103     fd_set *readset, fd_set *writeset);
104 
105 /*
106  * Data structure for storing which hosts are permitted for forward requests.
107  * The local sides of any remote forwards are stored in this array to prevent
108  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
109  * network (which might be behind a firewall).
110  */
111 /* XXX: streamlocal wants a path instead of host:port */
112 /*      Overload host_to_connect; we could just make this match Forward */
113 /*	XXX - can we use listen_host instead of listen_path? */
114 struct permission {
115 	char *host_to_connect;		/* Connect to 'host'. */
116 	int port_to_connect;		/* Connect to 'port'. */
117 	char *listen_host;		/* Remote side should listen address. */
118 	char *listen_path;		/* Remote side should listen path. */
119 	int listen_port;		/* Remote side should listen port. */
120 	Channel *downstream;		/* Downstream mux*/
121 };
122 
123 /*
124  * Stores the forwarding permission state for a single direction (local or
125  * remote).
126  */
127 struct permission_set {
128 	/*
129 	 * List of all local permitted host/port pairs to allow for the
130 	 * user.
131 	 */
132 	u_int num_permitted_user;
133 	struct permission *permitted_user;
134 
135 	/*
136 	 * List of all permitted host/port pairs to allow for the admin.
137 	 */
138 	u_int num_permitted_admin;
139 	struct permission *permitted_admin;
140 
141 	/*
142 	 * If this is true, all opens/listens are permitted.  This is the
143 	 * case on the server on which we have to trust the client anyway,
144 	 * and the user could do anything after logging in.
145 	 */
146 	int all_permitted;
147 };
148 
149 /* Master structure for channels state */
150 struct ssh_channels {
151 	/*
152 	 * Pointer to an array containing all allocated channels.  The array
153 	 * is dynamically extended as needed.
154 	 */
155 	Channel **channels;
156 
157 	/*
158 	 * Size of the channel array.  All slots of the array must always be
159 	 * initialized (at least the type field); unused slots set to NULL
160 	 */
161 	u_int channels_alloc;
162 
163 	/*
164 	 * Maximum file descriptor value used in any of the channels.  This is
165 	 * updated in channel_new.
166 	 */
167 	int channel_max_fd;
168 
169 	/*
170 	 * 'channel_pre*' are called just before select() to add any bits
171 	 * relevant to channels in the select bitmasks.
172 	 *
173 	 * 'channel_post*': perform any appropriate operations for
174 	 * channels which have events pending.
175 	 */
176 	chan_fn **channel_pre;
177 	chan_fn **channel_post;
178 
179 	/* -- tcp forwarding */
180 	struct permission_set local_perms;
181 	struct permission_set remote_perms;
182 
183 	/* -- X11 forwarding */
184 
185 	/* Saved X11 local (client) display. */
186 	char *x11_saved_display;
187 
188 	/* Saved X11 authentication protocol name. */
189 	char *x11_saved_proto;
190 
191 	/* Saved X11 authentication data.  This is the real data. */
192 	char *x11_saved_data;
193 	u_int x11_saved_data_len;
194 
195 	/* Deadline after which all X11 connections are refused */
196 	u_int x11_refuse_time;
197 
198 	/*
199 	 * Fake X11 authentication data.  This is what the server will be
200 	 * sending us; we should replace any occurrences of this by the
201 	 * real data.
202 	 */
203 	u_char *x11_fake_data;
204 	u_int x11_fake_data_len;
205 
206 	/* AF_UNSPEC or AF_INET or AF_INET6 */
207 	int IPv4or6;
208 };
209 
210 /* helper */
211 static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
212 static const char *channel_rfwd_bind_host(const char *listen_host);
213 
214 /* non-blocking connect helpers */
215 static int connect_next(struct channel_connect *);
216 static void channel_connect_ctx_free(struct channel_connect *);
217 static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
218 static int rdynamic_connect_finish(struct ssh *, Channel *);
219 
220 /* Setup helper */
221 static void channel_handler_init(struct ssh_channels *sc);
222 
223 /* -- channel core */
224 
225 void
channel_init_channels(struct ssh * ssh)226 channel_init_channels(struct ssh *ssh)
227 {
228 	struct ssh_channels *sc;
229 
230 	if ((sc = calloc(1, sizeof(*sc))) == NULL)
231 		fatal_f("allocation failed");
232 	sc->channels_alloc = 10;
233 	sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
234 	sc->IPv4or6 = AF_UNSPEC;
235 	channel_handler_init(sc);
236 
237 	ssh->chanctxt = sc;
238 }
239 
240 Channel *
channel_by_id(struct ssh * ssh,int id)241 channel_by_id(struct ssh *ssh, int id)
242 {
243 	Channel *c;
244 
245 	if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
246 		logit_f("%d: bad id", id);
247 		return NULL;
248 	}
249 	c = ssh->chanctxt->channels[id];
250 	if (c == NULL) {
251 		logit_f("%d: bad id: channel free", id);
252 		return NULL;
253 	}
254 	return c;
255 }
256 
257 Channel *
channel_by_remote_id(struct ssh * ssh,u_int remote_id)258 channel_by_remote_id(struct ssh *ssh, u_int remote_id)
259 {
260 	Channel *c;
261 	u_int i;
262 
263 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
264 		c = ssh->chanctxt->channels[i];
265 		if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
266 			return c;
267 	}
268 	return NULL;
269 }
270 
271 /*
272  * Returns the channel if it is allowed to receive protocol messages.
273  * Private channels, like listening sockets, may not receive messages.
274  */
275 Channel *
channel_lookup(struct ssh * ssh,int id)276 channel_lookup(struct ssh *ssh, int id)
277 {
278 	Channel *c;
279 
280 	if ((c = channel_by_id(ssh, id)) == NULL)
281 		return NULL;
282 
283 	switch (c->type) {
284 	case SSH_CHANNEL_X11_OPEN:
285 	case SSH_CHANNEL_LARVAL:
286 	case SSH_CHANNEL_CONNECTING:
287 	case SSH_CHANNEL_DYNAMIC:
288 	case SSH_CHANNEL_RDYNAMIC_OPEN:
289 	case SSH_CHANNEL_RDYNAMIC_FINISH:
290 	case SSH_CHANNEL_OPENING:
291 	case SSH_CHANNEL_OPEN:
292 	case SSH_CHANNEL_ABANDONED:
293 	case SSH_CHANNEL_MUX_PROXY:
294 		return c;
295 	}
296 	logit("Non-public channel %d, type %d.", id, c->type);
297 	return NULL;
298 }
299 
300 /*
301  * Register filedescriptors for a channel, used when allocating a channel or
302  * when the channel consumer/producer is ready, e.g. shell exec'd
303  */
304 static void
channel_register_fds(struct ssh * ssh,Channel * c,int rfd,int wfd,int efd,int extusage,int nonblock,int is_tty)305 channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
306     int extusage, int nonblock, int is_tty)
307 {
308 	struct ssh_channels *sc = ssh->chanctxt;
309 
310 	/* Update the maximum file descriptor value. */
311 	sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, rfd);
312 	sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, wfd);
313 	sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, efd);
314 
315 	if (rfd != -1)
316 		fcntl(rfd, F_SETFD, FD_CLOEXEC);
317 	if (wfd != -1 && wfd != rfd)
318 		fcntl(wfd, F_SETFD, FD_CLOEXEC);
319 	if (efd != -1 && efd != rfd && efd != wfd)
320 		fcntl(efd, F_SETFD, FD_CLOEXEC);
321 
322 	c->rfd = rfd;
323 	c->wfd = wfd;
324 	c->sock = (rfd == wfd) ? rfd : -1;
325 	c->efd = efd;
326 	c->extended_usage = extusage;
327 
328 	if ((c->isatty = is_tty) != 0)
329 		debug2("channel %d: rfd %d isatty", c->self, c->rfd);
330 #ifdef _AIX
331 	/* XXX: Later AIX versions can't push as much data to tty */
332 	c->wfd_isatty = is_tty || isatty(c->wfd);
333 #endif
334 
335 	/* enable nonblocking mode */
336 	if (nonblock) {
337 		if (rfd != -1)
338 			set_nonblock(rfd);
339 		if (wfd != -1)
340 			set_nonblock(wfd);
341 		if (efd != -1)
342 			set_nonblock(efd);
343 	}
344 }
345 
346 /*
347  * Allocate a new channel object and set its type and socket. This will cause
348  * remote_name to be freed.
349  */
350 Channel *
channel_new(struct ssh * ssh,char * ctype,int type,int rfd,int wfd,int efd,u_int window,u_int maxpack,int extusage,char * remote_name,int nonblock)351 channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
352     u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
353 {
354 	struct ssh_channels *sc = ssh->chanctxt;
355 	u_int i, found;
356 	Channel *c;
357 	int r;
358 
359 	/* Try to find a free slot where to put the new channel. */
360 	for (i = 0; i < sc->channels_alloc; i++) {
361 		if (sc->channels[i] == NULL) {
362 			/* Found a free slot. */
363 			found = i;
364 			break;
365 		}
366 	}
367 	if (i >= sc->channels_alloc) {
368 		/*
369 		 * There are no free slots. Take last+1 slot and expand
370 		 * the array.
371 		 */
372 		found = sc->channels_alloc;
373 		if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
374 			fatal_f("internal error: channels_alloc %d too big",
375 			    sc->channels_alloc);
376 		sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
377 		    sc->channels_alloc + 10, sizeof(*sc->channels));
378 		sc->channels_alloc += 10;
379 		debug2("channel: expanding %d", sc->channels_alloc);
380 	}
381 	/* Initialize and return new channel. */
382 	c = sc->channels[found] = xcalloc(1, sizeof(Channel));
383 	if ((c->input = sshbuf_new()) == NULL ||
384 	    (c->output = sshbuf_new()) == NULL ||
385 	    (c->extended = sshbuf_new()) == NULL)
386 		fatal_f("sshbuf_new failed");
387 	if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
388 		fatal_fr(r, "sshbuf_set_max_size");
389 	c->ostate = CHAN_OUTPUT_OPEN;
390 	c->istate = CHAN_INPUT_OPEN;
391 	channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
392 	c->self = found;
393 	c->type = type;
394 	c->ctype = ctype;
395 	c->local_window = window;
396 	c->local_window_max = window;
397 	c->local_maxpacket = maxpack;
398 	c->remote_name = xstrdup(remote_name);
399 	c->ctl_chan = -1;
400 	c->delayed = 1;		/* prevent call to channel_post handler */
401 	TAILQ_INIT(&c->status_confirms);
402 	debug("channel %d: new [%s]", found, remote_name);
403 	return c;
404 }
405 
406 static void
channel_find_maxfd(struct ssh_channels * sc)407 channel_find_maxfd(struct ssh_channels *sc)
408 {
409 	u_int i;
410 	int max = 0;
411 	Channel *c;
412 
413 	for (i = 0; i < sc->channels_alloc; i++) {
414 		c = sc->channels[i];
415 		if (c != NULL) {
416 			max = MAXIMUM(max, c->rfd);
417 			max = MAXIMUM(max, c->wfd);
418 			max = MAXIMUM(max, c->efd);
419 		}
420 	}
421 	sc->channel_max_fd = max;
422 }
423 
424 int
channel_close_fd(struct ssh * ssh,int * fdp)425 channel_close_fd(struct ssh *ssh, int *fdp)
426 {
427 	struct ssh_channels *sc = ssh->chanctxt;
428 	int ret = 0, fd = *fdp;
429 
430 	if (fd != -1) {
431 		ret = close(fd);
432 		*fdp = -1;
433 		if (fd == sc->channel_max_fd)
434 			channel_find_maxfd(sc);
435 	}
436 	return ret;
437 }
438 
439 /* Close all channel fd/socket. */
440 static void
channel_close_fds(struct ssh * ssh,Channel * c)441 channel_close_fds(struct ssh *ssh, Channel *c)
442 {
443 	int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
444 
445 	channel_close_fd(ssh, &c->sock);
446 	if (rfd != sock)
447 		channel_close_fd(ssh, &c->rfd);
448 	if (wfd != sock && wfd != rfd)
449 		channel_close_fd(ssh, &c->wfd);
450 	if (efd != sock && efd != rfd && efd != wfd)
451 		channel_close_fd(ssh, &c->efd);
452 }
453 
454 static void
fwd_perm_clear(struct permission * perm)455 fwd_perm_clear(struct permission *perm)
456 {
457 	free(perm->host_to_connect);
458 	free(perm->listen_host);
459 	free(perm->listen_path);
460 	memset(perm, 0, sizeof(*perm));
461 }
462 
463 /* Returns an printable name for the specified forwarding permission list */
464 static const char *
fwd_ident(int who,int where)465 fwd_ident(int who, int where)
466 {
467 	if (who == FORWARD_ADM) {
468 		if (where == FORWARD_LOCAL)
469 			return "admin local";
470 		else if (where == FORWARD_REMOTE)
471 			return "admin remote";
472 	} else if (who == FORWARD_USER) {
473 		if (where == FORWARD_LOCAL)
474 			return "user local";
475 		else if (where == FORWARD_REMOTE)
476 			return "user remote";
477 	}
478 	fatal("Unknown forward permission list %d/%d", who, where);
479 }
480 
481 /* Returns the forwarding permission list for the specified direction */
482 static struct permission_set *
permission_set_get(struct ssh * ssh,int where)483 permission_set_get(struct ssh *ssh, int where)
484 {
485 	struct ssh_channels *sc = ssh->chanctxt;
486 
487 	switch (where) {
488 	case FORWARD_LOCAL:
489 		return &sc->local_perms;
490 		break;
491 	case FORWARD_REMOTE:
492 		return &sc->remote_perms;
493 		break;
494 	default:
495 		fatal_f("invalid forwarding direction %d", where);
496 	}
497 }
498 
499 /* Returns pointers to the specified forwarding list and its element count */
500 static void
permission_set_get_array(struct ssh * ssh,int who,int where,struct permission *** permpp,u_int ** npermpp)501 permission_set_get_array(struct ssh *ssh, int who, int where,
502     struct permission ***permpp, u_int **npermpp)
503 {
504 	struct permission_set *pset = permission_set_get(ssh, where);
505 
506 	switch (who) {
507 	case FORWARD_USER:
508 		*permpp = &pset->permitted_user;
509 		*npermpp = &pset->num_permitted_user;
510 		break;
511 	case FORWARD_ADM:
512 		*permpp = &pset->permitted_admin;
513 		*npermpp = &pset->num_permitted_admin;
514 		break;
515 	default:
516 		fatal_f("invalid forwarding client %d", who);
517 	}
518 }
519 
520 /* Adds an entry to the spcified forwarding list */
521 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)522 permission_set_add(struct ssh *ssh, int who, int where,
523     const char *host_to_connect, int port_to_connect,
524     const char *listen_host, const char *listen_path, int listen_port,
525     Channel *downstream)
526 {
527 	struct permission **permp;
528 	u_int n, *npermp;
529 
530 	permission_set_get_array(ssh, who, where, &permp, &npermp);
531 
532 	if (*npermp >= INT_MAX)
533 		fatal_f("%s overflow", fwd_ident(who, where));
534 
535 	*permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
536 	n = (*npermp)++;
537 #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
538 	(*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
539 	(*permp)[n].port_to_connect = port_to_connect;
540 	(*permp)[n].listen_host = MAYBE_DUP(listen_host);
541 	(*permp)[n].listen_path = MAYBE_DUP(listen_path);
542 	(*permp)[n].listen_port = listen_port;
543 	(*permp)[n].downstream = downstream;
544 #undef MAYBE_DUP
545 	return (int)n;
546 }
547 
548 static void
mux_remove_remote_forwardings(struct ssh * ssh,Channel * c)549 mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
550 {
551 	struct ssh_channels *sc = ssh->chanctxt;
552 	struct permission_set *pset = &sc->local_perms;
553 	struct permission *perm;
554 	int r;
555 	u_int i;
556 
557 	for (i = 0; i < pset->num_permitted_user; i++) {
558 		perm = &pset->permitted_user[i];
559 		if (perm->downstream != c)
560 			continue;
561 
562 		/* cancel on the server, since mux client is gone */
563 		debug("channel %d: cleanup remote forward for %s:%u",
564 		    c->self, perm->listen_host, perm->listen_port);
565 		if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
566 		    (r = sshpkt_put_cstring(ssh,
567 		    "cancel-tcpip-forward")) != 0 ||
568 		    (r = sshpkt_put_u8(ssh, 0)) != 0 ||
569 		    (r = sshpkt_put_cstring(ssh,
570 		    channel_rfwd_bind_host(perm->listen_host))) != 0 ||
571 		    (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
572 		    (r = sshpkt_send(ssh)) != 0) {
573 			fatal_fr(r, "channel %i", c->self);
574 		}
575 		fwd_perm_clear(perm); /* unregister */
576 	}
577 }
578 
579 /* Free the channel and close its fd/socket. */
580 void
channel_free(struct ssh * ssh,Channel * c)581 channel_free(struct ssh *ssh, Channel *c)
582 {
583 	struct ssh_channels *sc = ssh->chanctxt;
584 	char *s;
585 	u_int i, n;
586 	Channel *other;
587 	struct channel_confirm *cc;
588 
589 	for (n = 0, i = 0; i < sc->channels_alloc; i++) {
590 		if ((other = sc->channels[i]) == NULL)
591 			continue;
592 		n++;
593 		/* detach from mux client and prepare for closing */
594 		if (c->type == SSH_CHANNEL_MUX_CLIENT &&
595 		    other->type == SSH_CHANNEL_MUX_PROXY &&
596 		    other->mux_ctx == c) {
597 			other->mux_ctx = NULL;
598 			other->type = SSH_CHANNEL_OPEN;
599 			other->istate = CHAN_INPUT_CLOSED;
600 			other->ostate = CHAN_OUTPUT_CLOSED;
601 		}
602 	}
603 	debug("channel %d: free: %s, nchannels %u", c->self,
604 	    c->remote_name ? c->remote_name : "???", n);
605 
606 	if (c->type == SSH_CHANNEL_MUX_CLIENT)
607 		mux_remove_remote_forwardings(ssh, c);
608 	else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
609 		free(c->mux_ctx);
610 		c->mux_ctx = NULL;
611 	}
612 
613 	if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
614 		s = channel_open_message(ssh);
615 		debug3("channel %d: status: %s", c->self, s);
616 		free(s);
617 	}
618 
619 	channel_close_fds(ssh, c);
620 	sshbuf_free(c->input);
621 	sshbuf_free(c->output);
622 	sshbuf_free(c->extended);
623 	c->input = c->output = c->extended = NULL;
624 	free(c->remote_name);
625 	c->remote_name = NULL;
626 	free(c->path);
627 	c->path = NULL;
628 	free(c->listening_addr);
629 	c->listening_addr = NULL;
630 	while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
631 		if (cc->abandon_cb != NULL)
632 			cc->abandon_cb(ssh, c, cc->ctx);
633 		TAILQ_REMOVE(&c->status_confirms, cc, entry);
634 		freezero(cc, sizeof(*cc));
635 	}
636 	if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
637 		c->filter_cleanup(ssh, c->self, c->filter_ctx);
638 	sc->channels[c->self] = NULL;
639 	freezero(c, sizeof(*c));
640 }
641 
642 void
channel_free_all(struct ssh * ssh)643 channel_free_all(struct ssh *ssh)
644 {
645 	u_int i;
646 	struct ssh_channels *sc = ssh->chanctxt;
647 
648 	for (i = 0; i < sc->channels_alloc; i++)
649 		if (sc->channels[i] != NULL)
650 			channel_free(ssh, sc->channels[i]);
651 
652 	free(sc->channels);
653 	sc->channels = NULL;
654 	sc->channels_alloc = 0;
655 	sc->channel_max_fd = 0;
656 
657 	free(sc->x11_saved_display);
658 	sc->x11_saved_display = NULL;
659 
660 	free(sc->x11_saved_proto);
661 	sc->x11_saved_proto = NULL;
662 
663 	free(sc->x11_saved_data);
664 	sc->x11_saved_data = NULL;
665 	sc->x11_saved_data_len = 0;
666 
667 	free(sc->x11_fake_data);
668 	sc->x11_fake_data = NULL;
669 	sc->x11_fake_data_len = 0;
670 }
671 
672 /*
673  * Closes the sockets/fds of all channels.  This is used to close extra file
674  * descriptors after a fork.
675  */
676 void
channel_close_all(struct ssh * ssh)677 channel_close_all(struct ssh *ssh)
678 {
679 	u_int i;
680 
681 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
682 		if (ssh->chanctxt->channels[i] != NULL)
683 			channel_close_fds(ssh, ssh->chanctxt->channels[i]);
684 }
685 
686 /*
687  * Stop listening to channels.
688  */
689 void
channel_stop_listening(struct ssh * ssh)690 channel_stop_listening(struct ssh *ssh)
691 {
692 	u_int i;
693 	Channel *c;
694 
695 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
696 		c = ssh->chanctxt->channels[i];
697 		if (c != NULL) {
698 			switch (c->type) {
699 			case SSH_CHANNEL_AUTH_SOCKET:
700 			case SSH_CHANNEL_PORT_LISTENER:
701 			case SSH_CHANNEL_RPORT_LISTENER:
702 			case SSH_CHANNEL_X11_LISTENER:
703 			case SSH_CHANNEL_UNIX_LISTENER:
704 			case SSH_CHANNEL_RUNIX_LISTENER:
705 				channel_close_fd(ssh, &c->sock);
706 				channel_free(ssh, c);
707 				break;
708 			}
709 		}
710 	}
711 }
712 
713 /*
714  * Returns true if no channel has too much buffered data, and false if one or
715  * more channel is overfull.
716  */
717 int
channel_not_very_much_buffered_data(struct ssh * ssh)718 channel_not_very_much_buffered_data(struct ssh *ssh)
719 {
720 	u_int i;
721 	u_int maxsize = ssh_packet_get_maxsize(ssh);
722 	Channel *c;
723 
724 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
725 		c = ssh->chanctxt->channels[i];
726 		if (c == NULL || c->type != SSH_CHANNEL_OPEN)
727 			continue;
728 		if (sshbuf_len(c->output) > maxsize) {
729 			debug2("channel %d: big output buffer %zu > %u",
730 			    c->self, sshbuf_len(c->output), maxsize);
731 			return 0;
732 		}
733 	}
734 	return 1;
735 }
736 
737 /* Returns true if any channel is still open. */
738 int
channel_still_open(struct ssh * ssh)739 channel_still_open(struct ssh *ssh)
740 {
741 	u_int i;
742 	Channel *c;
743 
744 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
745 		c = ssh->chanctxt->channels[i];
746 		if (c == NULL)
747 			continue;
748 		switch (c->type) {
749 		case SSH_CHANNEL_X11_LISTENER:
750 		case SSH_CHANNEL_PORT_LISTENER:
751 		case SSH_CHANNEL_RPORT_LISTENER:
752 		case SSH_CHANNEL_MUX_LISTENER:
753 		case SSH_CHANNEL_CLOSED:
754 		case SSH_CHANNEL_AUTH_SOCKET:
755 		case SSH_CHANNEL_DYNAMIC:
756 		case SSH_CHANNEL_RDYNAMIC_OPEN:
757 		case SSH_CHANNEL_CONNECTING:
758 		case SSH_CHANNEL_ZOMBIE:
759 		case SSH_CHANNEL_ABANDONED:
760 		case SSH_CHANNEL_UNIX_LISTENER:
761 		case SSH_CHANNEL_RUNIX_LISTENER:
762 			continue;
763 		case SSH_CHANNEL_LARVAL:
764 			continue;
765 		case SSH_CHANNEL_OPENING:
766 		case SSH_CHANNEL_OPEN:
767 		case SSH_CHANNEL_RDYNAMIC_FINISH:
768 		case SSH_CHANNEL_X11_OPEN:
769 		case SSH_CHANNEL_MUX_CLIENT:
770 		case SSH_CHANNEL_MUX_PROXY:
771 			return 1;
772 		default:
773 			fatal_f("bad channel type %d", c->type);
774 			/* NOTREACHED */
775 		}
776 	}
777 	return 0;
778 }
779 
780 /* Returns the id of an open channel suitable for keepaliving */
781 int
channel_find_open(struct ssh * ssh)782 channel_find_open(struct ssh *ssh)
783 {
784 	u_int i;
785 	Channel *c;
786 
787 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
788 		c = ssh->chanctxt->channels[i];
789 		if (c == NULL || !c->have_remote_id)
790 			continue;
791 		switch (c->type) {
792 		case SSH_CHANNEL_CLOSED:
793 		case SSH_CHANNEL_DYNAMIC:
794 		case SSH_CHANNEL_RDYNAMIC_OPEN:
795 		case SSH_CHANNEL_RDYNAMIC_FINISH:
796 		case SSH_CHANNEL_X11_LISTENER:
797 		case SSH_CHANNEL_PORT_LISTENER:
798 		case SSH_CHANNEL_RPORT_LISTENER:
799 		case SSH_CHANNEL_MUX_LISTENER:
800 		case SSH_CHANNEL_MUX_CLIENT:
801 		case SSH_CHANNEL_MUX_PROXY:
802 		case SSH_CHANNEL_OPENING:
803 		case SSH_CHANNEL_CONNECTING:
804 		case SSH_CHANNEL_ZOMBIE:
805 		case SSH_CHANNEL_ABANDONED:
806 		case SSH_CHANNEL_UNIX_LISTENER:
807 		case SSH_CHANNEL_RUNIX_LISTENER:
808 			continue;
809 		case SSH_CHANNEL_LARVAL:
810 		case SSH_CHANNEL_AUTH_SOCKET:
811 		case SSH_CHANNEL_OPEN:
812 		case SSH_CHANNEL_X11_OPEN:
813 			return i;
814 		default:
815 			fatal_f("bad channel type %d", c->type);
816 			/* NOTREACHED */
817 		}
818 	}
819 	return -1;
820 }
821 
822 /* Returns the state of the channel's extended usage flag */
823 const char *
channel_format_extended_usage(const Channel * c)824 channel_format_extended_usage(const Channel *c)
825 {
826 	if (c->efd == -1)
827 		return "closed";
828 
829 	switch (c->extended_usage) {
830 	case CHAN_EXTENDED_WRITE:
831 		return "write";
832 	case CHAN_EXTENDED_READ:
833 		return "read";
834 	case CHAN_EXTENDED_IGNORE:
835 		return "ignore";
836 	default:
837 		return "UNKNOWN";
838 	}
839 }
840 
841 static char *
channel_format_status(const Channel * c)842 channel_format_status(const Channel *c)
843 {
844 	char *ret = NULL;
845 
846 	xasprintf(&ret, "t%d %s%u i%u/%zu o%u/%zu e[%s]/%zu "
847 	    "fd %d/%d/%d sock %d cc %d",
848 	    c->type,
849 	    c->have_remote_id ? "r" : "nr", c->remote_id,
850 	    c->istate, sshbuf_len(c->input),
851 	    c->ostate, sshbuf_len(c->output),
852 	    channel_format_extended_usage(c), sshbuf_len(c->extended),
853 	    c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan);
854 	return ret;
855 }
856 
857 /*
858  * Returns a message describing the currently open forwarded connections,
859  * suitable for sending to the client.  The message contains crlf pairs for
860  * newlines.
861  */
862 char *
channel_open_message(struct ssh * ssh)863 channel_open_message(struct ssh *ssh)
864 {
865 	struct sshbuf *buf;
866 	Channel *c;
867 	u_int i;
868 	int r;
869 	char *cp, *ret;
870 
871 	if ((buf = sshbuf_new()) == NULL)
872 		fatal_f("sshbuf_new");
873 	if ((r = sshbuf_putf(buf,
874 	    "The following connections are open:\r\n")) != 0)
875 		fatal_fr(r, "sshbuf_putf");
876 	for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
877 		c = ssh->chanctxt->channels[i];
878 		if (c == NULL)
879 			continue;
880 		switch (c->type) {
881 		case SSH_CHANNEL_X11_LISTENER:
882 		case SSH_CHANNEL_PORT_LISTENER:
883 		case SSH_CHANNEL_RPORT_LISTENER:
884 		case SSH_CHANNEL_CLOSED:
885 		case SSH_CHANNEL_AUTH_SOCKET:
886 		case SSH_CHANNEL_ZOMBIE:
887 		case SSH_CHANNEL_ABANDONED:
888 		case SSH_CHANNEL_MUX_LISTENER:
889 		case SSH_CHANNEL_UNIX_LISTENER:
890 		case SSH_CHANNEL_RUNIX_LISTENER:
891 			continue;
892 		case SSH_CHANNEL_LARVAL:
893 		case SSH_CHANNEL_OPENING:
894 		case SSH_CHANNEL_CONNECTING:
895 		case SSH_CHANNEL_DYNAMIC:
896 		case SSH_CHANNEL_RDYNAMIC_OPEN:
897 		case SSH_CHANNEL_RDYNAMIC_FINISH:
898 		case SSH_CHANNEL_OPEN:
899 		case SSH_CHANNEL_X11_OPEN:
900 		case SSH_CHANNEL_MUX_PROXY:
901 		case SSH_CHANNEL_MUX_CLIENT:
902 			cp = channel_format_status(c);
903 			if ((r = sshbuf_putf(buf, "  #%d %.300s (%s)\r\n",
904 			    c->self, c->remote_name, cp)) != 0) {
905 				free(cp);
906 				fatal_fr(r, "sshbuf_putf");
907 			}
908 			free(cp);
909 			continue;
910 		default:
911 			fatal_f("bad channel type %d", c->type);
912 			/* NOTREACHED */
913 		}
914 	}
915 	if ((ret = sshbuf_dup_string(buf)) == NULL)
916 		fatal_f("sshbuf_dup_string");
917 	sshbuf_free(buf);
918 	return ret;
919 }
920 
921 static void
open_preamble(struct ssh * ssh,const char * where,Channel * c,const char * type)922 open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
923 {
924 	int r;
925 
926 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
927 	    (r = sshpkt_put_cstring(ssh, type)) != 0 ||
928 	    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
929 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
930 	    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
931 		fatal_r(r, "%s: channel %i: open", where, c->self);
932 	}
933 }
934 
935 void
channel_send_open(struct ssh * ssh,int id)936 channel_send_open(struct ssh *ssh, int id)
937 {
938 	Channel *c = channel_lookup(ssh, id);
939 	int r;
940 
941 	if (c == NULL) {
942 		logit("channel_send_open: %d: bad id", id);
943 		return;
944 	}
945 	debug2("channel %d: send open", id);
946 	open_preamble(ssh, __func__, c, c->ctype);
947 	if ((r = sshpkt_send(ssh)) != 0)
948 		fatal_fr(r, "channel %i", c->self);
949 }
950 
951 void
channel_request_start(struct ssh * ssh,int id,char * service,int wantconfirm)952 channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
953 {
954 	Channel *c = channel_lookup(ssh, id);
955 	int r;
956 
957 	if (c == NULL) {
958 		logit_f("%d: unknown channel id", id);
959 		return;
960 	}
961 	if (!c->have_remote_id)
962 		fatal_f("channel %d: no remote id", c->self);
963 
964 	debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
965 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
966 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
967 	    (r = sshpkt_put_cstring(ssh, service)) != 0 ||
968 	    (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
969 		fatal_fr(r, "channel %i", c->self);
970 	}
971 }
972 
973 void
channel_register_status_confirm(struct ssh * ssh,int id,channel_confirm_cb * cb,channel_confirm_abandon_cb * abandon_cb,void * ctx)974 channel_register_status_confirm(struct ssh *ssh, int id,
975     channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
976 {
977 	struct channel_confirm *cc;
978 	Channel *c;
979 
980 	if ((c = channel_lookup(ssh, id)) == NULL)
981 		fatal_f("%d: bad id", id);
982 
983 	cc = xcalloc(1, sizeof(*cc));
984 	cc->cb = cb;
985 	cc->abandon_cb = abandon_cb;
986 	cc->ctx = ctx;
987 	TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
988 }
989 
990 void
channel_register_open_confirm(struct ssh * ssh,int id,channel_open_fn * fn,void * ctx)991 channel_register_open_confirm(struct ssh *ssh, int id,
992     channel_open_fn *fn, void *ctx)
993 {
994 	Channel *c = channel_lookup(ssh, id);
995 
996 	if (c == NULL) {
997 		logit_f("%d: bad id", id);
998 		return;
999 	}
1000 	c->open_confirm = fn;
1001 	c->open_confirm_ctx = ctx;
1002 }
1003 
1004 void
channel_register_cleanup(struct ssh * ssh,int id,channel_callback_fn * fn,int do_close)1005 channel_register_cleanup(struct ssh *ssh, int id,
1006     channel_callback_fn *fn, int do_close)
1007 {
1008 	Channel *c = channel_by_id(ssh, id);
1009 
1010 	if (c == NULL) {
1011 		logit_f("%d: bad id", id);
1012 		return;
1013 	}
1014 	c->detach_user = fn;
1015 	c->detach_close = do_close;
1016 }
1017 
1018 void
channel_cancel_cleanup(struct ssh * ssh,int id)1019 channel_cancel_cleanup(struct ssh *ssh, int id)
1020 {
1021 	Channel *c = channel_by_id(ssh, id);
1022 
1023 	if (c == NULL) {
1024 		logit_f("%d: bad id", id);
1025 		return;
1026 	}
1027 	c->detach_user = NULL;
1028 	c->detach_close = 0;
1029 }
1030 
1031 void
channel_register_filter(struct ssh * ssh,int id,channel_infilter_fn * ifn,channel_outfilter_fn * ofn,channel_filter_cleanup_fn * cfn,void * ctx)1032 channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
1033     channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
1034 {
1035 	Channel *c = channel_lookup(ssh, id);
1036 
1037 	if (c == NULL) {
1038 		logit_f("%d: bad id", id);
1039 		return;
1040 	}
1041 	c->input_filter = ifn;
1042 	c->output_filter = ofn;
1043 	c->filter_ctx = ctx;
1044 	c->filter_cleanup = cfn;
1045 }
1046 
1047 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)1048 channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
1049     int extusage, int nonblock, int is_tty, u_int window_max)
1050 {
1051 	Channel *c = channel_lookup(ssh, id);
1052 	int r;
1053 
1054 	if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
1055 		fatal("channel_activate for non-larval channel %d.", id);
1056 	if (!c->have_remote_id)
1057 		fatal_f("channel %d: no remote id", c->self);
1058 
1059 	channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
1060 	c->type = SSH_CHANNEL_OPEN;
1061 	c->local_window = c->local_window_max = window_max;
1062 
1063 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
1064 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1065 	    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1066 	    (r = sshpkt_send(ssh)) != 0)
1067 		fatal_fr(r, "channel %i", c->self);
1068 }
1069 
1070 static void
channel_pre_listener(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1071 channel_pre_listener(struct ssh *ssh, Channel *c,
1072     fd_set *readset, fd_set *writeset)
1073 {
1074 	FD_SET(c->sock, readset);
1075 }
1076 
1077 static void
channel_pre_connecting(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1078 channel_pre_connecting(struct ssh *ssh, Channel *c,
1079     fd_set *readset, fd_set *writeset)
1080 {
1081 	debug3("channel %d: waiting for connection", c->self);
1082 	FD_SET(c->sock, writeset);
1083 }
1084 
1085 static void
channel_pre_open(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1086 channel_pre_open(struct ssh *ssh, Channel *c,
1087     fd_set *readset, fd_set *writeset)
1088 {
1089 	if (c->istate == CHAN_INPUT_OPEN &&
1090 	    c->remote_window > 0 &&
1091 	    sshbuf_len(c->input) < c->remote_window &&
1092 	    sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1093 		FD_SET(c->rfd, readset);
1094 	if (c->ostate == CHAN_OUTPUT_OPEN ||
1095 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1096 		if (sshbuf_len(c->output) > 0) {
1097 			FD_SET(c->wfd, writeset);
1098 		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1099 			if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
1100 				debug2("channel %d: "
1101 				    "obuf_empty delayed efd %d/(%zu)", c->self,
1102 				    c->efd, sshbuf_len(c->extended));
1103 			else
1104 				chan_obuf_empty(ssh, c);
1105 		}
1106 	}
1107 	/** XXX check close conditions, too */
1108 	if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
1109 	    c->ostate == CHAN_OUTPUT_CLOSED)) {
1110 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1111 		    sshbuf_len(c->extended) > 0)
1112 			FD_SET(c->efd, writeset);
1113 		else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
1114 		    (c->extended_usage == CHAN_EXTENDED_READ ||
1115 		    c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1116 		    sshbuf_len(c->extended) < c->remote_window)
1117 			FD_SET(c->efd, readset);
1118 	}
1119 	/* XXX: What about efd? races? */
1120 }
1121 
1122 /*
1123  * This is a special state for X11 authentication spoofing.  An opened X11
1124  * connection (when authentication spoofing is being done) remains in this
1125  * state until the first packet has been completely read.  The authentication
1126  * data in that packet is then substituted by the real data if it matches the
1127  * fake data, and the channel is put into normal mode.
1128  * XXX All this happens at the client side.
1129  * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
1130  */
1131 static int
x11_open_helper(struct ssh * ssh,struct sshbuf * b)1132 x11_open_helper(struct ssh *ssh, struct sshbuf *b)
1133 {
1134 	struct ssh_channels *sc = ssh->chanctxt;
1135 	u_char *ucp;
1136 	u_int proto_len, data_len;
1137 
1138 	/* Is this being called after the refusal deadline? */
1139 	if (sc->x11_refuse_time != 0 &&
1140 	    (u_int)monotime() >= sc->x11_refuse_time) {
1141 		verbose("Rejected X11 connection after ForwardX11Timeout "
1142 		    "expired");
1143 		return -1;
1144 	}
1145 
1146 	/* Check if the fixed size part of the packet is in buffer. */
1147 	if (sshbuf_len(b) < 12)
1148 		return 0;
1149 
1150 	/* Parse the lengths of variable-length fields. */
1151 	ucp = sshbuf_mutable_ptr(b);
1152 	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
1153 		proto_len = 256 * ucp[6] + ucp[7];
1154 		data_len = 256 * ucp[8] + ucp[9];
1155 	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
1156 		proto_len = ucp[6] + 256 * ucp[7];
1157 		data_len = ucp[8] + 256 * ucp[9];
1158 	} else {
1159 		debug2("Initial X11 packet contains bad byte order byte: 0x%x",
1160 		    ucp[0]);
1161 		return -1;
1162 	}
1163 
1164 	/* Check if the whole packet is in buffer. */
1165 	if (sshbuf_len(b) <
1166 	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
1167 		return 0;
1168 
1169 	/* Check if authentication protocol matches. */
1170 	if (proto_len != strlen(sc->x11_saved_proto) ||
1171 	    memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
1172 		debug2("X11 connection uses different authentication protocol.");
1173 		return -1;
1174 	}
1175 	/* Check if authentication data matches our fake data. */
1176 	if (data_len != sc->x11_fake_data_len ||
1177 	    timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
1178 		sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
1179 		debug2("X11 auth data does not match fake data.");
1180 		return -1;
1181 	}
1182 	/* Check fake data length */
1183 	if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
1184 		error("X11 fake_data_len %d != saved_data_len %d",
1185 		    sc->x11_fake_data_len, sc->x11_saved_data_len);
1186 		return -1;
1187 	}
1188 	/*
1189 	 * Received authentication protocol and data match
1190 	 * our fake data. Substitute the fake data with real
1191 	 * data.
1192 	 */
1193 	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
1194 	    sc->x11_saved_data, sc->x11_saved_data_len);
1195 	return 1;
1196 }
1197 
1198 static void
channel_pre_x11_open(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1199 channel_pre_x11_open(struct ssh *ssh, Channel *c,
1200     fd_set *readset, fd_set *writeset)
1201 {
1202 	int ret = x11_open_helper(ssh, c->output);
1203 
1204 	/* c->force_drain = 1; */
1205 
1206 	if (ret == 1) {
1207 		c->type = SSH_CHANNEL_OPEN;
1208 		channel_pre_open(ssh, c, readset, writeset);
1209 	} else if (ret == -1) {
1210 		logit("X11 connection rejected because of wrong authentication.");
1211 		debug2("X11 rejected %d i%d/o%d",
1212 		    c->self, c->istate, c->ostate);
1213 		chan_read_failed(ssh, c);
1214 		sshbuf_reset(c->input);
1215 		chan_ibuf_empty(ssh, c);
1216 		sshbuf_reset(c->output);
1217 		chan_write_failed(ssh, c);
1218 		debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1219 	}
1220 }
1221 
1222 static void
channel_pre_mux_client(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1223 channel_pre_mux_client(struct ssh *ssh,
1224     Channel *c, fd_set *readset, fd_set *writeset)
1225 {
1226 	if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1227 	    sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
1228 		FD_SET(c->rfd, readset);
1229 	if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1230 		/* clear buffer immediately (discard any partial packet) */
1231 		sshbuf_reset(c->input);
1232 		chan_ibuf_empty(ssh, c);
1233 		/* Start output drain. XXX just kill chan? */
1234 		chan_rcvd_oclose(ssh, c);
1235 	}
1236 	if (c->ostate == CHAN_OUTPUT_OPEN ||
1237 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1238 		if (sshbuf_len(c->output) > 0)
1239 			FD_SET(c->wfd, writeset);
1240 		else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1241 			chan_obuf_empty(ssh, c);
1242 	}
1243 }
1244 
1245 /* try to decode a socks4 header */
1246 static int
channel_decode_socks4(Channel * c,struct sshbuf * input,struct sshbuf * output)1247 channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
1248 {
1249 	const u_char *p;
1250 	char *host;
1251 	u_int len, have, i, found, need;
1252 	char username[256];
1253 	struct {
1254 		u_int8_t version;
1255 		u_int8_t command;
1256 		u_int16_t dest_port;
1257 		struct in_addr dest_addr;
1258 	} s4_req, s4_rsp;
1259 	int r;
1260 
1261 	debug2("channel %d: decode socks4", c->self);
1262 
1263 	have = sshbuf_len(input);
1264 	len = sizeof(s4_req);
1265 	if (have < len)
1266 		return 0;
1267 	p = sshbuf_ptr(input);
1268 
1269 	need = 1;
1270 	/* SOCKS4A uses an invalid IP address 0.0.0.x */
1271 	if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1272 		debug2("channel %d: socks4a request", c->self);
1273 		/* ... and needs an extra string (the hostname) */
1274 		need = 2;
1275 	}
1276 	/* Check for terminating NUL on the string(s) */
1277 	for (found = 0, i = len; i < have; i++) {
1278 		if (p[i] == '\0') {
1279 			found++;
1280 			if (found == need)
1281 				break;
1282 		}
1283 		if (i > 1024) {
1284 			/* the peer is probably sending garbage */
1285 			debug("channel %d: decode socks4: too long",
1286 			    c->self);
1287 			return -1;
1288 		}
1289 	}
1290 	if (found < need)
1291 		return 0;
1292 	if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
1293 	    (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
1294 	    (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
1295 	    (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
1296 		debug_r(r, "channels %d: decode socks4", c->self);
1297 		return -1;
1298 	}
1299 	have = sshbuf_len(input);
1300 	p = sshbuf_ptr(input);
1301 	if (memchr(p, '\0', have) == NULL) {
1302 		error("channel %d: decode socks4: unterminated user", c->self);
1303 		return -1;
1304 	}
1305 	len = strlen(p);
1306 	debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1307 	len++; /* trailing '\0' */
1308 	strlcpy(username, p, sizeof(username));
1309 	if ((r = sshbuf_consume(input, len)) != 0)
1310 		fatal_fr(r, "channel %d: consume", c->self);
1311 	free(c->path);
1312 	c->path = NULL;
1313 	if (need == 1) {			/* SOCKS4: one string */
1314 		host = inet_ntoa(s4_req.dest_addr);
1315 		c->path = xstrdup(host);
1316 	} else {				/* SOCKS4A: two strings */
1317 		have = sshbuf_len(input);
1318 		p = sshbuf_ptr(input);
1319 		if (memchr(p, '\0', have) == NULL) {
1320 			error("channel %d: decode socks4a: host not nul "
1321 			    "terminated", c->self);
1322 			return -1;
1323 		}
1324 		len = strlen(p);
1325 		debug2("channel %d: decode socks4a: host %s/%d",
1326 		    c->self, p, len);
1327 		len++;				/* trailing '\0' */
1328 		if (len > NI_MAXHOST) {
1329 			error("channel %d: hostname \"%.100s\" too long",
1330 			    c->self, p);
1331 			return -1;
1332 		}
1333 		c->path = xstrdup(p);
1334 		if ((r = sshbuf_consume(input, len)) != 0)
1335 			fatal_fr(r, "channel %d: consume", c->self);
1336 	}
1337 	c->host_port = ntohs(s4_req.dest_port);
1338 
1339 	debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1340 	    c->self, c->path, c->host_port, s4_req.command);
1341 
1342 	if (s4_req.command != 1) {
1343 		debug("channel %d: cannot handle: %s cn %d",
1344 		    c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1345 		return -1;
1346 	}
1347 	s4_rsp.version = 0;			/* vn: 0 for reply */
1348 	s4_rsp.command = 90;			/* cd: req granted */
1349 	s4_rsp.dest_port = 0;			/* ignored */
1350 	s4_rsp.dest_addr.s_addr = INADDR_ANY;	/* ignored */
1351 	if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0)
1352 		fatal_fr(r, "channel %d: append reply", c->self);
1353 	return 1;
1354 }
1355 
1356 /* try to decode a socks5 header */
1357 #define SSH_SOCKS5_AUTHDONE	0x1000
1358 #define SSH_SOCKS5_NOAUTH	0x00
1359 #define SSH_SOCKS5_IPV4		0x01
1360 #define SSH_SOCKS5_DOMAIN	0x03
1361 #define SSH_SOCKS5_IPV6		0x04
1362 #define SSH_SOCKS5_CONNECT	0x01
1363 #define SSH_SOCKS5_SUCCESS	0x00
1364 
1365 static int
channel_decode_socks5(Channel * c,struct sshbuf * input,struct sshbuf * output)1366 channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
1367 {
1368 	/* XXX use get/put_u8 instead of trusting struct padding */
1369 	struct {
1370 		u_int8_t version;
1371 		u_int8_t command;
1372 		u_int8_t reserved;
1373 		u_int8_t atyp;
1374 	} s5_req, s5_rsp;
1375 	u_int16_t dest_port;
1376 	char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1377 	const u_char *p;
1378 	u_int have, need, i, found, nmethods, addrlen, af;
1379 	int r;
1380 
1381 	debug2("channel %d: decode socks5", c->self);
1382 	p = sshbuf_ptr(input);
1383 	if (p[0] != 0x05)
1384 		return -1;
1385 	have = sshbuf_len(input);
1386 	if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1387 		/* format: ver | nmethods | methods */
1388 		if (have < 2)
1389 			return 0;
1390 		nmethods = p[1];
1391 		if (have < nmethods + 2)
1392 			return 0;
1393 		/* look for method: "NO AUTHENTICATION REQUIRED" */
1394 		for (found = 0, i = 2; i < nmethods + 2; i++) {
1395 			if (p[i] == SSH_SOCKS5_NOAUTH) {
1396 				found = 1;
1397 				break;
1398 			}
1399 		}
1400 		if (!found) {
1401 			debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1402 			    c->self);
1403 			return -1;
1404 		}
1405 		if ((r = sshbuf_consume(input, nmethods + 2)) != 0)
1406 			fatal_fr(r, "channel %d: consume", c->self);
1407 		/* version, method */
1408 		if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
1409 		    (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0)
1410 			fatal_fr(r, "channel %d: append reply", c->self);
1411 		c->flags |= SSH_SOCKS5_AUTHDONE;
1412 		debug2("channel %d: socks5 auth done", c->self);
1413 		return 0;				/* need more */
1414 	}
1415 	debug2("channel %d: socks5 post auth", c->self);
1416 	if (have < sizeof(s5_req)+1)
1417 		return 0;			/* need more */
1418 	memcpy(&s5_req, p, sizeof(s5_req));
1419 	if (s5_req.version != 0x05 ||
1420 	    s5_req.command != SSH_SOCKS5_CONNECT ||
1421 	    s5_req.reserved != 0x00) {
1422 		debug2("channel %d: only socks5 connect supported", c->self);
1423 		return -1;
1424 	}
1425 	switch (s5_req.atyp){
1426 	case SSH_SOCKS5_IPV4:
1427 		addrlen = 4;
1428 		af = AF_INET;
1429 		break;
1430 	case SSH_SOCKS5_DOMAIN:
1431 		addrlen = p[sizeof(s5_req)];
1432 		af = -1;
1433 		break;
1434 	case SSH_SOCKS5_IPV6:
1435 		addrlen = 16;
1436 		af = AF_INET6;
1437 		break;
1438 	default:
1439 		debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1440 		return -1;
1441 	}
1442 	need = sizeof(s5_req) + addrlen + 2;
1443 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1444 		need++;
1445 	if (have < need)
1446 		return 0;
1447 	if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0)
1448 		fatal_fr(r, "channel %d: consume", c->self);
1449 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1450 		/* host string length */
1451 		if ((r = sshbuf_consume(input, 1)) != 0)
1452 			fatal_fr(r, "channel %d: consume", c->self);
1453 	}
1454 	if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
1455 	    (r = sshbuf_get(input, &dest_port, 2)) != 0) {
1456 		debug_r(r, "channel %d: parse addr/port", c->self);
1457 		return -1;
1458 	}
1459 	dest_addr[addrlen] = '\0';
1460 	free(c->path);
1461 	c->path = NULL;
1462 	if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1463 		if (addrlen >= NI_MAXHOST) {
1464 			error("channel %d: dynamic request: socks5 hostname "
1465 			    "\"%.100s\" too long", c->self, dest_addr);
1466 			return -1;
1467 		}
1468 		c->path = xstrdup(dest_addr);
1469 	} else {
1470 		if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1471 			return -1;
1472 		c->path = xstrdup(ntop);
1473 	}
1474 	c->host_port = ntohs(dest_port);
1475 
1476 	debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1477 	    c->self, c->path, c->host_port, s5_req.command);
1478 
1479 	s5_rsp.version = 0x05;
1480 	s5_rsp.command = SSH_SOCKS5_SUCCESS;
1481 	s5_rsp.reserved = 0;			/* ignored */
1482 	s5_rsp.atyp = SSH_SOCKS5_IPV4;
1483 	dest_port = 0;				/* ignored */
1484 
1485 	if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
1486 	    (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
1487 	    (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
1488 		fatal_fr(r, "channel %d: append reply", c->self);
1489 	return 1;
1490 }
1491 
1492 Channel *
channel_connect_stdio_fwd(struct ssh * ssh,const char * host_to_connect,u_short port_to_connect,int in,int out)1493 channel_connect_stdio_fwd(struct ssh *ssh,
1494     const char *host_to_connect, u_short port_to_connect, int in, int out)
1495 {
1496 	Channel *c;
1497 
1498 	debug_f("%s:%d", host_to_connect, port_to_connect);
1499 
1500 	c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
1501 	    -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1502 	    0, "stdio-forward", /*nonblock*/0);
1503 
1504 	c->path = xstrdup(host_to_connect);
1505 	c->host_port = port_to_connect;
1506 	c->listening_port = 0;
1507 	c->force_drain = 1;
1508 
1509 	channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
1510 	port_open_helper(ssh, c, "direct-tcpip");
1511 
1512 	return c;
1513 }
1514 
1515 /* dynamic port forwarding */
1516 static void
channel_pre_dynamic(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1517 channel_pre_dynamic(struct ssh *ssh, Channel *c,
1518     fd_set *readset, fd_set *writeset)
1519 {
1520 	const u_char *p;
1521 	u_int have;
1522 	int ret;
1523 
1524 	have = sshbuf_len(c->input);
1525 	debug2("channel %d: pre_dynamic: have %d", c->self, have);
1526 	/* sshbuf_dump(c->input, stderr); */
1527 	/* check if the fixed size part of the packet is in buffer. */
1528 	if (have < 3) {
1529 		/* need more */
1530 		FD_SET(c->sock, readset);
1531 		return;
1532 	}
1533 	/* try to guess the protocol */
1534 	p = sshbuf_ptr(c->input);
1535 	/* XXX sshbuf_peek_u8? */
1536 	switch (p[0]) {
1537 	case 0x04:
1538 		ret = channel_decode_socks4(c, c->input, c->output);
1539 		break;
1540 	case 0x05:
1541 		ret = channel_decode_socks5(c, c->input, c->output);
1542 		break;
1543 	default:
1544 		ret = -1;
1545 		break;
1546 	}
1547 	if (ret < 0) {
1548 		chan_mark_dead(ssh, c);
1549 	} else if (ret == 0) {
1550 		debug2("channel %d: pre_dynamic: need more", c->self);
1551 		/* need more */
1552 		FD_SET(c->sock, readset);
1553 		if (sshbuf_len(c->output))
1554 			FD_SET(c->sock, writeset);
1555 	} else {
1556 		/* switch to the next state */
1557 		c->type = SSH_CHANNEL_OPENING;
1558 		port_open_helper(ssh, c, "direct-tcpip");
1559 	}
1560 }
1561 
1562 /* simulate read-error */
1563 static void
rdynamic_close(struct ssh * ssh,Channel * c)1564 rdynamic_close(struct ssh *ssh, Channel *c)
1565 {
1566 	c->type = SSH_CHANNEL_OPEN;
1567 	chan_read_failed(ssh, c);
1568 	sshbuf_reset(c->input);
1569 	chan_ibuf_empty(ssh, c);
1570 	sshbuf_reset(c->output);
1571 	chan_write_failed(ssh, c);
1572 }
1573 
1574 /* reverse dynamic port forwarding */
1575 static void
channel_before_prepare_select_rdynamic(struct ssh * ssh,Channel * c)1576 channel_before_prepare_select_rdynamic(struct ssh *ssh, Channel *c)
1577 {
1578 	const u_char *p;
1579 	u_int have, len;
1580 	int r, ret;
1581 
1582 	have = sshbuf_len(c->output);
1583 	debug2("channel %d: pre_rdynamic: have %d", c->self, have);
1584 	/* sshbuf_dump(c->output, stderr); */
1585 	/* EOF received */
1586 	if (c->flags & CHAN_EOF_RCVD) {
1587 		if ((r = sshbuf_consume(c->output, have)) != 0)
1588 			fatal_fr(r, "channel %d: consume", c->self);
1589 		rdynamic_close(ssh, c);
1590 		return;
1591 	}
1592 	/* check if the fixed size part of the packet is in buffer. */
1593 	if (have < 3)
1594 		return;
1595 	/* try to guess the protocol */
1596 	p = sshbuf_ptr(c->output);
1597 	switch (p[0]) {
1598 	case 0x04:
1599 		/* switch input/output for reverse forwarding */
1600 		ret = channel_decode_socks4(c, c->output, c->input);
1601 		break;
1602 	case 0x05:
1603 		ret = channel_decode_socks5(c, c->output, c->input);
1604 		break;
1605 	default:
1606 		ret = -1;
1607 		break;
1608 	}
1609 	if (ret < 0) {
1610 		rdynamic_close(ssh, c);
1611 	} else if (ret == 0) {
1612 		debug2("channel %d: pre_rdynamic: need more", c->self);
1613 		/* send socks request to peer */
1614 		len = sshbuf_len(c->input);
1615 		if (len > 0 && len < c->remote_window) {
1616 			if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
1617 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1618 			    (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
1619 			    (r = sshpkt_send(ssh)) != 0) {
1620 				fatal_fr(r, "channel %i: rdynamic", c->self);
1621 			}
1622 			if ((r = sshbuf_consume(c->input, len)) != 0)
1623 				fatal_fr(r, "channel %d: consume", c->self);
1624 			c->remote_window -= len;
1625 		}
1626 	} else if (rdynamic_connect_finish(ssh, c) < 0) {
1627 		/* the connect failed */
1628 		rdynamic_close(ssh, c);
1629 	}
1630 }
1631 
1632 /* This is our fake X11 server socket. */
1633 static void
channel_post_x11_listener(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1634 channel_post_x11_listener(struct ssh *ssh, Channel *c,
1635     fd_set *readset, fd_set *writeset)
1636 {
1637 	Channel *nc;
1638 	struct sockaddr_storage addr;
1639 	int r, newsock, oerrno, remote_port;
1640 	socklen_t addrlen;
1641 	char buf[16384], *remote_ipaddr;
1642 
1643 	if (!FD_ISSET(c->sock, readset))
1644 		return;
1645 
1646 	debug("X11 connection requested.");
1647 	addrlen = sizeof(addr);
1648 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1649 	if (c->single_connection) {
1650 		oerrno = errno;
1651 		debug2("single_connection: closing X11 listener.");
1652 		channel_close_fd(ssh, &c->sock);
1653 		chan_mark_dead(ssh, c);
1654 		errno = oerrno;
1655 	}
1656 	if (newsock == -1) {
1657 		if (errno != EINTR && errno != EWOULDBLOCK &&
1658 		    errno != ECONNABORTED)
1659 			error("accept: %.100s", strerror(errno));
1660 		if (errno == EMFILE || errno == ENFILE)
1661 			c->notbefore = monotime() + 1;
1662 		return;
1663 	}
1664 	set_nodelay(newsock);
1665 	remote_ipaddr = get_peer_ipaddr(newsock);
1666 	remote_port = get_peer_port(newsock);
1667 	snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1668 	    remote_ipaddr, remote_port);
1669 
1670 	nc = channel_new(ssh, "accepted x11 socket",
1671 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1672 	    c->local_window_max, c->local_maxpacket, 0, buf, 1);
1673 	open_preamble(ssh, __func__, nc, "x11");
1674 	if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1675 	    (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
1676 		fatal_fr(r, "channel %i: reply", c->self);
1677 	}
1678 	if ((r = sshpkt_send(ssh)) != 0)
1679 		fatal_fr(r, "channel %i: send", c->self);
1680 	free(remote_ipaddr);
1681 }
1682 
1683 static void
port_open_helper(struct ssh * ssh,Channel * c,char * rtype)1684 port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
1685 {
1686 	char *local_ipaddr = get_local_ipaddr(c->sock);
1687 	int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
1688 	char *remote_ipaddr = get_peer_ipaddr(c->sock);
1689 	int remote_port = get_peer_port(c->sock);
1690 	int r;
1691 
1692 	if (remote_port == -1) {
1693 		/* Fake addr/port to appease peers that validate it (Tectia) */
1694 		free(remote_ipaddr);
1695 		remote_ipaddr = xstrdup("127.0.0.1");
1696 		remote_port = 65535;
1697 	}
1698 
1699 	free(c->remote_name);
1700 	xasprintf(&c->remote_name,
1701 	    "%s: listening port %d for %.100s port %d, "
1702 	    "connect from %.200s port %d to %.100s port %d",
1703 	    rtype, c->listening_port, c->path, c->host_port,
1704 	    remote_ipaddr, remote_port, local_ipaddr, local_port);
1705 
1706 	open_preamble(ssh, __func__, c, rtype);
1707 	if (strcmp(rtype, "direct-tcpip") == 0) {
1708 		/* target host, port */
1709 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1710 		    (r = sshpkt_put_u32(ssh, c->host_port)) != 0)
1711 			fatal_fr(r, "channel %i: reply", c->self);
1712 	} else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
1713 		/* target path */
1714 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1715 			fatal_fr(r, "channel %i: reply", c->self);
1716 	} else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1717 		/* listen path */
1718 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0)
1719 			fatal_fr(r, "channel %i: reply", c->self);
1720 	} else {
1721 		/* listen address, port */
1722 		if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
1723 		    (r = sshpkt_put_u32(ssh, local_port)) != 0)
1724 			fatal_fr(r, "channel %i: reply", c->self);
1725 	}
1726 	if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
1727 		/* reserved for future owner/mode info */
1728 		if ((r = sshpkt_put_cstring(ssh, "")) != 0)
1729 			fatal_fr(r, "channel %i: reply", c->self);
1730 	} else {
1731 		/* originator host and port */
1732 		if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
1733 		    (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0)
1734 			fatal_fr(r, "channel %i: reply", c->self);
1735 	}
1736 	if ((r = sshpkt_send(ssh)) != 0)
1737 		fatal_fr(r, "channel %i: send", c->self);
1738 	free(remote_ipaddr);
1739 	free(local_ipaddr);
1740 }
1741 
1742 void
channel_set_x11_refuse_time(struct ssh * ssh,u_int refuse_time)1743 channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
1744 {
1745 	ssh->chanctxt->x11_refuse_time = refuse_time;
1746 }
1747 
1748 /*
1749  * This socket is listening for connections to a forwarded TCP/IP port.
1750  */
1751 static void
channel_post_port_listener(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1752 channel_post_port_listener(struct ssh *ssh, Channel *c,
1753     fd_set *readset, fd_set *writeset)
1754 {
1755 	Channel *nc;
1756 	struct sockaddr_storage addr;
1757 	int newsock, nextstate;
1758 	socklen_t addrlen;
1759 	char *rtype;
1760 
1761 	if (!FD_ISSET(c->sock, readset))
1762 		return;
1763 
1764 	debug("Connection to port %d forwarding to %.100s port %d requested.",
1765 	    c->listening_port, c->path, c->host_port);
1766 
1767 	if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1768 		nextstate = SSH_CHANNEL_OPENING;
1769 		rtype = "forwarded-tcpip";
1770 	} else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
1771 		nextstate = SSH_CHANNEL_OPENING;
1772 		rtype = "forwarded-streamlocal@openssh.com";
1773 	} else if (c->host_port == PORT_STREAMLOCAL) {
1774 		nextstate = SSH_CHANNEL_OPENING;
1775 		rtype = "direct-streamlocal@openssh.com";
1776 	} else if (c->host_port == 0) {
1777 		nextstate = SSH_CHANNEL_DYNAMIC;
1778 		rtype = "dynamic-tcpip";
1779 	} else {
1780 		nextstate = SSH_CHANNEL_OPENING;
1781 		rtype = "direct-tcpip";
1782 	}
1783 
1784 	addrlen = sizeof(addr);
1785 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1786 	if (newsock == -1) {
1787 		if (errno != EINTR && errno != EWOULDBLOCK &&
1788 		    errno != ECONNABORTED)
1789 			error("accept: %.100s", strerror(errno));
1790 		if (errno == EMFILE || errno == ENFILE)
1791 			c->notbefore = monotime() + 1;
1792 		return;
1793 	}
1794 	if (c->host_port != PORT_STREAMLOCAL)
1795 		set_nodelay(newsock);
1796 	nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
1797 	    c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1798 	nc->listening_port = c->listening_port;
1799 	nc->host_port = c->host_port;
1800 	if (c->path != NULL)
1801 		nc->path = xstrdup(c->path);
1802 
1803 	if (nextstate != SSH_CHANNEL_DYNAMIC)
1804 		port_open_helper(ssh, nc, rtype);
1805 }
1806 
1807 /*
1808  * This is the authentication agent socket listening for connections from
1809  * clients.
1810  */
1811 static void
channel_post_auth_listener(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1812 channel_post_auth_listener(struct ssh *ssh, Channel *c,
1813     fd_set *readset, fd_set *writeset)
1814 {
1815 	Channel *nc;
1816 	int r, newsock;
1817 	struct sockaddr_storage addr;
1818 	socklen_t addrlen;
1819 
1820 	if (!FD_ISSET(c->sock, readset))
1821 		return;
1822 
1823 	addrlen = sizeof(addr);
1824 	newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1825 	if (newsock == -1) {
1826 		error("accept from auth socket: %.100s", strerror(errno));
1827 		if (errno == EMFILE || errno == ENFILE)
1828 			c->notbefore = monotime() + 1;
1829 		return;
1830 	}
1831 	nc = channel_new(ssh, "accepted auth socket",
1832 	    SSH_CHANNEL_OPENING, newsock, newsock, -1,
1833 	    c->local_window_max, c->local_maxpacket,
1834 	    0, "accepted auth socket", 1);
1835 	open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
1836 	if ((r = sshpkt_send(ssh)) != 0)
1837 		fatal_fr(r, "channel %i", c->self);
1838 }
1839 
1840 static void
channel_post_connecting(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1841 channel_post_connecting(struct ssh *ssh, Channel *c,
1842     fd_set *readset, fd_set *writeset)
1843 {
1844 	int err = 0, sock, isopen, r;
1845 	socklen_t sz = sizeof(err);
1846 
1847 	if (!FD_ISSET(c->sock, writeset))
1848 		return;
1849 	if (!c->have_remote_id)
1850 		fatal_f("channel %d: no remote id", c->self);
1851 	/* for rdynamic the OPEN_CONFIRMATION has been sent already */
1852 	isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
1853 	if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
1854 		err = errno;
1855 		error("getsockopt SO_ERROR failed");
1856 	}
1857 	if (err == 0) {
1858 		debug("channel %d: connected to %s port %d",
1859 		    c->self, c->connect_ctx.host, c->connect_ctx.port);
1860 		channel_connect_ctx_free(&c->connect_ctx);
1861 		c->type = SSH_CHANNEL_OPEN;
1862 		if (isopen) {
1863 			/* no message necessary */
1864 		} else {
1865 			if ((r = sshpkt_start(ssh,
1866 			    SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
1867 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1868 			    (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
1869 			    (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
1870 			    (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0 ||
1871 			    (r = sshpkt_send(ssh)) != 0)
1872 				fatal_fr(r, "channel %i open confirm", c->self);
1873 		}
1874 	} else {
1875 		debug("channel %d: connection failed: %s",
1876 		    c->self, strerror(err));
1877 		/* Try next address, if any */
1878 		if ((sock = connect_next(&c->connect_ctx)) > 0) {
1879 			close(c->sock);
1880 			c->sock = c->rfd = c->wfd = sock;
1881 			channel_find_maxfd(ssh->chanctxt);
1882 			return;
1883 		}
1884 		/* Exhausted all addresses */
1885 		error("connect_to %.100s port %d: failed.",
1886 		    c->connect_ctx.host, c->connect_ctx.port);
1887 		channel_connect_ctx_free(&c->connect_ctx);
1888 		if (isopen) {
1889 			rdynamic_close(ssh, c);
1890 		} else {
1891 			if ((r = sshpkt_start(ssh,
1892 			    SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
1893 			    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
1894 			    (r = sshpkt_put_u32(ssh,
1895 			    SSH2_OPEN_CONNECT_FAILED)) != 0 ||
1896 			    (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
1897 			    (r = sshpkt_put_cstring(ssh, "")) != 0 ||
1898 			    (r = sshpkt_send(ssh)) != 0)
1899 				fatal_fr(r, "channel %i: failure", c->self);
1900 			chan_mark_dead(ssh, c);
1901 		}
1902 	}
1903 }
1904 
1905 static int
channel_handle_rfd(struct ssh * ssh,Channel * c,fd_set * readset,fd_set * writeset)1906 channel_handle_rfd(struct ssh *ssh, Channel *c,
1907     fd_set *readset, fd_set *writeset)
1908 {
1909 	char buf[CHAN_RBUF];
1910 	ssize_t len;
1911 	int r, force;
1912 
1913 	force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1914 
1915 	if (c->rfd == -1 || (!force && !FD_ISSET(c->rfd, readset)))
1916 		return 1;
1917 
1918 	errno = 0;
1919 	len = read(c->rfd, buf, sizeof(buf));
1920 	if (len == -1 && (errno == EINTR ||
1921 	    ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1922 		return 1;
1923 #ifndef PTY_ZEROREAD
1924  	if (len <= 0) {
1925 #else
1926 	if ((!c->isatty && len <= 0) ||
1927 	    (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1928 #endif
1929 		debug2("channel %d: read<=0 rfd %d len %zd",
1930 		    c->self, c->rfd, len);
1931 		if (c->type != SSH_CHANNEL_OPEN) {
1932 			debug2("channel %d: not open", c->self);
1933 			chan_mark_dead(ssh, c);
1934 			return -1;
1935 		} else {
1936 			chan_read_failed(ssh, c);
1937 		}
1938 		return -1;
1939 	}
1940 	if (c->input_filter != NULL) {
1941 		if (c->input_filter(ssh, c, buf, len) == -1) {
1942 			debug2("channel %d: filter stops", c->self);
1943 			chan_read_failed(ssh, c);
1944 		}
1945 	} else if (c->datagram) {
1946 		if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
1947 			fatal_fr(r, "channel %i: put datagram", c->self);
1948 	} else if ((r = sshbuf_put(c->input, buf, len)) != 0)
1949 		fatal_fr(r, "channel %i: put data", c->self);
1950 	return 1;
1951 }
1952 
1953 static int
1954 channel_handle_wfd(struct ssh *ssh, Channel *c,
1955    fd_set *readset, fd_set *writeset)
1956 {
1957 	struct termios tio;
1958 	u_char *data = NULL, *buf; /* XXX const; need filter API change */
1959 	size_t dlen, olen = 0;
1960 	int r, len;
1961 
1962 	if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
1963 	    sshbuf_len(c->output) == 0)
1964 		return 1;
1965 
1966 	/* Send buffered output data to the socket. */
1967 	olen = sshbuf_len(c->output);
1968 	if (c->output_filter != NULL) {
1969 		if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
1970 			debug2("channel %d: filter stops", c->self);
1971 			if (c->type != SSH_CHANNEL_OPEN)
1972 				chan_mark_dead(ssh, c);
1973 			else
1974 				chan_write_failed(ssh, c);
1975 			return -1;
1976 		}
1977 	} else if (c->datagram) {
1978 		if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
1979 			fatal_fr(r, "channel %i: get datagram", c->self);
1980 		buf = data;
1981 	} else {
1982 		buf = data = sshbuf_mutable_ptr(c->output);
1983 		dlen = sshbuf_len(c->output);
1984 	}
1985 
1986 	if (c->datagram) {
1987 		/* ignore truncated writes, datagrams might get lost */
1988 		len = write(c->wfd, buf, dlen);
1989 		free(data);
1990 		if (len == -1 && (errno == EINTR || errno == EAGAIN ||
1991 		    errno == EWOULDBLOCK))
1992 			return 1;
1993 		if (len <= 0)
1994 			goto write_fail;
1995 		goto out;
1996 	}
1997 
1998 #ifdef _AIX
1999 	/* XXX: Later AIX versions can't push as much data to tty */
2000 	if (c->wfd_isatty)
2001 		dlen = MIN(dlen, 8*1024);
2002 #endif
2003 
2004 	len = write(c->wfd, buf, dlen);
2005 	if (len == -1 &&
2006 	    (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
2007 		return 1;
2008 	if (len <= 0) {
2009  write_fail:
2010 		if (c->type != SSH_CHANNEL_OPEN) {
2011 			debug2("channel %d: not open", c->self);
2012 			chan_mark_dead(ssh, c);
2013 			return -1;
2014 		} else {
2015 			chan_write_failed(ssh, c);
2016 		}
2017 		return -1;
2018 	}
2019 #ifndef BROKEN_TCGETATTR_ICANON
2020 	if (c->isatty && dlen >= 1 && buf[0] != '\r') {
2021 		if (tcgetattr(c->wfd, &tio) == 0 &&
2022 		    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
2023 			/*
2024 			 * Simulate echo to reduce the impact of
2025 			 * traffic analysis. We need to match the
2026 			 * size of a SSH2_MSG_CHANNEL_DATA message
2027 			 * (4 byte channel id + buf)
2028 			 */
2029 			if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
2030 			    (r = sshpkt_send(ssh)) != 0)
2031 				fatal_fr(r, "channel %i: ignore", c->self);
2032 		}
2033 	}
2034 #endif /* BROKEN_TCGETATTR_ICANON */
2035 	if ((r = sshbuf_consume(c->output, len)) != 0)
2036 		fatal_fr(r, "channel %i: consume", c->self);
2037  out:
2038 	c->local_consumed += olen - sshbuf_len(c->output);
2039 
2040 	return 1;
2041 }
2042 
2043 static int
2044 channel_handle_efd_write(struct ssh *ssh, Channel *c,
2045     fd_set *readset, fd_set *writeset)
2046 {
2047 	int r;
2048 	ssize_t len;
2049 
2050 	if (!FD_ISSET(c->efd, writeset) || sshbuf_len(c->extended) == 0)
2051 		return 1;
2052 
2053 	len = write(c->efd, sshbuf_ptr(c->extended),
2054 	    sshbuf_len(c->extended));
2055 	debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
2056 	if (len == -1 && (errno == EINTR || errno == EAGAIN ||
2057 	    errno == EWOULDBLOCK))
2058 		return 1;
2059 	if (len <= 0) {
2060 		debug2("channel %d: closing write-efd %d", c->self, c->efd);
2061 		channel_close_fd(ssh, &c->efd);
2062 	} else {
2063 		if ((r = sshbuf_consume(c->extended, len)) != 0)
2064 			fatal_fr(r, "channel %i: consume", c->self);
2065 		c->local_consumed += len;
2066 	}
2067 	return 1;
2068 }
2069 
2070 static int
2071 channel_handle_efd_read(struct ssh *ssh, Channel *c,
2072     fd_set *readset, fd_set *writeset)
2073 {
2074 	char buf[CHAN_RBUF];
2075 	ssize_t len;
2076 	int r, force;
2077 
2078 	force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
2079 
2080 	if (c->efd == -1 || (!force && !FD_ISSET(c->efd, readset)))
2081 		return 1;
2082 
2083 	len = read(c->efd, buf, sizeof(buf));
2084 	debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
2085 	if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
2086 	    errno == EWOULDBLOCK) && !force)))
2087 		return 1;
2088 	if (len <= 0) {
2089 		debug2("channel %d: closing read-efd %d", c->self, c->efd);
2090 		channel_close_fd(ssh, &c->efd);
2091 	} else if (c->extended_usage == CHAN_EXTENDED_IGNORE)
2092 		debug3("channel %d: discard efd", c->self);
2093 	else if ((r = sshbuf_put(c->extended, buf, len)) != 0)
2094 		fatal_fr(r, "channel %i: append", c->self);
2095 	return 1;
2096 }
2097 
2098 static int
2099 channel_handle_efd(struct ssh *ssh, Channel *c,
2100     fd_set *readset, fd_set *writeset)
2101 {
2102 	if (c->efd == -1)
2103 		return 1;
2104 
2105 	/** XXX handle drain efd, too */
2106 
2107 	if (c->extended_usage == CHAN_EXTENDED_WRITE)
2108 		return channel_handle_efd_write(ssh, c, readset, writeset);
2109 	else if (c->extended_usage == CHAN_EXTENDED_READ ||
2110 	    c->extended_usage == CHAN_EXTENDED_IGNORE)
2111 		return channel_handle_efd_read(ssh, c, readset, writeset);
2112 
2113 	return 1;
2114 }
2115 
2116 static int
2117 channel_check_window(struct ssh *ssh, Channel *c)
2118 {
2119 	int r;
2120 
2121 	if (c->type == SSH_CHANNEL_OPEN &&
2122 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
2123 	    ((c->local_window_max - c->local_window >
2124 	    c->local_maxpacket*3) ||
2125 	    c->local_window < c->local_window_max/2) &&
2126 	    c->local_consumed > 0) {
2127 		if (!c->have_remote_id)
2128 			fatal_f("channel %d: no remote id", c->self);
2129 		if ((r = sshpkt_start(ssh,
2130 		    SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
2131 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2132 		    (r = sshpkt_put_u32(ssh, c->local_consumed)) != 0 ||
2133 		    (r = sshpkt_send(ssh)) != 0) {
2134 			fatal_fr(r, "channel %i", c->self);
2135 		}
2136 		debug2("channel %d: window %d sent adjust %d", c->self,
2137 		    c->local_window, c->local_consumed);
2138 		c->local_window += c->local_consumed;
2139 		c->local_consumed = 0;
2140 	}
2141 	return 1;
2142 }
2143 
2144 static void
2145 channel_post_open(struct ssh *ssh, Channel *c,
2146     fd_set *readset, fd_set *writeset)
2147 {
2148 	channel_handle_rfd(ssh, c, readset, writeset);
2149 	channel_handle_wfd(ssh, c, readset, writeset);
2150 	channel_handle_efd(ssh, c, readset, writeset);
2151 	channel_check_window(ssh, c);
2152 }
2153 
2154 static u_int
2155 read_mux(struct ssh *ssh, Channel *c, u_int need)
2156 {
2157 	char buf[CHAN_RBUF];
2158 	ssize_t len;
2159 	u_int rlen;
2160 	int r;
2161 
2162 	if (sshbuf_len(c->input) < need) {
2163 		rlen = need - sshbuf_len(c->input);
2164 		len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
2165 		if (len == -1 && (errno == EINTR || errno == EAGAIN))
2166 			return sshbuf_len(c->input);
2167 		if (len <= 0) {
2168 			debug2("channel %d: ctl read<=0 rfd %d len %zd",
2169 			    c->self, c->rfd, len);
2170 			chan_read_failed(ssh, c);
2171 			return 0;
2172 		} else if ((r = sshbuf_put(c->input, buf, len)) != 0)
2173 			fatal_fr(r, "channel %i: append", c->self);
2174 	}
2175 	return sshbuf_len(c->input);
2176 }
2177 
2178 static void
2179 channel_post_mux_client_read(struct ssh *ssh, Channel *c,
2180     fd_set *readset, fd_set *writeset)
2181 {
2182 	u_int need;
2183 
2184 	if (c->rfd == -1 || !FD_ISSET(c->rfd, readset))
2185 		return;
2186 	if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
2187 		return;
2188 	if (c->mux_pause)
2189 		return;
2190 
2191 	/*
2192 	 * Don't not read past the precise end of packets to
2193 	 * avoid disrupting fd passing.
2194 	 */
2195 	if (read_mux(ssh, c, 4) < 4) /* read header */
2196 		return;
2197 	/* XXX sshbuf_peek_u32 */
2198 	need = PEEK_U32(sshbuf_ptr(c->input));
2199 #define CHANNEL_MUX_MAX_PACKET	(256 * 1024)
2200 	if (need > CHANNEL_MUX_MAX_PACKET) {
2201 		debug2("channel %d: packet too big %u > %u",
2202 		    c->self, CHANNEL_MUX_MAX_PACKET, need);
2203 		chan_rcvd_oclose(ssh, c);
2204 		return;
2205 	}
2206 	if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
2207 		return;
2208 	if (c->mux_rcb(ssh, c) != 0) {
2209 		debug("channel %d: mux_rcb failed", c->self);
2210 		chan_mark_dead(ssh, c);
2211 		return;
2212 	}
2213 }
2214 
2215 static void
2216 channel_post_mux_client_write(struct ssh *ssh, Channel *c,
2217     fd_set *readset, fd_set *writeset)
2218 {
2219 	ssize_t len;
2220 	int r;
2221 
2222 	if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
2223 	    sshbuf_len(c->output) == 0)
2224 		return;
2225 
2226 	len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
2227 	if (len == -1 && (errno == EINTR || errno == EAGAIN))
2228 		return;
2229 	if (len <= 0) {
2230 		chan_mark_dead(ssh, c);
2231 		return;
2232 	}
2233 	if ((r = sshbuf_consume(c->output, len)) != 0)
2234 		fatal_fr(r, "channel %i: consume", c->self);
2235 }
2236 
2237 static void
2238 channel_post_mux_client(struct ssh *ssh, Channel *c,
2239     fd_set *readset, fd_set *writeset)
2240 {
2241 	channel_post_mux_client_read(ssh, c, readset, writeset);
2242 	channel_post_mux_client_write(ssh, c, readset, writeset);
2243 }
2244 
2245 static void
2246 channel_post_mux_listener(struct ssh *ssh, Channel *c,
2247     fd_set *readset, fd_set *writeset)
2248 {
2249 	Channel *nc;
2250 	struct sockaddr_storage addr;
2251 	socklen_t addrlen;
2252 	int newsock;
2253 	uid_t euid;
2254 	gid_t egid;
2255 
2256 	if (!FD_ISSET(c->sock, readset))
2257 		return;
2258 
2259 	debug("multiplexing control connection");
2260 
2261 	/*
2262 	 * Accept connection on control socket
2263 	 */
2264 	memset(&addr, 0, sizeof(addr));
2265 	addrlen = sizeof(addr);
2266 	if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
2267 	    &addrlen)) == -1) {
2268 		error_f("accept: %s", strerror(errno));
2269 		if (errno == EMFILE || errno == ENFILE)
2270 			c->notbefore = monotime() + 1;
2271 		return;
2272 	}
2273 
2274 	if (getpeereid(newsock, &euid, &egid) == -1) {
2275 		error_f("getpeereid failed: %s", strerror(errno));
2276 		close(newsock);
2277 		return;
2278 	}
2279 	if ((euid != 0) && (getuid() != euid)) {
2280 		error("multiplex uid mismatch: peer euid %u != uid %u",
2281 		    (u_int)euid, (u_int)getuid());
2282 		close(newsock);
2283 		return;
2284 	}
2285 	nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
2286 	    newsock, newsock, -1, c->local_window_max,
2287 	    c->local_maxpacket, 0, "mux-control", 1);
2288 	nc->mux_rcb = c->mux_rcb;
2289 	debug3_f("new mux channel %d fd %d", nc->self, nc->sock);
2290 	/* establish state */
2291 	nc->mux_rcb(ssh, nc);
2292 	/* mux state transitions must not elicit protocol messages */
2293 	nc->flags |= CHAN_LOCAL;
2294 }
2295 
2296 static void
2297 channel_handler_init(struct ssh_channels *sc)
2298 {
2299 	chan_fn **pre, **post;
2300 
2301 	if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
2302 	   (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
2303 		fatal_f("allocation failed");
2304 
2305 	pre[SSH_CHANNEL_OPEN] =			&channel_pre_open;
2306 	pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
2307 	pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
2308 	pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
2309 	pre[SSH_CHANNEL_UNIX_LISTENER] =	&channel_pre_listener;
2310 	pre[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_pre_listener;
2311 	pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
2312 	pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
2313 	pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
2314 	pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
2315 	pre[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_pre_connecting;
2316 	pre[SSH_CHANNEL_MUX_LISTENER] =		&channel_pre_listener;
2317 	pre[SSH_CHANNEL_MUX_CLIENT] =		&channel_pre_mux_client;
2318 
2319 	post[SSH_CHANNEL_OPEN] =		&channel_post_open;
2320 	post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
2321 	post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
2322 	post[SSH_CHANNEL_UNIX_LISTENER] =	&channel_post_port_listener;
2323 	post[SSH_CHANNEL_RUNIX_LISTENER] =	&channel_post_port_listener;
2324 	post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
2325 	post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
2326 	post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
2327 	post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open;
2328 	post[SSH_CHANNEL_RDYNAMIC_FINISH] =	&channel_post_connecting;
2329 	post[SSH_CHANNEL_MUX_LISTENER] =	&channel_post_mux_listener;
2330 	post[SSH_CHANNEL_MUX_CLIENT] =		&channel_post_mux_client;
2331 
2332 	sc->channel_pre = pre;
2333 	sc->channel_post = post;
2334 }
2335 
2336 /* gc dead channels */
2337 static void
2338 channel_garbage_collect(struct ssh *ssh, Channel *c)
2339 {
2340 	if (c == NULL)
2341 		return;
2342 	if (c->detach_user != NULL) {
2343 		if (!chan_is_dead(ssh, c, c->detach_close))
2344 			return;
2345 
2346 		debug2("channel %d: gc: notify user", c->self);
2347 		c->detach_user(ssh, c->self, NULL);
2348 		/* if we still have a callback */
2349 		if (c->detach_user != NULL)
2350 			return;
2351 		debug2("channel %d: gc: user detached", c->self);
2352 	}
2353 	if (!chan_is_dead(ssh, c, 1))
2354 		return;
2355 	debug2("channel %d: garbage collecting", c->self);
2356 	channel_free(ssh, c);
2357 }
2358 
2359 enum channel_table { CHAN_PRE, CHAN_POST };
2360 
2361 static void
2362 channel_handler(struct ssh *ssh, int table,
2363     fd_set *readset, fd_set *writeset, time_t *unpause_secs)
2364 {
2365 	struct ssh_channels *sc = ssh->chanctxt;
2366 	chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
2367 	u_int i, oalloc;
2368 	Channel *c;
2369 	time_t now;
2370 
2371 	now = monotime();
2372 	if (unpause_secs != NULL)
2373 		*unpause_secs = 0;
2374 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2375 		c = sc->channels[i];
2376 		if (c == NULL)
2377 			continue;
2378 		if (c->delayed) {
2379 			if (table == CHAN_PRE)
2380 				c->delayed = 0;
2381 			else
2382 				continue;
2383 		}
2384 		if (ftab[c->type] != NULL) {
2385 			/*
2386 			 * Run handlers that are not paused.
2387 			 */
2388 			if (c->notbefore <= now)
2389 				(*ftab[c->type])(ssh, c, readset, writeset);
2390 			else if (unpause_secs != NULL) {
2391 				/*
2392 				 * Collect the time that the earliest
2393 				 * channel comes off pause.
2394 				 */
2395 				debug3_f("chan %d: skip for %d more "
2396 				    "seconds", c->self,
2397 				    (int)(c->notbefore - now));
2398 				if (*unpause_secs == 0 ||
2399 				    (c->notbefore - now) < *unpause_secs)
2400 					*unpause_secs = c->notbefore - now;
2401 			}
2402 		}
2403 		channel_garbage_collect(ssh, c);
2404 	}
2405 	if (unpause_secs != NULL && *unpause_secs != 0)
2406 		debug3_f("first channel unpauses in %d seconds",
2407 		    (int)*unpause_secs);
2408 }
2409 
2410 /*
2411  * Create sockets before allocating the select bitmasks.
2412  * This is necessary for things that need to happen after reading
2413  * the network-input but before channel_prepare_select().
2414  */
2415 static void
2416 channel_before_prepare_select(struct ssh *ssh)
2417 {
2418 	struct ssh_channels *sc = ssh->chanctxt;
2419 	Channel *c;
2420 	u_int i, oalloc;
2421 
2422 	for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
2423 		c = sc->channels[i];
2424 		if (c == NULL)
2425 			continue;
2426 		if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
2427 			channel_before_prepare_select_rdynamic(ssh, c);
2428 	}
2429 }
2430 
2431 /*
2432  * Allocate/update select bitmasks and add any bits relevant to channels in
2433  * select bitmasks.
2434  */
2435 void
2436 channel_prepare_select(struct ssh *ssh, fd_set **readsetp, fd_set **writesetp,
2437     int *maxfdp, u_int *nallocp, time_t *minwait_secs)
2438 {
2439 	u_int n, sz, nfdset;
2440 
2441 	channel_before_prepare_select(ssh); /* might update channel_max_fd */
2442 
2443 	n = MAXIMUM(*maxfdp, ssh->chanctxt->channel_max_fd);
2444 
2445 	nfdset = howmany(n+1, NFDBITS);
2446 	/* Explicitly test here, because xrealloc isn't always called */
2447 	if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
2448 		fatal("channel_prepare_select: max_fd (%d) is too large", n);
2449 	sz = nfdset * sizeof(fd_mask);
2450 
2451 	/* perhaps check sz < nalloc/2 and shrink? */
2452 	if (*readsetp == NULL || sz > *nallocp) {
2453 		*readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
2454 		*writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
2455 		*nallocp = sz;
2456 	}
2457 	*maxfdp = n;
2458 	memset(*readsetp, 0, sz);
2459 	memset(*writesetp, 0, sz);
2460 
2461 	if (!ssh_packet_is_rekeying(ssh))
2462 		channel_handler(ssh, CHAN_PRE, *readsetp, *writesetp,
2463 		    minwait_secs);
2464 }
2465 
2466 /*
2467  * After select, perform any appropriate operations for channels which have
2468  * events pending.
2469  */
2470 void
2471 channel_after_select(struct ssh *ssh, fd_set *readset, fd_set *writeset)
2472 {
2473 	channel_handler(ssh, CHAN_POST, readset, writeset, NULL);
2474 }
2475 
2476 /*
2477  * Enqueue data for channels with open or draining c->input.
2478  */
2479 static void
2480 channel_output_poll_input_open(struct ssh *ssh, Channel *c)
2481 {
2482 	size_t len, plen;
2483 	const u_char *pkt;
2484 	int r;
2485 
2486 	if ((len = sshbuf_len(c->input)) == 0) {
2487 		if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2488 			/*
2489 			 * input-buffer is empty and read-socket shutdown:
2490 			 * tell peer, that we will not send more data:
2491 			 * send IEOF.
2492 			 * hack for extended data: delay EOF if EFD still
2493 			 * in use.
2494 			 */
2495 			if (CHANNEL_EFD_INPUT_ACTIVE(c))
2496 				debug2("channel %d: "
2497 				    "ibuf_empty delayed efd %d/(%zu)",
2498 				    c->self, c->efd, sshbuf_len(c->extended));
2499 			else
2500 				chan_ibuf_empty(ssh, c);
2501 		}
2502 		return;
2503 	}
2504 
2505 	if (!c->have_remote_id)
2506 		fatal_f("channel %d: no remote id", c->self);
2507 
2508 	if (c->datagram) {
2509 		/* Check datagram will fit; drop if not */
2510 		if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
2511 			fatal_fr(r, "channel %i: get datagram", c->self);
2512 		/*
2513 		 * XXX this does tail-drop on the datagram queue which is
2514 		 * usually suboptimal compared to head-drop. Better to have
2515 		 * backpressure at read time? (i.e. read + discard)
2516 		 */
2517 		if (plen > c->remote_window || plen > c->remote_maxpacket) {
2518 			debug("channel %d: datagram too big", c->self);
2519 			return;
2520 		}
2521 		/* Enqueue it */
2522 		if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2523 		    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2524 		    (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
2525 		    (r = sshpkt_send(ssh)) != 0)
2526 			fatal_fr(r, "channel %i: send datagram", c->self);
2527 		c->remote_window -= plen;
2528 		return;
2529 	}
2530 
2531 	/* Enqueue packet for buffered data. */
2532 	if (len > c->remote_window)
2533 		len = c->remote_window;
2534 	if (len > c->remote_maxpacket)
2535 		len = c->remote_maxpacket;
2536 	if (len == 0)
2537 		return;
2538 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
2539 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2540 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
2541 	    (r = sshpkt_send(ssh)) != 0)
2542 		fatal_fr(r, "channel %i: send data", c->self);
2543 	if ((r = sshbuf_consume(c->input, len)) != 0)
2544 		fatal_fr(r, "channel %i: consume", c->self);
2545 	c->remote_window -= len;
2546 }
2547 
2548 /*
2549  * Enqueue data for channels with open c->extended in read mode.
2550  */
2551 static void
2552 channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
2553 {
2554 	size_t len;
2555 	int r;
2556 
2557 	if ((len = sshbuf_len(c->extended)) == 0)
2558 		return;
2559 
2560 	debug2("channel %d: rwin %u elen %zu euse %d", c->self,
2561 	    c->remote_window, sshbuf_len(c->extended), c->extended_usage);
2562 	if (len > c->remote_window)
2563 		len = c->remote_window;
2564 	if (len > c->remote_maxpacket)
2565 		len = c->remote_maxpacket;
2566 	if (len == 0)
2567 		return;
2568 	if (!c->have_remote_id)
2569 		fatal_f("channel %d: no remote id", c->self);
2570 	if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
2571 	    (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
2572 	    (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
2573 	    (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
2574 	    (r = sshpkt_send(ssh)) != 0)
2575 		fatal_fr(r, "channel %i: data", c->self);
2576 	if ((r = sshbuf_consume(c->extended, len)) != 0)
2577 		fatal_fr(r, "channel %i: consume", c->self);
2578 	c->remote_window -= len;
2579 	debug2("channel %d: sent ext data %zu", c->self, len);
2580 }
2581 
2582 /* If there is data to send to the connection, enqueue some of it now. */
2583 void
2584 channel_output_poll(struct ssh *ssh)
2585 {
2586 	struct ssh_channels *sc = ssh->chanctxt;
2587 	Channel *c;
2588 	u_int i;
2589 
2590 	for (i = 0; i < sc->channels_alloc; i++) {
2591 		c = sc->channels[i];
2592 		if (c == NULL)
2593 			continue;
2594 
2595 		/*
2596 		 * We are only interested in channels that can have buffered
2597 		 * incoming data.
2598 		 */
2599 		if (c->type != SSH_CHANNEL_OPEN)
2600 			continue;
2601 		if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2602 			/* XXX is this true? */
2603 			debug3("channel %d: will not send data after close",
2604 			    c->self);
2605 			continue;
2606 		}
2607 
2608 		/* Get the amount of buffered data for this channel. */
2609 		if (c->istate == CHAN_INPUT_OPEN ||
2610 		    c->istate == CHAN_INPUT_WAIT_DRAIN)
2611 			channel_output_poll_input_open(ssh, c);
2612 		/* Send extended data, i.e. stderr */
2613 		if (!(c->flags & CHAN_EOF_SENT) &&
2614 		    c->extended_usage == CHAN_EXTENDED_READ)
2615 			channel_output_poll_extended_read(ssh, c);
2616 	}
2617 }
2618 
2619 /* -- mux proxy support  */
2620 
2621 /*
2622  * When multiplexing channel messages for mux clients we have to deal
2623  * with downstream messages from the mux client and upstream messages
2624  * from the ssh server:
2625  * 1) Handling downstream messages is straightforward and happens
2626  *    in channel_proxy_downstream():
2627  *    - We forward all messages (mostly) unmodified to the server.
2628  *    - However, in order to route messages from upstream to the correct
2629  *      downstream client, we have to replace the channel IDs used by the
2630  *      mux clients with a unique channel ID because the mux clients might
2631  *      use conflicting channel IDs.
2632  *    - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
2633  *      SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
2634  *      SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
2635  *      with the newly allocated channel ID.
2636  * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
2637  *    channels and processed by channel_proxy_upstream(). The local channel ID
2638  *    is then translated back to the original mux client ID.
2639  * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
2640  *    messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
2641  * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
2642  *    downstream mux client are removed.
2643  * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
2644  *    requires more work, because they are not addressed to a specific
2645  *    channel. E.g. client_request_forwarded_tcpip() needs to figure
2646  *    out whether the request is addressed to the local client or a
2647  *    specific downstream client based on the listen-address/port.
2648  * 6) Agent and X11-Forwarding have a similar problem and are currently
2649  *    not supported as the matching session/channel cannot be identified
2650  *    easily.
2651  */
2652 
2653 /*
2654  * receive packets from downstream mux clients:
2655  * channel callback fired on read from mux client, creates
2656  * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
2657  * on channel creation.
2658  */
2659 int
2660 channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
2661 {
2662 	Channel *c = NULL;
2663 	struct sshbuf *original = NULL, *modified = NULL;
2664 	const u_char *cp;
2665 	char *ctype = NULL, *listen_host = NULL;
2666 	u_char type;
2667 	size_t have;
2668 	int ret = -1, r;
2669 	u_int id, remote_id, listen_port;
2670 
2671 	/* sshbuf_dump(downstream->input, stderr); */
2672 	if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
2673 	    != 0) {
2674 		error_fr(r, "parse");
2675 		return -1;
2676 	}
2677 	if (have < 2) {
2678 		error_f("short message");
2679 		return -1;
2680 	}
2681 	type = cp[1];
2682 	/* skip padlen + type */
2683 	cp += 2;
2684 	have -= 2;
2685 	if (ssh_packet_log_type(type))
2686 		debug3_f("channel %u: down->up: type %u",
2687 		    downstream->self, type);
2688 
2689 	switch (type) {
2690 	case SSH2_MSG_CHANNEL_OPEN:
2691 		if ((original = sshbuf_from(cp, have)) == NULL ||
2692 		    (modified = sshbuf_new()) == NULL) {
2693 			error_f("alloc");
2694 			goto out;
2695 		}
2696 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
2697 		    (r = sshbuf_get_u32(original, &id)) != 0) {
2698 			error_fr(r, "parse");
2699 			goto out;
2700 		}
2701 		c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2702 		   -1, -1, -1, 0, 0, 0, ctype, 1);
2703 		c->mux_ctx = downstream;	/* point to mux client */
2704 		c->mux_downstream_id = id;	/* original downstream id */
2705 		if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
2706 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2707 		    (r = sshbuf_putb(modified, original)) != 0) {
2708 			error_fr(r, "compose");
2709 			channel_free(ssh, c);
2710 			goto out;
2711 		}
2712 		break;
2713 	case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
2714 		/*
2715 		 * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
2716 		 * need to parse 'remote_id' instead of 'ctype'.
2717 		 */
2718 		if ((original = sshbuf_from(cp, have)) == NULL ||
2719 		    (modified = sshbuf_new()) == NULL) {
2720 			error_f("alloc");
2721 			goto out;
2722 		}
2723 		if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
2724 		    (r = sshbuf_get_u32(original, &id)) != 0) {
2725 			error_fr(r, "parse");
2726 			goto out;
2727 		}
2728 		c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
2729 		   -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
2730 		c->mux_ctx = downstream;	/* point to mux client */
2731 		c->mux_downstream_id = id;
2732 		c->remote_id = remote_id;
2733 		c->have_remote_id = 1;
2734 		if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
2735 		    (r = sshbuf_put_u32(modified, c->self)) != 0 ||
2736 		    (r = sshbuf_putb(modified, original)) != 0) {
2737 			error_fr(r, "compose");
2738 			channel_free(ssh, c);
2739 			goto out;
2740 		}
2741 		break;
2742 	case SSH2_MSG_GLOBAL_REQUEST:
2743 		if ((original = sshbuf_from(cp, have)) == NULL) {
2744 			error_f("alloc");
2745 			goto out;
2746 		}
2747 		if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
2748 			error_fr(r, "parse");
2749 			goto out;
2750 		}
2751 		if (strcmp(ctype, "tcpip-forward") != 0) {
2752 			error_f("unsupported request %s", ctype);
2753 			goto out;
2754 		}
2755 		if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
2756 		    (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
2757 		    (r = sshbuf_get_u32(original, &listen_port)) != 0) {
2758 			error_fr(r, "parse");
2759 			goto out;
2760 		}
2761 		if (listen_port > 65535) {
2762 			error_f("tcpip-forward for %s: bad port %u",
2763 			    listen_host, listen_port);
2764 			goto out;
2765 		}
2766 		/* Record that connection to this host/port is permitted. */
2767 		permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
2768 		    listen_host, NULL, (int)listen_port, downstream);
2769 		listen_host = NULL;
2770 		break;
2771 	case SSH2_MSG_CHANNEL_CLOSE:
2772 		if (have < 4)
2773 			break;
2774 		remote_id = PEEK_U32(cp);
2775 		if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
2776 			if (c->flags & CHAN_CLOSE_RCVD)
2777 				channel_free(ssh, c);
2778 			else
2779 				c->flags |= CHAN_CLOSE_SENT;
2780 		}
2781 		break;
2782 	}
2783 	if (modified) {
2784 		if ((r = sshpkt_start(ssh, type)) != 0 ||
2785 		    (r = sshpkt_putb(ssh, modified)) != 0 ||
2786 		    (r = sshpkt_send(ssh)) != 0) {
2787 			error_fr(r, "send");
2788 			goto out;
2789 		}
2790 	} else {
2791 		if ((r = sshpkt_start(ssh, type)) != 0 ||
2792 		    (r = sshpkt_put(ssh, cp, have)) != 0 ||
2793 		    (r = sshpkt_send(ssh)) != 0) {
2794 			error_fr(r, "send");
2795 			goto out;
2796 		}
2797 	}
2798 	ret = 0;
2799  out:
2800 	free(ctype);
2801 	free(listen_host);
2802 	sshbuf_free(original);
2803 	sshbuf_free(modified);
2804 	return ret;
2805 }
2806 
2807 /*
2808  * receive packets from upstream server and de-multiplex packets
2809  * to correct downstream:
2810  * implemented as a helper for channel input handlers,
2811  * replaces local (proxy) channel ID with downstream channel ID.
2812  */
2813 int
2814 channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
2815 {
2816 	struct sshbuf *b = NULL;
2817 	Channel *downstream;
2818 	const u_char *cp = NULL;
2819 	size_t len;
2820 	int r;
2821 
2822 	/*
2823 	 * When receiving packets from the peer we need to check whether we
2824 	 * need to forward the packets to the mux client. In this case we
2825 	 * restore the original channel id and keep track of CLOSE messages,
2826 	 * so we can cleanup the channel.
2827 	 */
2828 	if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
2829 		return 0;
2830 	if ((downstream = c->mux_ctx) == NULL)
2831 		return 0;
2832