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