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