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