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