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