channels.c revision 74500
157429Smarkm/*
257429Smarkm * Author: Tatu Ylonen <ylo@cs.hut.fi>
357429Smarkm * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
457429Smarkm *                    All rights reserved
557429Smarkm * This file contains functions for generic socket connection forwarding.
657429Smarkm * There is also code for initiating connection forwarding for X11 connections,
757429Smarkm * arbitrary tcp/ip connections, and the authentication agent connection.
860573Skris *
965668Skris * As far as I am concerned, the code I have written for this software
1065668Skris * can be used freely for any purpose.  Any derived versions of this
1165668Skris * software must be clearly marked as such, and if the derived work is
1265668Skris * incompatible with the protocol description in the RFC file, it must be
1365668Skris * called by a name other than "ssh" or "Secure Shell".
1465668Skris *
1565668Skris *
1660573Skris * SSH2 support added by Markus Friedl.
1765668Skris * Copyright (c) 1999,2000 Markus Friedl.  All rights reserved.
1865668Skris * Copyright (c) 1999 Dug Song.  All rights reserved.
1965668Skris * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
2065668Skris *
2165668Skris * Redistribution and use in source and binary forms, with or without
2265668Skris * modification, are permitted provided that the following conditions
2365668Skris * are met:
2465668Skris * 1. Redistributions of source code must retain the above copyright
2565668Skris *    notice, this list of conditions and the following disclaimer.
2665668Skris * 2. Redistributions in binary form must reproduce the above copyright
2765668Skris *    notice, this list of conditions and the following disclaimer in the
2865668Skris *    documentation and/or other materials provided with the distribution.
2965668Skris *
3065668Skris * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
3165668Skris * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
3265668Skris * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
3365668Skris * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
3465668Skris * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
3565668Skris * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3665668Skris * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3765668Skris * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3865668Skris * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
3965668Skris * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4057429Smarkm */
4157429Smarkm
4257429Smarkm#include "includes.h"
4374500SgreenRCSID("$FreeBSD: head/crypto/openssh/channels.c 74500 2001-03-20 02:06:40Z green $");
4469587SgreenRCSID("$OpenBSD: channels.c,v 1.72 2000/10/27 07:48:22 markus Exp $");
4557429Smarkm
4657429Smarkm#include "ssh.h"
4757429Smarkm#include "packet.h"
4857429Smarkm#include "xmalloc.h"
4957429Smarkm#include "buffer.h"
5057429Smarkm#include "uidswap.h"
5157429Smarkm#include "readconf.h"
5257429Smarkm#include "servconf.h"
5357429Smarkm
5457429Smarkm#include "channels.h"
5557429Smarkm#include "nchan.h"
5657429Smarkm#include "compat.h"
5757429Smarkm
5860573Skris#include "ssh2.h"
5960573Skris
6065668Skris#include <openssl/rsa.h>
6165668Skris#include <openssl/dsa.h>
6265668Skris#include "key.h"
6365668Skris#include "authfd.h"
6465668Skris
6557429Smarkm/* Maximum number of fake X11 displays to try. */
6657429Smarkm#define MAX_DISPLAYS  1000
6757429Smarkm
6857429Smarkm/* Max len of agent socket */
6957429Smarkm#define MAX_SOCKET_NAME 100
7057429Smarkm
7157429Smarkm/*
7257429Smarkm * Pointer to an array containing all allocated channels.  The array is
7357429Smarkm * dynamically extended as needed.
7457429Smarkm */
7557429Smarkmstatic Channel *channels = NULL;
7657429Smarkm
7757429Smarkm/*
7857429Smarkm * Size of the channel array.  All slots of the array must always be
7957429Smarkm * initialized (at least the type field); unused slots are marked with type
8057429Smarkm * SSH_CHANNEL_FREE.
8157429Smarkm */
8257429Smarkmstatic int channels_alloc = 0;
8357429Smarkm
8457429Smarkm/*
8557429Smarkm * Maximum file descriptor value used in any of the channels.  This is
8657429Smarkm * updated in channel_allocate.
8757429Smarkm */
8857429Smarkmstatic int channel_max_fd_value = 0;
8957429Smarkm
9057429Smarkm/* Name and directory of socket for authentication agent forwarding. */
9157429Smarkmstatic char *channel_forwarded_auth_socket_name = NULL;
9257429Smarkmstatic char *channel_forwarded_auth_socket_dir = NULL;
9357429Smarkm
9457429Smarkm/* Saved X11 authentication protocol name. */
9557429Smarkmchar *x11_saved_proto = NULL;
9657429Smarkm
9757429Smarkm/* Saved X11 authentication data.  This is the real data. */
9857429Smarkmchar *x11_saved_data = NULL;
9957429Smarkmunsigned int x11_saved_data_len = 0;
10057429Smarkm
10157429Smarkm/*
10257429Smarkm * Fake X11 authentication data.  This is what the server will be sending us;
10357429Smarkm * we should replace any occurrences of this by the real data.
10457429Smarkm */
10557429Smarkmchar *x11_fake_data = NULL;
10657429Smarkmunsigned int x11_fake_data_len;
10757429Smarkm
10857429Smarkm/*
10957429Smarkm * Data structure for storing which hosts are permitted for forward requests.
11057429Smarkm * The local sides of any remote forwards are stored in this array to prevent
11157429Smarkm * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
11257429Smarkm * network (which might be behind a firewall).
11357429Smarkm */
11457429Smarkmtypedef struct {
11560573Skris	char *host_to_connect;		/* Connect to 'host'. */
11660573Skris	u_short port_to_connect;	/* Connect to 'port'. */
11760573Skris	u_short listen_port;		/* Remote side should listen port number. */
11857429Smarkm} ForwardPermission;
11957429Smarkm
12057429Smarkm/* List of all permitted host/port pairs to connect. */
12157429Smarkmstatic ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
12257429Smarkm/* Number of permitted host/port pairs in the array. */
12357429Smarkmstatic int num_permitted_opens = 0;
12457429Smarkm/*
12557429Smarkm * If this is true, all opens are permitted.  This is the case on the server
12657429Smarkm * on which we have to trust the client anyway, and the user could do
12757429Smarkm * anything after logging in anyway.
12857429Smarkm */
12957429Smarkmstatic int all_opens_permitted = 0;
13057429Smarkm
13157429Smarkm/* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
13257429Smarkmstatic int have_hostname_in_open = 0;
13357429Smarkm
13457429Smarkm/* Sets specific protocol options. */
13557429Smarkm
13660573Skrisvoid
13757429Smarkmchannel_set_options(int hostname_in_open)
13857429Smarkm{
13957429Smarkm	have_hostname_in_open = hostname_in_open;
14057429Smarkm}
14157429Smarkm
14257429Smarkm/*
14357429Smarkm * Permits opening to any host/port in SSH_MSG_PORT_OPEN.  This is usually
14457429Smarkm * called by the server, because the user could connect to any port anyway,
14557429Smarkm * and the server has no way to know but to trust the client anyway.
14657429Smarkm */
14757429Smarkm
14860573Skrisvoid
14957429Smarkmchannel_permit_all_opens()
15057429Smarkm{
15157429Smarkm	all_opens_permitted = 1;
15257429Smarkm}
15357429Smarkm
15460573Skris/* lookup channel by id */
15560573Skris
15660573SkrisChannel *
15760573Skrischannel_lookup(int id)
15860573Skris{
15960573Skris	Channel *c;
16065668Skris	if (id < 0 || id > channels_alloc) {
16160573Skris		log("channel_lookup: %d: bad id", id);
16260573Skris		return NULL;
16360573Skris	}
16460573Skris	c = &channels[id];
16560573Skris	if (c->type == SSH_CHANNEL_FREE) {
16660573Skris		log("channel_lookup: %d: bad id: channel free", id);
16760573Skris		return NULL;
16860573Skris	}
16960573Skris	return c;
17060573Skris}
17160573Skris
17257429Smarkm/*
17360573Skris * Register filedescriptors for a channel, used when allocating a channel or
17460573Skris * when the channel consumer/producer is ready, e.g. shell exec'd
17560573Skris */
17660573Skris
17760573Skrisvoid
17869587Sgreenchannel_register_fds(Channel *c, int rfd, int wfd, int efd,
17969587Sgreen    int extusage, int nonblock)
18060573Skris{
18160573Skris	/* Update the maximum file descriptor value. */
18260573Skris	if (rfd > channel_max_fd_value)
18360573Skris		channel_max_fd_value = rfd;
18460573Skris	if (wfd > channel_max_fd_value)
18560573Skris		channel_max_fd_value = wfd;
18660573Skris	if (efd > channel_max_fd_value)
18760573Skris		channel_max_fd_value = efd;
18860573Skris	/* XXX set close-on-exec -markus */
18960573Skris
19060573Skris	c->rfd = rfd;
19160573Skris	c->wfd = wfd;
19260573Skris	c->sock = (rfd == wfd) ? rfd : -1;
19360573Skris	c->efd = efd;
19460573Skris	c->extended_usage = extusage;
19569587Sgreen
19674500Sgreen	/* XXX ugly hack: nonblock is only set by the server */
19774500Sgreen	if (nonblock && isatty(c->rfd)) {
19874500Sgreen		debug("channel: %d: rfd %d isatty", c->self, c->rfd);
19974500Sgreen		c->isatty = 1;
20074500Sgreen		if (!isatty(c->wfd)) {
20174500Sgreen			error("channel: %d: wfd %d is not a tty?",
20274500Sgreen			    c->self, c->wfd);
20374500Sgreen		}
20474500Sgreen	} else {
20574500Sgreen		c->isatty = 0;
20674500Sgreen	}
20774500Sgreen
20869587Sgreen	/* enable nonblocking mode */
20969587Sgreen	if (nonblock) {
21069587Sgreen		if (rfd != -1)
21169587Sgreen			set_nonblock(rfd);
21269587Sgreen		if (wfd != -1)
21369587Sgreen			set_nonblock(wfd);
21469587Sgreen		if (efd != -1)
21569587Sgreen			set_nonblock(efd);
21669587Sgreen	}
21760573Skris}
21860573Skris
21960573Skris/*
22057429Smarkm * Allocate a new channel object and set its type and socket. This will cause
22157429Smarkm * remote_name to be freed.
22257429Smarkm */
22357429Smarkm
22460573Skrisint
22560573Skrischannel_new(char *ctype, int type, int rfd, int wfd, int efd,
22669587Sgreen    int window, int maxpack, int extusage, char *remote_name, int nonblock)
22757429Smarkm{
22857429Smarkm	int i, found;
22957429Smarkm	Channel *c;
23057429Smarkm
23157429Smarkm	/* Do initial allocation if this is the first call. */
23257429Smarkm	if (channels_alloc == 0) {
23360573Skris		chan_init();
23457429Smarkm		channels_alloc = 10;
23557429Smarkm		channels = xmalloc(channels_alloc * sizeof(Channel));
23657429Smarkm		for (i = 0; i < channels_alloc; i++)
23757429Smarkm			channels[i].type = SSH_CHANNEL_FREE;
23857429Smarkm		/*
23957429Smarkm		 * Kludge: arrange a call to channel_stop_listening if we
24057429Smarkm		 * terminate with fatal().
24157429Smarkm		 */
24257429Smarkm		fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
24357429Smarkm	}
24457429Smarkm	/* Try to find a free slot where to put the new channel. */
24557429Smarkm	for (found = -1, i = 0; i < channels_alloc; i++)
24657429Smarkm		if (channels[i].type == SSH_CHANNEL_FREE) {
24757429Smarkm			/* Found a free slot. */
24857429Smarkm			found = i;
24957429Smarkm			break;
25057429Smarkm		}
25157429Smarkm	if (found == -1) {
25257429Smarkm		/* There are no free slots.  Take last+1 slot and expand the array.  */
25357429Smarkm		found = channels_alloc;
25457429Smarkm		channels_alloc += 10;
25569587Sgreen		debug2("channel: expanding %d", channels_alloc);
25657429Smarkm		channels = xrealloc(channels, channels_alloc * sizeof(Channel));
25757429Smarkm		for (i = found; i < channels_alloc; i++)
25857429Smarkm			channels[i].type = SSH_CHANNEL_FREE;
25957429Smarkm	}
26057429Smarkm	/* Initialize and return new channel number. */
26157429Smarkm	c = &channels[found];
26257429Smarkm	buffer_init(&c->input);
26357429Smarkm	buffer_init(&c->output);
26460573Skris	buffer_init(&c->extended);
26557429Smarkm	chan_init_iostates(c);
26669587Sgreen	channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
26757429Smarkm	c->self = found;
26857429Smarkm	c->type = type;
26960573Skris	c->ctype = ctype;
27060573Skris	c->local_window = window;
27160573Skris	c->local_window_max = window;
27260573Skris	c->local_consumed = 0;
27360573Skris	c->local_maxpacket = maxpack;
27457429Smarkm	c->remote_id = -1;
27557429Smarkm	c->remote_name = remote_name;
27660573Skris	c->remote_window = 0;
27760573Skris	c->remote_maxpacket = 0;
27860573Skris	c->cb_fn = NULL;
27960573Skris	c->cb_arg = NULL;
28060573Skris	c->cb_event = 0;
28160573Skris	c->dettach_user = NULL;
28265668Skris	c->input_filter = NULL;
28357429Smarkm	debug("channel %d: new [%s]", found, remote_name);
28457429Smarkm	return found;
28557429Smarkm}
28660573Skris/* old interface XXX */
28760573Skrisint
28860573Skrischannel_allocate(int type, int sock, char *remote_name)
28960573Skris{
29069587Sgreen	return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name, 1);
29160573Skris}
29257429Smarkm
29357429Smarkm
29460573Skris/* Close all channel fd/socket. */
29560573Skris
29660573Skrisvoid
29760573Skrischannel_close_fds(Channel *c)
29857429Smarkm{
29960573Skris	if (c->sock != -1) {
30060573Skris		close(c->sock);
30160573Skris		c->sock = -1;
30260573Skris	}
30360573Skris	if (c->rfd != -1) {
30460573Skris		close(c->rfd);
30560573Skris		c->rfd = -1;
30660573Skris	}
30760573Skris	if (c->wfd != -1) {
30860573Skris		close(c->wfd);
30960573Skris		c->wfd = -1;
31060573Skris	}
31160573Skris	if (c->efd != -1) {
31260573Skris		close(c->efd);
31360573Skris		c->efd = -1;
31460573Skris	}
31560573Skris}
31657429Smarkm
31760573Skris/* Free the channel and close its fd/socket. */
31860573Skris
31960573Skrisvoid
32060573Skrischannel_free(int id)
32160573Skris{
32260573Skris	Channel *c = channel_lookup(id);
32360573Skris	if (c == NULL)
32460573Skris		packet_disconnect("channel free: bad local channel %d", id);
32560573Skris	debug("channel_free: channel %d: status: %s", id, channel_open_message());
32660573Skris	if (c->dettach_user != NULL) {
32760573Skris		debug("channel_free: channel %d: dettaching channel user", id);
32860573Skris		c->dettach_user(c->self, NULL);
32957429Smarkm	}
33060573Skris	if (c->sock != -1)
33160573Skris		shutdown(c->sock, SHUT_RDWR);
33260573Skris	channel_close_fds(c);
33360573Skris	buffer_free(&c->input);
33460573Skris	buffer_free(&c->output);
33560573Skris	buffer_free(&c->extended);
33660573Skris	c->type = SSH_CHANNEL_FREE;
33760573Skris	if (c->remote_name) {
33860573Skris		xfree(c->remote_name);
33960573Skris		c->remote_name = NULL;
34060573Skris	}
34157429Smarkm}
34257429Smarkm
34357429Smarkm/*
34460573Skris * 'channel_pre*' are called just before select() to add any bits relevant to
34560573Skris * channels in the select bitmasks.
34657429Smarkm */
34760573Skris/*
34860573Skris * 'channel_post*': perform any appropriate operations for channels which
34960573Skris * have events pending.
35060573Skris */
35160573Skristypedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
35260573Skrischan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
35360573Skrischan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
35457429Smarkm
35560573Skrisvoid
35660573Skrischannel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
35757429Smarkm{
35860573Skris	FD_SET(c->sock, readset);
35960573Skris}
36060573Skris
36160573Skrisvoid
36260573Skrischannel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
36360573Skris{
36460573Skris	if (buffer_len(&c->input) < packet_get_maxsize())
36560573Skris		FD_SET(c->sock, readset);
36660573Skris	if (buffer_len(&c->output) > 0)
36760573Skris		FD_SET(c->sock, writeset);
36860573Skris}
36960573Skris
37060573Skrisvoid
37160573Skrischannel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
37260573Skris{
37360573Skris	/* test whether sockets are 'alive' for read/write */
37460573Skris	if (c->istate == CHAN_INPUT_OPEN)
37560573Skris		if (buffer_len(&c->input) < packet_get_maxsize())
37660573Skris			FD_SET(c->sock, readset);
37760573Skris	if (c->ostate == CHAN_OUTPUT_OPEN ||
37860573Skris	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
37960573Skris		if (buffer_len(&c->output) > 0) {
38060573Skris			FD_SET(c->sock, writeset);
38160573Skris		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
38260573Skris			chan_obuf_empty(c);
38360573Skris		}
38460573Skris	}
38560573Skris}
38660573Skris
38760573Skrisvoid
38860573Skrischannel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
38960573Skris{
39060573Skris	if (c->istate == CHAN_INPUT_OPEN &&
39160573Skris	    c->remote_window > 0 &&
39260573Skris	    buffer_len(&c->input) < c->remote_window)
39360573Skris		FD_SET(c->rfd, readset);
39460573Skris	if (c->ostate == CHAN_OUTPUT_OPEN ||
39560573Skris	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
39660573Skris		if (buffer_len(&c->output) > 0) {
39760573Skris			FD_SET(c->wfd, writeset);
39860573Skris		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
39960573Skris			chan_obuf_empty(c);
40060573Skris		}
40160573Skris	}
40260573Skris	/** XXX check close conditions, too */
40360573Skris	if (c->efd != -1) {
40460573Skris		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
40560573Skris		    buffer_len(&c->extended) > 0)
40660573Skris			FD_SET(c->efd, writeset);
40760573Skris		else if (c->extended_usage == CHAN_EXTENDED_READ &&
40860573Skris		    buffer_len(&c->extended) < c->remote_window)
40960573Skris			FD_SET(c->efd, readset);
41060573Skris	}
41160573Skris}
41260573Skris
41360573Skrisvoid
41460573Skrischannel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
41560573Skris{
41660573Skris	if (buffer_len(&c->input) == 0) {
41760573Skris		packet_start(SSH_MSG_CHANNEL_CLOSE);
41860573Skris		packet_put_int(c->remote_id);
41960573Skris		packet_send();
42060573Skris		c->type = SSH_CHANNEL_CLOSED;
42160573Skris		debug("Closing channel %d after input drain.", c->self);
42260573Skris	}
42360573Skris}
42460573Skris
42560573Skrisvoid
42660573Skrischannel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
42760573Skris{
42860573Skris	if (buffer_len(&c->output) == 0)
42960573Skris		channel_free(c->self);
43060573Skris	else
43160573Skris		FD_SET(c->sock, writeset);
43260573Skris}
43360573Skris
43460573Skris/*
43560573Skris * This is a special state for X11 authentication spoofing.  An opened X11
43660573Skris * connection (when authentication spoofing is being done) remains in this
43760573Skris * state until the first packet has been completely read.  The authentication
43860573Skris * data in that packet is then substituted by the real data if it matches the
43960573Skris * fake data, and the channel is put into normal mode.
44060573Skris * XXX All this happens at the client side.
44160573Skris */
44260573Skrisint
44360573Skrisx11_open_helper(Channel *c)
44460573Skris{
44557429Smarkm	unsigned char *ucp;
44657429Smarkm	unsigned int proto_len, data_len;
44757429Smarkm
44860573Skris	/* Check if the fixed size part of the packet is in buffer. */
44960573Skris	if (buffer_len(&c->output) < 12)
45060573Skris		return 0;
45157429Smarkm
45260573Skris	/* Parse the lengths of variable-length fields. */
45360573Skris	ucp = (unsigned char *) buffer_ptr(&c->output);
45460573Skris	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
45560573Skris		proto_len = 256 * ucp[6] + ucp[7];
45660573Skris		data_len = 256 * ucp[8] + ucp[9];
45760573Skris	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
45860573Skris		proto_len = ucp[6] + 256 * ucp[7];
45960573Skris		data_len = ucp[8] + 256 * ucp[9];
46060573Skris	} else {
46160573Skris		debug("Initial X11 packet contains bad byte order byte: 0x%x",
46260573Skris		      ucp[0]);
46360573Skris		return -1;
46460573Skris	}
46557429Smarkm
46660573Skris	/* Check if the whole packet is in buffer. */
46760573Skris	if (buffer_len(&c->output) <
46860573Skris	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
46960573Skris		return 0;
47057429Smarkm
47160573Skris	/* Check if authentication protocol matches. */
47260573Skris	if (proto_len != strlen(x11_saved_proto) ||
47360573Skris	    memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
47460573Skris		debug("X11 connection uses different authentication protocol.");
47560573Skris		return -1;
47660573Skris	}
47760573Skris	/* Check if authentication data matches our fake data. */
47860573Skris	if (data_len != x11_fake_data_len ||
47960573Skris	    memcmp(ucp + 12 + ((proto_len + 3) & ~3),
48060573Skris		x11_fake_data, x11_fake_data_len) != 0) {
48160573Skris		debug("X11 auth data does not match fake data.");
48260573Skris		return -1;
48360573Skris	}
48460573Skris	/* Check fake data length */
48560573Skris	if (x11_fake_data_len != x11_saved_data_len) {
48660573Skris		error("X11 fake_data_len %d != saved_data_len %d",
48760573Skris		    x11_fake_data_len, x11_saved_data_len);
48860573Skris		return -1;
48960573Skris	}
49060573Skris	/*
49160573Skris	 * Received authentication protocol and data match
49260573Skris	 * our fake data. Substitute the fake data with real
49360573Skris	 * data.
49460573Skris	 */
49560573Skris	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
49660573Skris	    x11_saved_data, x11_saved_data_len);
49760573Skris	return 1;
49860573Skris}
49957429Smarkm
50060573Skrisvoid
50160573Skrischannel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
50260573Skris{
50360573Skris	int ret = x11_open_helper(c);
50460573Skris	if (ret == 1) {
50560573Skris		/* Start normal processing for the channel. */
50660573Skris		c->type = SSH_CHANNEL_OPEN;
50760573Skris		channel_pre_open_13(c, readset, writeset);
50860573Skris	} else if (ret == -1) {
50960573Skris		/*
51060573Skris		 * We have received an X11 connection that has bad
51160573Skris		 * authentication information.
51260573Skris		 */
51360573Skris		log("X11 connection rejected because of wrong authentication.\r\n");
51460573Skris		buffer_clear(&c->input);
51560573Skris		buffer_clear(&c->output);
51660573Skris		close(c->sock);
51760573Skris		c->sock = -1;
51860573Skris		c->type = SSH_CHANNEL_CLOSED;
51960573Skris		packet_start(SSH_MSG_CHANNEL_CLOSE);
52060573Skris		packet_put_int(c->remote_id);
52160573Skris		packet_send();
52260573Skris	}
52360573Skris}
52457429Smarkm
52560573Skrisvoid
52660573Skrischannel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
52760573Skris{
52860573Skris	int ret = x11_open_helper(c);
52960573Skris	if (ret == 1) {
53060573Skris		c->type = SSH_CHANNEL_OPEN;
53160573Skris		if (compat20)
53260573Skris			channel_pre_open_20(c, readset, writeset);
53360573Skris		else
53460573Skris			channel_pre_open_15(c, readset, writeset);
53560573Skris	} else if (ret == -1) {
53660573Skris		debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
53760573Skris		chan_read_failed(c);	/** force close? */
53860573Skris		chan_write_failed(c);
53960573Skris		debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
54060573Skris	}
54160573Skris}
54257429Smarkm
54360573Skris/* This is our fake X11 server socket. */
54460573Skrisvoid
54560573Skrischannel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
54660573Skris{
54760573Skris	struct sockaddr addr;
54860573Skris	int newsock, newch;
54960573Skris	socklen_t addrlen;
55060573Skris	char buf[16384], *remote_hostname;
55160573Skris	int remote_port;
55257429Smarkm
55360573Skris	if (FD_ISSET(c->sock, readset)) {
55460573Skris		debug("X11 connection requested.");
55560573Skris		addrlen = sizeof(addr);
55660573Skris		newsock = accept(c->sock, &addr, &addrlen);
55760573Skris		if (newsock < 0) {
55860573Skris			error("accept: %.100s", strerror(errno));
55960573Skris			return;
56060573Skris		}
56160573Skris		remote_hostname = get_remote_hostname(newsock);
56260573Skris		remote_port = get_peer_port(newsock);
56360573Skris		snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
56460573Skris		    remote_hostname, remote_port);
56557429Smarkm
56660573Skris		newch = channel_new("x11",
56760573Skris		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
56860573Skris		    c->local_window_max, c->local_maxpacket,
56969587Sgreen		    0, xstrdup(buf), 1);
57060573Skris		if (compat20) {
57160573Skris			packet_start(SSH2_MSG_CHANNEL_OPEN);
57260573Skris			packet_put_cstring("x11");
57360573Skris			packet_put_int(newch);
57460573Skris			packet_put_int(c->local_window_max);
57560573Skris			packet_put_int(c->local_maxpacket);
57660573Skris			/* originator host and port */
57760573Skris			packet_put_cstring(remote_hostname);
57860573Skris			if (datafellows & SSH_BUG_X11FWD) {
57960573Skris				debug("ssh2 x11 bug compat mode");
58057429Smarkm			} else {
58160573Skris				packet_put_int(remote_port);
58257429Smarkm			}
58360573Skris			packet_send();
58460573Skris		} else {
58560573Skris			packet_start(SSH_SMSG_X11_OPEN);
58660573Skris			packet_put_int(newch);
58760573Skris			if (have_hostname_in_open)
58860573Skris				packet_put_string(buf, strlen(buf));
58960573Skris			packet_send();
59057429Smarkm		}
59160573Skris		xfree(remote_hostname);
59257429Smarkm	}
59357429Smarkm}
59457429Smarkm
59557429Smarkm/*
59660573Skris * This socket is listening for connections to a forwarded TCP/IP port.
59757429Smarkm */
59860573Skrisvoid
59960573Skrischannel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
60057429Smarkm{
60157429Smarkm	struct sockaddr addr;
60260573Skris	int newsock, newch;
60357429Smarkm	socklen_t addrlen;
60460573Skris	char buf[1024], *remote_hostname;
60560573Skris	int remote_port;
60657429Smarkm
60760573Skris	if (FD_ISSET(c->sock, readset)) {
60860573Skris		debug("Connection to port %d forwarding "
60960573Skris		    "to %.100s port %d requested.",
61060573Skris		    c->listening_port, c->path, c->host_port);
61160573Skris		addrlen = sizeof(addr);
61260573Skris		newsock = accept(c->sock, &addr, &addrlen);
61360573Skris		if (newsock < 0) {
61460573Skris			error("accept: %.100s", strerror(errno));
61560573Skris			return;
61660573Skris		}
61760573Skris		remote_hostname = get_remote_hostname(newsock);
61860573Skris		remote_port = get_peer_port(newsock);
61960573Skris		snprintf(buf, sizeof buf,
62060573Skris		    "listen port %d for %.100s port %d, "
62160573Skris		    "connect from %.200s port %d",
62260573Skris		    c->listening_port, c->path, c->host_port,
62360573Skris		    remote_hostname, remote_port);
62460573Skris		newch = channel_new("direct-tcpip",
62560573Skris		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
62660573Skris		    c->local_window_max, c->local_maxpacket,
62769587Sgreen		    0, xstrdup(buf), 1);
62860573Skris		if (compat20) {
62960573Skris			packet_start(SSH2_MSG_CHANNEL_OPEN);
63060573Skris			packet_put_cstring("direct-tcpip");
63160573Skris			packet_put_int(newch);
63260573Skris			packet_put_int(c->local_window_max);
63360573Skris			packet_put_int(c->local_maxpacket);
63460573Skris			/* target host and port */
63560573Skris			packet_put_string(c->path, strlen(c->path));
63660573Skris			packet_put_int(c->host_port);
63760573Skris			/* originator host and port */
63860573Skris			packet_put_cstring(remote_hostname);
63960573Skris			packet_put_int(remote_port);
64060573Skris			packet_send();
64160573Skris		} else {
64260573Skris			packet_start(SSH_MSG_PORT_OPEN);
64360573Skris			packet_put_int(newch);
64460573Skris			packet_put_string(c->path, strlen(c->path));
64560573Skris			packet_put_int(c->host_port);
64660573Skris			if (have_hostname_in_open) {
64760573Skris				packet_put_string(buf, strlen(buf));
64857429Smarkm			}
64960573Skris			packet_send();
65060573Skris		}
65160573Skris		xfree(remote_hostname);
65260573Skris	}
65360573Skris}
65457429Smarkm
65560573Skris/*
65660573Skris * This is the authentication agent socket listening for connections from
65760573Skris * clients.
65860573Skris */
65960573Skrisvoid
66060573Skrischannel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
66160573Skris{
66260573Skris	struct sockaddr addr;
66360573Skris	int newsock, newch;
66460573Skris	socklen_t addrlen;
66557429Smarkm
66660573Skris	if (FD_ISSET(c->sock, readset)) {
66760573Skris		addrlen = sizeof(addr);
66860573Skris		newsock = accept(c->sock, &addr, &addrlen);
66960573Skris		if (newsock < 0) {
67060573Skris			error("accept from auth socket: %.100s", strerror(errno));
67160573Skris			return;
67260573Skris		}
67360573Skris		newch = channel_allocate(SSH_CHANNEL_OPENING, newsock,
67460573Skris		    xstrdup("accepted auth socket"));
67560573Skris		packet_start(SSH_SMSG_AGENT_OPEN);
67660573Skris		packet_put_int(newch);
67760573Skris		packet_send();
67860573Skris	}
67960573Skris}
68057429Smarkm
68160573Skrisint
68260573Skrischannel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
68360573Skris{
68460573Skris	char buf[16*1024];
68560573Skris	int len;
68657429Smarkm
68760573Skris	if (c->rfd != -1 &&
68860573Skris	    FD_ISSET(c->rfd, readset)) {
68960573Skris		len = read(c->rfd, buf, sizeof(buf));
69060573Skris		if (len < 0 && (errno == EINTR || errno == EAGAIN))
69160573Skris			return 1;
69260573Skris		if (len <= 0) {
69360573Skris			debug("channel %d: read<=0 rfd %d len %d",
69460573Skris			    c->self, c->rfd, len);
69560573Skris			if (compat13) {
69660573Skris				buffer_consume(&c->output, buffer_len(&c->output));
69760573Skris				c->type = SSH_CHANNEL_INPUT_DRAINING;
69860573Skris				debug("Channel %d status set to input draining.", c->self);
69960573Skris			} else {
70060573Skris				chan_read_failed(c);
70157429Smarkm			}
70260573Skris			return -1;
70360573Skris		}
70465668Skris		if(c->input_filter != NULL) {
70565668Skris			if (c->input_filter(c, buf, len) == -1) {
70665668Skris				debug("filter stops channel %d", c->self);
70765668Skris				chan_read_failed(c);
70865668Skris			}
70965668Skris		} else {
71065668Skris			buffer_append(&c->input, buf, len);
71165668Skris		}
71260573Skris	}
71360573Skris	return 1;
71460573Skris}
71560573Skrisint
71660573Skrischannel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
71760573Skris{
71860573Skris	int len;
71960573Skris
72060573Skris	/* Send buffered output data to the socket. */
72160573Skris	if (c->wfd != -1 &&
72260573Skris	    FD_ISSET(c->wfd, writeset) &&
72360573Skris	    buffer_len(&c->output) > 0) {
72460573Skris		len = write(c->wfd, buffer_ptr(&c->output),
72560573Skris		    buffer_len(&c->output));
72660573Skris		if (len < 0 && (errno == EINTR || errno == EAGAIN))
72760573Skris			return 1;
72860573Skris		if (len <= 0) {
72960573Skris			if (compat13) {
73060573Skris				buffer_consume(&c->output, buffer_len(&c->output));
73160573Skris				debug("Channel %d status set to input draining.", c->self);
73260573Skris				c->type = SSH_CHANNEL_INPUT_DRAINING;
73360573Skris			} else {
73460573Skris				chan_write_failed(c);
73557429Smarkm			}
73660573Skris			return -1;
73760573Skris		}
73874500Sgreen		if (compat20 && c->isatty) {
73974500Sgreen			struct termios tio;
74074500Sgreen			if (tcgetattr(c->wfd, &tio) == 0 &&
74174500Sgreen			    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
74274500Sgreen				/*
74374500Sgreen				 * Simulate echo to reduce the impact of
74474500Sgreen				 * traffic analysis.
74574500Sgreen				 */
74674500Sgreen				packet_start(SSH2_MSG_IGNORE);
74774500Sgreen				memset(buffer_ptr(&c->output), 0, len);
74874500Sgreen				packet_put_string(buffer_ptr(&c->output), len);
74974500Sgreen				packet_send();
75074500Sgreen			}
75174500Sgreen		}
75260573Skris		buffer_consume(&c->output, len);
75360573Skris		if (compat20 && len > 0) {
75460573Skris			c->local_consumed += len;
75560573Skris		}
75660573Skris	}
75760573Skris	return 1;
75860573Skris}
75960573Skrisint
76060573Skrischannel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
76160573Skris{
76260573Skris	char buf[16*1024];
76360573Skris	int len;
76457429Smarkm
76560573Skris/** XXX handle drain efd, too */
76660573Skris	if (c->efd != -1) {
76760573Skris		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
76860573Skris		    FD_ISSET(c->efd, writeset) &&
76960573Skris		    buffer_len(&c->extended) > 0) {
77060573Skris			len = write(c->efd, buffer_ptr(&c->extended),
77160573Skris			    buffer_len(&c->extended));
77269587Sgreen			debug2("channel %d: written %d to efd %d",
77360573Skris			    c->self, len, c->efd);
77460573Skris			if (len > 0) {
77560573Skris				buffer_consume(&c->extended, len);
77660573Skris				c->local_consumed += len;
77757429Smarkm			}
77860573Skris		} else if (c->extended_usage == CHAN_EXTENDED_READ &&
77960573Skris		    FD_ISSET(c->efd, readset)) {
78060573Skris			len = read(c->efd, buf, sizeof(buf));
78169587Sgreen			debug2("channel %d: read %d from efd %d",
78260573Skris			     c->self, len, c->efd);
78360573Skris			if (len == 0) {
78460573Skris				debug("channel %d: closing efd %d",
78560573Skris				    c->self, c->efd);
78660573Skris				close(c->efd);
78760573Skris				c->efd = -1;
78860573Skris			} else if (len > 0)
78960573Skris				buffer_append(&c->extended, buf, len);
79060573Skris		}
79160573Skris	}
79260573Skris	return 1;
79360573Skris}
79460573Skrisint
79560573Skrischannel_check_window(Channel *c, fd_set * readset, fd_set * writeset)
79660573Skris{
79760573Skris	if (!(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
79860573Skris	    c->local_window < c->local_window_max/2 &&
79960573Skris	    c->local_consumed > 0) {
80060573Skris		packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
80160573Skris		packet_put_int(c->remote_id);
80260573Skris		packet_put_int(c->local_consumed);
80360573Skris		packet_send();
80469587Sgreen		debug2("channel %d: window %d sent adjust %d",
80560573Skris		    c->self, c->local_window,
80660573Skris		    c->local_consumed);
80760573Skris		c->local_window += c->local_consumed;
80860573Skris		c->local_consumed = 0;
80960573Skris	}
81060573Skris	return 1;
81160573Skris}
81257429Smarkm
81360573Skrisvoid
81460573Skrischannel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
81560573Skris{
81660573Skris	channel_handle_rfd(c, readset, writeset);
81760573Skris	channel_handle_wfd(c, readset, writeset);
81860573Skris}
81960573Skris
82060573Skrisvoid
82160573Skrischannel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
82260573Skris{
82360573Skris	channel_handle_rfd(c, readset, writeset);
82460573Skris	channel_handle_wfd(c, readset, writeset);
82560573Skris	channel_handle_efd(c, readset, writeset);
82660573Skris	channel_check_window(c, readset, writeset);
82760573Skris}
82860573Skris
82960573Skrisvoid
83060573Skrischannel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
83160573Skris{
83260573Skris	int len;
83360573Skris	/* Send buffered output data to the socket. */
83460573Skris	if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
83560573Skris		len = write(c->sock, buffer_ptr(&c->output),
83660573Skris			    buffer_len(&c->output));
83760573Skris		if (len <= 0)
83860573Skris			buffer_consume(&c->output, buffer_len(&c->output));
83960573Skris		else
84060573Skris			buffer_consume(&c->output, len);
84160573Skris	}
84260573Skris}
84360573Skris
84460573Skrisvoid
84560573Skrischannel_handler_init_20(void)
84660573Skris{
84760573Skris	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_20;
84860573Skris	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
84960573Skris	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
85060573Skris	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
85160573Skris
85260573Skris	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_2;
85360573Skris	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
85460573Skris	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
85560573Skris}
85660573Skris
85760573Skrisvoid
85860573Skrischannel_handler_init_13(void)
85960573Skris{
86060573Skris	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_13;
86160573Skris	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open_13;
86260573Skris	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
86360573Skris	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
86460573Skris	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
86560573Skris	channel_pre[SSH_CHANNEL_INPUT_DRAINING] =	&channel_pre_input_draining;
86660573Skris	channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_pre_output_draining;
86760573Skris
86860573Skris	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_1;
86960573Skris	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
87060573Skris	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
87160573Skris	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
87260573Skris	channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_post_output_drain_13;
87360573Skris}
87460573Skris
87560573Skrisvoid
87660573Skrischannel_handler_init_15(void)
87760573Skris{
87860573Skris	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_15;
87960573Skris	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
88060573Skris	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
88160573Skris	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
88260573Skris	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
88360573Skris
88460573Skris	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
88560573Skris	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
88660573Skris	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
88760573Skris	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_1;
88860573Skris}
88960573Skris
89060573Skrisvoid
89160573Skrischannel_handler_init(void)
89260573Skris{
89360573Skris	int i;
89460573Skris	for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
89560573Skris		channel_pre[i] = NULL;
89660573Skris		channel_post[i] = NULL;
89760573Skris	}
89860573Skris	if (compat20)
89960573Skris		channel_handler_init_20();
90060573Skris	else if (compat13)
90160573Skris		channel_handler_init_13();
90260573Skris	else
90360573Skris		channel_handler_init_15();
90460573Skris}
90560573Skris
90660573Skrisvoid
90760573Skrischannel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
90860573Skris{
90960573Skris	static int did_init = 0;
91060573Skris	int i;
91160573Skris	Channel *c;
91260573Skris
91360573Skris	if (!did_init) {
91460573Skris		channel_handler_init();
91560573Skris		did_init = 1;
91660573Skris	}
91760573Skris	for (i = 0; i < channels_alloc; i++) {
91860573Skris		c = &channels[i];
91960573Skris		if (c->type == SSH_CHANNEL_FREE)
92057429Smarkm			continue;
92160573Skris		if (ftab[c->type] == NULL)
92260573Skris			continue;
92360573Skris		(*ftab[c->type])(c, readset, writeset);
92460573Skris		chan_delete_if_full_closed(c);
92557429Smarkm	}
92657429Smarkm}
92757429Smarkm
92860573Skrisvoid
92960573Skrischannel_prepare_select(fd_set * readset, fd_set * writeset)
93060573Skris{
93160573Skris	channel_handler(channel_pre, readset, writeset);
93260573Skris}
93360573Skris
93460573Skrisvoid
93560573Skrischannel_after_select(fd_set * readset, fd_set * writeset)
93660573Skris{
93760573Skris	channel_handler(channel_post, readset, writeset);
93860573Skris}
93960573Skris
94057429Smarkm/* If there is data to send to the connection, send some of it now. */
94157429Smarkm
94260573Skrisvoid
94357429Smarkmchannel_output_poll()
94457429Smarkm{
94557429Smarkm	int len, i;
94660573Skris	Channel *c;
94757429Smarkm
94857429Smarkm	for (i = 0; i < channels_alloc; i++) {
94960573Skris		c = &channels[i];
95057429Smarkm
95157429Smarkm		/* We are only interested in channels that can have buffered incoming data. */
95257429Smarkm		if (compat13) {
95360573Skris			if (c->type != SSH_CHANNEL_OPEN &&
95460573Skris			    c->type != SSH_CHANNEL_INPUT_DRAINING)
95557429Smarkm				continue;
95657429Smarkm		} else {
95760573Skris			if (c->type != SSH_CHANNEL_OPEN)
95857429Smarkm				continue;
95960573Skris			if (c->istate != CHAN_INPUT_OPEN &&
96060573Skris			    c->istate != CHAN_INPUT_WAIT_DRAIN)
96157429Smarkm				continue;
96257429Smarkm		}
96360573Skris		if (compat20 &&
96460573Skris		    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
96560573Skris			debug("channel: %d: no data after CLOSE", c->self);
96660573Skris			continue;
96760573Skris		}
96857429Smarkm
96957429Smarkm		/* Get the amount of buffered data for this channel. */
97060573Skris		len = buffer_len(&c->input);
97157429Smarkm		if (len > 0) {
97257429Smarkm			/* Send some data for the other side over the secure connection. */
97360573Skris			if (compat20) {
97460573Skris				if (len > c->remote_window)
97560573Skris					len = c->remote_window;
97660573Skris				if (len > c->remote_maxpacket)
97760573Skris					len = c->remote_maxpacket;
97857429Smarkm			} else {
97960573Skris				if (packet_is_interactive()) {
98060573Skris					if (len > 1024)
98160573Skris						len = 512;
98260573Skris				} else {
98360573Skris					/* Keep the packets at reasonable size. */
98460573Skris					if (len > packet_get_maxsize()/2)
98560573Skris						len = packet_get_maxsize()/2;
98660573Skris				}
98757429Smarkm			}
98860573Skris			if (len > 0) {
98960573Skris				packet_start(compat20 ?
99060573Skris				    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
99160573Skris				packet_put_int(c->remote_id);
99260573Skris				packet_put_string(buffer_ptr(&c->input), len);
99360573Skris				packet_send();
99460573Skris				buffer_consume(&c->input, len);
99560573Skris				c->remote_window -= len;
99660573Skris			}
99760573Skris		} else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
99857429Smarkm			if (compat13)
99957429Smarkm				fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
100057429Smarkm			/*
100157429Smarkm			 * input-buffer is empty and read-socket shutdown:
100257429Smarkm			 * tell peer, that we will not send more data: send IEOF
100357429Smarkm			 */
100460573Skris			chan_ibuf_empty(c);
100557429Smarkm		}
100660573Skris		/* Send extended data, i.e. stderr */
100760573Skris		if (compat20 &&
100860573Skris		    c->remote_window > 0 &&
100960573Skris		    (len = buffer_len(&c->extended)) > 0 &&
101060573Skris		    c->extended_usage == CHAN_EXTENDED_READ) {
101160573Skris			if (len > c->remote_window)
101260573Skris				len = c->remote_window;
101360573Skris			if (len > c->remote_maxpacket)
101460573Skris				len = c->remote_maxpacket;
101560573Skris			packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
101660573Skris			packet_put_int(c->remote_id);
101760573Skris			packet_put_int(SSH2_EXTENDED_DATA_STDERR);
101860573Skris			packet_put_string(buffer_ptr(&c->extended), len);
101960573Skris			packet_send();
102060573Skris			buffer_consume(&c->extended, len);
102160573Skris			c->remote_window -= len;
102260573Skris		}
102357429Smarkm	}
102457429Smarkm}
102557429Smarkm
102657429Smarkm/*
102757429Smarkm * This is called when a packet of type CHANNEL_DATA has just been received.
102857429Smarkm * The message type has already been consumed, but channel number and data is
102957429Smarkm * still there.
103057429Smarkm */
103157429Smarkm
103260573Skrisvoid
103369587Sgreenchannel_input_data(int type, int plen, void *ctxt)
103457429Smarkm{
103557429Smarkm	int id;
103657429Smarkm	char *data;
103757429Smarkm	unsigned int data_len;
103860573Skris	Channel *c;
103957429Smarkm
104057429Smarkm	/* Get the channel number and verify it. */
104157429Smarkm	id = packet_get_int();
104260573Skris	c = channel_lookup(id);
104360573Skris	if (c == NULL)
104457429Smarkm		packet_disconnect("Received data for nonexistent channel %d.", id);
104557429Smarkm
104657429Smarkm	/* Ignore any data for non-open channels (might happen on close) */
104760573Skris	if (c->type != SSH_CHANNEL_OPEN &&
104860573Skris	    c->type != SSH_CHANNEL_X11_OPEN)
104957429Smarkm		return;
105057429Smarkm
105157429Smarkm	/* same for protocol 1.5 if output end is no longer open */
105260573Skris	if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
105357429Smarkm		return;
105457429Smarkm
105557429Smarkm	/* Get the data. */
105657429Smarkm	data = packet_get_string(&data_len);
105760573Skris	packet_done();
105860573Skris
105960573Skris	if (compat20){
106060573Skris		if (data_len > c->local_maxpacket) {
106160573Skris			log("channel %d: rcvd big packet %d, maxpack %d",
106260573Skris			    c->self, data_len, c->local_maxpacket);
106360573Skris		}
106460573Skris		if (data_len > c->local_window) {
106560573Skris			log("channel %d: rcvd too much data %d, win %d",
106660573Skris			    c->self, data_len, c->local_window);
106760573Skris			xfree(data);
106860573Skris			return;
106960573Skris		}
107060573Skris		c->local_window -= data_len;
107160573Skris	}else{
107260573Skris		packet_integrity_check(plen, 4 + 4 + data_len, type);
107360573Skris	}
107460573Skris	buffer_append(&c->output, data, data_len);
107557429Smarkm	xfree(data);
107657429Smarkm}
107760573Skrisvoid
107869587Sgreenchannel_input_extended_data(int type, int plen, void *ctxt)
107960573Skris{
108060573Skris	int id;
108160573Skris	int tcode;
108260573Skris	char *data;
108360573Skris	unsigned int data_len;
108460573Skris	Channel *c;
108557429Smarkm
108660573Skris	/* Get the channel number and verify it. */
108760573Skris	id = packet_get_int();
108860573Skris	c = channel_lookup(id);
108960573Skris
109060573Skris	if (c == NULL)
109160573Skris		packet_disconnect("Received extended_data for bad channel %d.", id);
109260573Skris	if (c->type != SSH_CHANNEL_OPEN) {
109360573Skris		log("channel %d: ext data for non open", id);
109460573Skris		return;
109560573Skris	}
109660573Skris	tcode = packet_get_int();
109760573Skris	if (c->efd == -1 ||
109860573Skris	    c->extended_usage != CHAN_EXTENDED_WRITE ||
109960573Skris	    tcode != SSH2_EXTENDED_DATA_STDERR) {
110060573Skris		log("channel %d: bad ext data", c->self);
110160573Skris		return;
110260573Skris	}
110360573Skris	data = packet_get_string(&data_len);
110460573Skris	packet_done();
110560573Skris	if (data_len > c->local_window) {
110660573Skris		log("channel %d: rcvd too much extended_data %d, win %d",
110760573Skris		    c->self, data_len, c->local_window);
110860573Skris		xfree(data);
110960573Skris		return;
111060573Skris	}
111169587Sgreen	debug2("channel %d: rcvd ext data %d", c->self, data_len);
111260573Skris	c->local_window -= data_len;
111360573Skris	buffer_append(&c->extended, data, data_len);
111460573Skris	xfree(data);
111560573Skris}
111660573Skris
111760573Skris
111857429Smarkm/*
111957429Smarkm * Returns true if no channel has too much buffered data, and false if one or
112057429Smarkm * more channel is overfull.
112157429Smarkm */
112257429Smarkm
112360573Skrisint
112457429Smarkmchannel_not_very_much_buffered_data()
112557429Smarkm{
112657429Smarkm	unsigned int i;
112760573Skris	Channel *c;
112857429Smarkm
112957429Smarkm	for (i = 0; i < channels_alloc; i++) {
113060573Skris		c = &channels[i];
113160573Skris		if (c->type == SSH_CHANNEL_OPEN) {
113260573Skris			if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
113360573Skris				debug("channel %d: big input buffer %d",
113460573Skris				    c->self, buffer_len(&c->input));
113557429Smarkm				return 0;
113660573Skris			}
113760573Skris			if (buffer_len(&c->output) > packet_get_maxsize()) {
113860573Skris				debug("channel %d: big output buffer %d",
113960573Skris				    c->self, buffer_len(&c->output));
114057429Smarkm				return 0;
114160573Skris			}
114257429Smarkm		}
114357429Smarkm	}
114457429Smarkm	return 1;
114557429Smarkm}
114657429Smarkm
114760573Skrisvoid
114869587Sgreenchannel_input_ieof(int type, int plen, void *ctxt)
114960573Skris{
115060573Skris	int id;
115160573Skris	Channel *c;
115257429Smarkm
115360573Skris	packet_integrity_check(plen, 4, type);
115460573Skris
115560573Skris	id = packet_get_int();
115660573Skris	c = channel_lookup(id);
115760573Skris	if (c == NULL)
115860573Skris		packet_disconnect("Received ieof for nonexistent channel %d.", id);
115960573Skris	chan_rcvd_ieof(c);
116060573Skris}
116160573Skris
116260573Skrisvoid
116369587Sgreenchannel_input_close(int type, int plen, void *ctxt)
116457429Smarkm{
116560573Skris	int id;
116660573Skris	Channel *c;
116757429Smarkm
116860573Skris	packet_integrity_check(plen, 4, type);
116957429Smarkm
117060573Skris	id = packet_get_int();
117160573Skris	c = channel_lookup(id);
117260573Skris	if (c == NULL)
117360573Skris		packet_disconnect("Received close for nonexistent channel %d.", id);
117457429Smarkm
117557429Smarkm	/*
117657429Smarkm	 * Send a confirmation that we have closed the channel and no more
117757429Smarkm	 * data is coming for it.
117857429Smarkm	 */
117957429Smarkm	packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
118060573Skris	packet_put_int(c->remote_id);
118157429Smarkm	packet_send();
118257429Smarkm
118357429Smarkm	/*
118457429Smarkm	 * If the channel is in closed state, we have sent a close request,
118557429Smarkm	 * and the other side will eventually respond with a confirmation.
118657429Smarkm	 * Thus, we cannot free the channel here, because then there would be
118757429Smarkm	 * no-one to receive the confirmation.  The channel gets freed when
118857429Smarkm	 * the confirmation arrives.
118957429Smarkm	 */
119060573Skris	if (c->type != SSH_CHANNEL_CLOSED) {
119157429Smarkm		/*
119257429Smarkm		 * Not a closed channel - mark it as draining, which will
119357429Smarkm		 * cause it to be freed later.
119457429Smarkm		 */
119560573Skris		buffer_consume(&c->input, buffer_len(&c->input));
119660573Skris		c->type = SSH_CHANNEL_OUTPUT_DRAINING;
119757429Smarkm	}
119857429Smarkm}
119957429Smarkm
120060573Skris/* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
120160573Skrisvoid
120269587Sgreenchannel_input_oclose(int type, int plen, void *ctxt)
120360573Skris{
120460573Skris	int id = packet_get_int();
120560573Skris	Channel *c = channel_lookup(id);
120660573Skris	packet_integrity_check(plen, 4, type);
120760573Skris	if (c == NULL)
120860573Skris		packet_disconnect("Received oclose for nonexistent channel %d.", id);
120960573Skris	chan_rcvd_oclose(c);
121060573Skris}
121157429Smarkm
121260573Skrisvoid
121369587Sgreenchannel_input_close_confirmation(int type, int plen, void *ctxt)
121457429Smarkm{
121560573Skris	int id = packet_get_int();
121660573Skris	Channel *c = channel_lookup(id);
121757429Smarkm
121860573Skris	packet_done();
121960573Skris	if (c == NULL)
122060573Skris		packet_disconnect("Received close confirmation for "
122160573Skris		    "out-of-range channel %d.", id);
122260573Skris	if (c->type != SSH_CHANNEL_CLOSED)
122360573Skris		packet_disconnect("Received close confirmation for "
122460573Skris		    "non-closed channel %d (type %d).", id, c->type);
122560573Skris	channel_free(c->self);
122660573Skris}
122757429Smarkm
122860573Skrisvoid
122969587Sgreenchannel_input_open_confirmation(int type, int plen, void *ctxt)
123060573Skris{
123160573Skris	int id, remote_id;
123260573Skris	Channel *c;
123360573Skris
123460573Skris	if (!compat20)
123560573Skris		packet_integrity_check(plen, 4 + 4, type);
123660573Skris
123760573Skris	id = packet_get_int();
123860573Skris	c = channel_lookup(id);
123960573Skris
124060573Skris	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
124160573Skris		packet_disconnect("Received open confirmation for "
124260573Skris		    "non-opening channel %d.", id);
124360573Skris	remote_id = packet_get_int();
124460573Skris	/* Record the remote channel number and mark that the channel is now open. */
124560573Skris	c->remote_id = remote_id;
124660573Skris	c->type = SSH_CHANNEL_OPEN;
124760573Skris
124860573Skris	if (compat20) {
124960573Skris		c->remote_window = packet_get_int();
125060573Skris		c->remote_maxpacket = packet_get_int();
125160573Skris		packet_done();
125260573Skris		if (c->cb_fn != NULL && c->cb_event == type) {
125369587Sgreen			debug2("callback start");
125460573Skris			c->cb_fn(c->self, c->cb_arg);
125569587Sgreen			debug2("callback done");
125660573Skris		}
125760573Skris		debug("channel %d: open confirm rwindow %d rmax %d", c->self,
125860573Skris		    c->remote_window, c->remote_maxpacket);
125957429Smarkm	}
126057429Smarkm}
126157429Smarkm
126260573Skrisvoid
126369587Sgreenchannel_input_open_failure(int type, int plen, void *ctxt)
126457429Smarkm{
126560573Skris	int id;
126660573Skris	Channel *c;
126757429Smarkm
126860573Skris	if (!compat20)
126960573Skris		packet_integrity_check(plen, 4, type);
127057429Smarkm
127160573Skris	id = packet_get_int();
127260573Skris	c = channel_lookup(id);
127357429Smarkm
127460573Skris	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
127560573Skris		packet_disconnect("Received open failure for "
127660573Skris		    "non-opening channel %d.", id);
127760573Skris	if (compat20) {
127860573Skris		int reason = packet_get_int();
127960573Skris		char *msg  = packet_get_string(NULL);
128060573Skris		char *lang  = packet_get_string(NULL);
128160573Skris		log("channel_open_failure: %d: reason %d: %s", id, reason, msg);
128260573Skris		packet_done();
128360573Skris		xfree(msg);
128460573Skris		xfree(lang);
128560573Skris	}
128660573Skris	/* Free the channel.  This will also close the socket. */
128760573Skris	channel_free(id);
128857429Smarkm}
128957429Smarkm
129060573Skrisvoid
129169587Sgreenchannel_input_channel_request(int type, int plen, void *ctxt)
129260573Skris{
129360573Skris	int id;
129460573Skris	Channel *c;
129557429Smarkm
129660573Skris	id = packet_get_int();
129760573Skris	c = channel_lookup(id);
129860573Skris
129960573Skris	if (c == NULL ||
130060573Skris	    (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
130160573Skris		packet_disconnect("Received request for "
130260573Skris		    "non-open channel %d.", id);
130360573Skris	if (c->cb_fn != NULL && c->cb_event == type) {
130469587Sgreen		debug2("callback start");
130560573Skris		c->cb_fn(c->self, c->cb_arg);
130669587Sgreen		debug2("callback done");
130760573Skris	} else {
130860573Skris		char *service = packet_get_string(NULL);
130960573Skris		debug("channel: %d rcvd request for %s", c->self, service);
131069587Sgreen		debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
131160573Skris		xfree(service);
131260573Skris	}
131360573Skris}
131460573Skris
131560573Skrisvoid
131669587Sgreenchannel_input_window_adjust(int type, int plen, void *ctxt)
131757429Smarkm{
131860573Skris	Channel *c;
131960573Skris	int id, adjust;
132057429Smarkm
132160573Skris	if (!compat20)
132260573Skris		return;
132360573Skris
132457429Smarkm	/* Get the channel number and verify it. */
132560573Skris	id = packet_get_int();
132660573Skris	c = channel_lookup(id);
132757429Smarkm
132860573Skris	if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
132960573Skris		log("Received window adjust for "
133060573Skris		    "non-open channel %d.", id);
133160573Skris		return;
133260573Skris	}
133360573Skris	adjust = packet_get_int();
133460573Skris	packet_done();
133569587Sgreen	debug2("channel %d: rcvd adjust %d", id, adjust);
133660573Skris	c->remote_window += adjust;
133757429Smarkm}
133857429Smarkm
133957429Smarkm/*
134057429Smarkm * Stops listening for channels, and removes any unix domain sockets that we
134157429Smarkm * might have.
134257429Smarkm */
134357429Smarkm
134460573Skrisvoid
134557429Smarkmchannel_stop_listening()
134657429Smarkm{
134757429Smarkm	int i;
134857429Smarkm	for (i = 0; i < channels_alloc; i++) {
134957429Smarkm		switch (channels[i].type) {
135057429Smarkm		case SSH_CHANNEL_AUTH_SOCKET:
135157429Smarkm			close(channels[i].sock);
135257429Smarkm			remove(channels[i].path);
135357429Smarkm			channel_free(i);
135457429Smarkm			break;
135557429Smarkm		case SSH_CHANNEL_PORT_LISTENER:
135657429Smarkm		case SSH_CHANNEL_X11_LISTENER:
135757429Smarkm			close(channels[i].sock);
135857429Smarkm			channel_free(i);
135957429Smarkm			break;
136057429Smarkm		default:
136157429Smarkm			break;
136257429Smarkm		}
136357429Smarkm	}
136457429Smarkm}
136557429Smarkm
136657429Smarkm/*
136760573Skris * Closes the sockets/fds of all channels.  This is used to close extra file
136857429Smarkm * descriptors after a fork.
136957429Smarkm */
137057429Smarkm
137160573Skrisvoid
137257429Smarkmchannel_close_all()
137357429Smarkm{
137457429Smarkm	int i;
137560573Skris	for (i = 0; i < channels_alloc; i++)
137657429Smarkm		if (channels[i].type != SSH_CHANNEL_FREE)
137760573Skris			channel_close_fds(&channels[i]);
137857429Smarkm}
137957429Smarkm
138057429Smarkm/* Returns the maximum file descriptor number used by the channels. */
138157429Smarkm
138260573Skrisint
138357429Smarkmchannel_max_fd()
138457429Smarkm{
138557429Smarkm	return channel_max_fd_value;
138657429Smarkm}
138757429Smarkm
138857429Smarkm/* Returns true if any channel is still open. */
138957429Smarkm
139060573Skrisint
139157429Smarkmchannel_still_open()
139257429Smarkm{
139357429Smarkm	unsigned int i;
139457429Smarkm	for (i = 0; i < channels_alloc; i++)
139557429Smarkm		switch (channels[i].type) {
139657429Smarkm		case SSH_CHANNEL_FREE:
139757429Smarkm		case SSH_CHANNEL_X11_LISTENER:
139857429Smarkm		case SSH_CHANNEL_PORT_LISTENER:
139957429Smarkm		case SSH_CHANNEL_CLOSED:
140057429Smarkm		case SSH_CHANNEL_AUTH_SOCKET:
140157429Smarkm			continue;
140260573Skris		case SSH_CHANNEL_LARVAL:
140360573Skris			if (!compat20)
140460573Skris				fatal("cannot happen: SSH_CHANNEL_LARVAL");
140560573Skris			continue;
140657429Smarkm		case SSH_CHANNEL_OPENING:
140757429Smarkm		case SSH_CHANNEL_OPEN:
140857429Smarkm		case SSH_CHANNEL_X11_OPEN:
140957429Smarkm			return 1;
141057429Smarkm		case SSH_CHANNEL_INPUT_DRAINING:
141157429Smarkm		case SSH_CHANNEL_OUTPUT_DRAINING:
141257429Smarkm			if (!compat13)
141357429Smarkm				fatal("cannot happen: OUT_DRAIN");
141457429Smarkm			return 1;
141557429Smarkm		default:
141657429Smarkm			fatal("channel_still_open: bad channel type %d", channels[i].type);
141757429Smarkm			/* NOTREACHED */
141857429Smarkm		}
141957429Smarkm	return 0;
142057429Smarkm}
142157429Smarkm
142257429Smarkm/*
142357429Smarkm * Returns a message describing the currently open forwarded connections,
142457429Smarkm * suitable for sending to the client.  The message contains crlf pairs for
142557429Smarkm * newlines.
142657429Smarkm */
142757429Smarkm
142857429Smarkmchar *
142957429Smarkmchannel_open_message()
143057429Smarkm{
143157429Smarkm	Buffer buffer;
143257429Smarkm	int i;
143357429Smarkm	char buf[512], *cp;
143457429Smarkm
143557429Smarkm	buffer_init(&buffer);
143657429Smarkm	snprintf(buf, sizeof buf, "The following connections are open:\r\n");
143757429Smarkm	buffer_append(&buffer, buf, strlen(buf));
143857429Smarkm	for (i = 0; i < channels_alloc; i++) {
143957429Smarkm		Channel *c = &channels[i];
144057429Smarkm		switch (c->type) {
144157429Smarkm		case SSH_CHANNEL_FREE:
144257429Smarkm		case SSH_CHANNEL_X11_LISTENER:
144357429Smarkm		case SSH_CHANNEL_PORT_LISTENER:
144457429Smarkm		case SSH_CHANNEL_CLOSED:
144557429Smarkm		case SSH_CHANNEL_AUTH_SOCKET:
144657429Smarkm			continue;
144760573Skris		case SSH_CHANNEL_LARVAL:
144857429Smarkm		case SSH_CHANNEL_OPENING:
144957429Smarkm		case SSH_CHANNEL_OPEN:
145057429Smarkm		case SSH_CHANNEL_X11_OPEN:
145157429Smarkm		case SSH_CHANNEL_INPUT_DRAINING:
145257429Smarkm		case SSH_CHANNEL_OUTPUT_DRAINING:
145360573Skris			snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
145457429Smarkm			    c->self, c->remote_name,
145557429Smarkm			    c->type, c->remote_id,
145657429Smarkm			    c->istate, buffer_len(&c->input),
145760573Skris			    c->ostate, buffer_len(&c->output),
145860573Skris			    c->rfd, c->wfd);
145957429Smarkm			buffer_append(&buffer, buf, strlen(buf));
146057429Smarkm			continue;
146157429Smarkm		default:
146260573Skris			fatal("channel_open_message: bad channel type %d", c->type);
146357429Smarkm			/* NOTREACHED */
146457429Smarkm		}
146557429Smarkm	}
146657429Smarkm	buffer_append(&buffer, "\0", 1);
146757429Smarkm	cp = xstrdup(buffer_ptr(&buffer));
146857429Smarkm	buffer_free(&buffer);
146957429Smarkm	return cp;
147057429Smarkm}
147157429Smarkm
147257429Smarkm/*
147357429Smarkm * Initiate forwarding of connections to local port "port" through the secure
147457429Smarkm * channel to host:port from remote side.
147557429Smarkm */
147657429Smarkm
147760573Skrisvoid
147857429Smarkmchannel_request_local_forwarding(u_short port, const char *host,
147957429Smarkm				 u_short host_port, int gateway_ports)
148057429Smarkm{
148157429Smarkm	int success, ch, sock, on = 1;
148257429Smarkm	struct addrinfo hints, *ai, *aitop;
148357429Smarkm	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
148457429Smarkm	struct linger linger;
148557429Smarkm
148657429Smarkm	if (strlen(host) > sizeof(channels[0].path) - 1)
148757429Smarkm		packet_disconnect("Forward host name too long.");
148857429Smarkm
148957429Smarkm	/*
149057429Smarkm	 * getaddrinfo returns a loopback address if the hostname is
149157429Smarkm	 * set to NULL and hints.ai_flags is not AI_PASSIVE
149257429Smarkm	 */
149357429Smarkm	memset(&hints, 0, sizeof(hints));
149457429Smarkm	hints.ai_family = IPv4or6;
149557429Smarkm	hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
149657429Smarkm	hints.ai_socktype = SOCK_STREAM;
149757429Smarkm	snprintf(strport, sizeof strport, "%d", port);
149857429Smarkm	if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
149957429Smarkm		packet_disconnect("getaddrinfo: fatal error");
150057429Smarkm
150157429Smarkm	success = 0;
150257429Smarkm	for (ai = aitop; ai; ai = ai->ai_next) {
150357429Smarkm		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
150457429Smarkm			continue;
150557429Smarkm		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
150657429Smarkm		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
150757429Smarkm			error("channel_request_local_forwarding: getnameinfo failed");
150857429Smarkm			continue;
150957429Smarkm		}
151057429Smarkm		/* Create a port to listen for the host. */
151157429Smarkm		sock = socket(ai->ai_family, SOCK_STREAM, 0);
151257429Smarkm		if (sock < 0) {
151357429Smarkm			/* this is no error since kernel may not support ipv6 */
151457429Smarkm			verbose("socket: %.100s", strerror(errno));
151557429Smarkm			continue;
151657429Smarkm		}
151757429Smarkm		/*
151857429Smarkm		 * Set socket options.  We would like the socket to disappear
151957429Smarkm		 * as soon as it has been closed for whatever reason.
152057429Smarkm		 */
152157429Smarkm		setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
152257429Smarkm		linger.l_onoff = 1;
152357429Smarkm		linger.l_linger = 5;
152457429Smarkm		setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
152557429Smarkm		debug("Local forwarding listening on %s port %s.", ntop, strport);
152657429Smarkm
152757429Smarkm		/* Bind the socket to the address. */
152857429Smarkm		if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
152957429Smarkm			/* address can be in use ipv6 address is already bound */
153057429Smarkm			verbose("bind: %.100s", strerror(errno));
153157429Smarkm			close(sock);
153257429Smarkm			continue;
153357429Smarkm		}
153457429Smarkm		/* Start listening for connections on the socket. */
153557429Smarkm		if (listen(sock, 5) < 0) {
153657429Smarkm			error("listen: %.100s", strerror(errno));
153757429Smarkm			close(sock);
153857429Smarkm			continue;
153957429Smarkm		}
154057429Smarkm		/* Allocate a channel number for the socket. */
154160573Skris		ch = channel_new(
154260573Skris		    "port listener", SSH_CHANNEL_PORT_LISTENER,
154360573Skris		    sock, sock, -1,
154460573Skris		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
154569587Sgreen		    0, xstrdup("port listener"), 1);
154657429Smarkm		strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
154757429Smarkm		channels[ch].host_port = host_port;
154857429Smarkm		channels[ch].listening_port = port;
154957429Smarkm		success = 1;
155057429Smarkm	}
155157429Smarkm	if (success == 0)
155257429Smarkm		packet_disconnect("cannot listen port: %d", port);
155357429Smarkm	freeaddrinfo(aitop);
155457429Smarkm}
155557429Smarkm
155657429Smarkm/*
155757429Smarkm * Initiate forwarding of connections to port "port" on remote host through
155857429Smarkm * the secure channel to host:port from local side.
155957429Smarkm */
156057429Smarkm
156160573Skrisvoid
156260573Skrischannel_request_remote_forwarding(u_short listen_port, const char *host_to_connect,
156360573Skris				  u_short port_to_connect)
156457429Smarkm{
156557429Smarkm	int payload_len;
156657429Smarkm	/* Record locally that connection to this host/port is permitted. */
156757429Smarkm	if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
156857429Smarkm		fatal("channel_request_remote_forwarding: too many forwards");
156957429Smarkm
157060573Skris	permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
157160573Skris	permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
157260573Skris	permitted_opens[num_permitted_opens].listen_port = listen_port;
157357429Smarkm	num_permitted_opens++;
157457429Smarkm
157557429Smarkm	/* Send the forward request to the remote side. */
157660573Skris	if (compat20) {
157760573Skris		const char *address_to_bind = "0.0.0.0";
157860573Skris		packet_start(SSH2_MSG_GLOBAL_REQUEST);
157960573Skris		packet_put_cstring("tcpip-forward");
158060573Skris		packet_put_char(0);			/* boolean: want reply */
158160573Skris		packet_put_cstring(address_to_bind);
158260573Skris		packet_put_int(listen_port);
158360573Skris	} else {
158460573Skris		packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
158560573Skris		packet_put_int(listen_port);
158660573Skris		packet_put_cstring(host_to_connect);
158760573Skris		packet_put_int(port_to_connect);
158860573Skris		packet_send();
158960573Skris		packet_write_wait();
159060573Skris		/*
159160573Skris		 * Wait for response from the remote side.  It will send a disconnect
159260573Skris		 * message on failure, and we will never see it here.
159360573Skris		 */
159460573Skris		packet_read_expect(&payload_len, SSH_SMSG_SUCCESS);
159560573Skris	}
159657429Smarkm}
159757429Smarkm
159857429Smarkm/*
159957429Smarkm * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
160057429Smarkm * listening for the port, and sends back a success reply (or disconnect
160157429Smarkm * message if there was an error).  This never returns if there was an error.
160257429Smarkm */
160357429Smarkm
160460573Skrisvoid
160560573Skrischannel_input_port_forward_request(int is_root, int gateway_ports)
160657429Smarkm{
160757429Smarkm	u_short port, host_port;
160857429Smarkm	char *hostname;
160957429Smarkm
161057429Smarkm	/* Get arguments from the packet. */
161157429Smarkm	port = packet_get_int();
161257429Smarkm	hostname = packet_get_string(NULL);
161357429Smarkm	host_port = packet_get_int();
161457429Smarkm
161557429Smarkm	/*
161657429Smarkm	 * Check that an unprivileged user is not trying to forward a
161757429Smarkm	 * privileged port.
161857429Smarkm	 */
161957429Smarkm	if (port < IPPORT_RESERVED && !is_root)
162057429Smarkm		packet_disconnect("Requested forwarding of port %d but user is not root.",
162157429Smarkm				  port);
162257429Smarkm	/*
162357429Smarkm	 * Initiate forwarding,
162457429Smarkm	 */
162560573Skris	channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
162657429Smarkm
162757429Smarkm	/* Free the argument string. */
162857429Smarkm	xfree(hostname);
162957429Smarkm}
163057429Smarkm
163160573Skris/* XXX move to aux.c */
163260573Skrisint
163360573Skrischannel_connect_to(const char *host, u_short host_port)
163460573Skris{
163560573Skris	struct addrinfo hints, *ai, *aitop;
163660573Skris	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
163760573Skris	int gaierr;
163860573Skris	int sock = -1;
163960573Skris
164060573Skris	memset(&hints, 0, sizeof(hints));
164160573Skris	hints.ai_family = IPv4or6;
164260573Skris	hints.ai_socktype = SOCK_STREAM;
164360573Skris	snprintf(strport, sizeof strport, "%d", host_port);
164460573Skris	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
164560573Skris		error("%.100s: unknown host (%s)", host, gai_strerror(gaierr));
164660573Skris		return -1;
164760573Skris	}
164860573Skris	for (ai = aitop; ai; ai = ai->ai_next) {
164960573Skris		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
165060573Skris			continue;
165160573Skris		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
165260573Skris		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
165360573Skris			error("channel_connect_to: getnameinfo failed");
165460573Skris			continue;
165560573Skris		}
165660573Skris		/* Create the socket. */
165760573Skris		sock = socket(ai->ai_family, SOCK_STREAM, 0);
165860573Skris		if (sock < 0) {
165960573Skris			error("socket: %.100s", strerror(errno));
166060573Skris			continue;
166160573Skris		}
166260573Skris		/* Connect to the host/port. */
166360573Skris		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
166460573Skris			error("connect %.100s port %s: %.100s", ntop, strport,
166560573Skris			    strerror(errno));
166660573Skris			close(sock);
166760573Skris			continue;	/* fail -- try next */
166860573Skris		}
166960573Skris		break; /* success */
167060573Skris
167160573Skris	}
167260573Skris	freeaddrinfo(aitop);
167360573Skris	if (!ai) {
167460573Skris		error("connect %.100s port %d: failed.", host, host_port);
167560573Skris		return -1;
167660573Skris	}
167760573Skris	/* success */
167860573Skris	return sock;
167960573Skris}
168057429Smarkm/*
168157429Smarkm * This is called after receiving PORT_OPEN message.  This attempts to
168257429Smarkm * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
168357429Smarkm * or CHANNEL_OPEN_FAILURE.
168457429Smarkm */
168557429Smarkm
168660573Skrisvoid
168769587Sgreenchannel_input_port_open(int type, int plen, void *ctxt)
168857429Smarkm{
168957429Smarkm	u_short host_port;
169057429Smarkm	char *host, *originator_string;
169160573Skris	int remote_channel, sock = -1, newch, i, denied;
169258582Skris	unsigned int host_len, originator_len;
169357429Smarkm
169457429Smarkm	/* Get remote channel number. */
169557429Smarkm	remote_channel = packet_get_int();
169657429Smarkm
169757429Smarkm	/* Get host name to connect to. */
169857429Smarkm	host = packet_get_string(&host_len);
169957429Smarkm
170057429Smarkm	/* Get port to connect to. */
170157429Smarkm	host_port = packet_get_int();
170257429Smarkm
170357429Smarkm	/* Get remote originator name. */
170457429Smarkm	if (have_hostname_in_open) {
170557429Smarkm		originator_string = packet_get_string(&originator_len);
170657429Smarkm		originator_len += 4;	/* size of packet_int */
170757429Smarkm	} else {
170857429Smarkm		originator_string = xstrdup("unknown (remote did not supply name)");
170957429Smarkm		originator_len = 0;	/* no originator supplied */
171057429Smarkm	}
171157429Smarkm
171260573Skris	packet_integrity_check(plen,
171360573Skris	    4 + 4 + host_len + 4 + originator_len, SSH_MSG_PORT_OPEN);
171457429Smarkm
171557429Smarkm	/* Check if opening that port is permitted. */
171660573Skris	denied = 0;
171757429Smarkm	if (!all_opens_permitted) {
171857429Smarkm		/* Go trough all permitted ports. */
171957429Smarkm		for (i = 0; i < num_permitted_opens; i++)
172060573Skris			if (permitted_opens[i].port_to_connect == host_port &&
172160573Skris			    strcmp(permitted_opens[i].host_to_connect, host) == 0)
172257429Smarkm				break;
172357429Smarkm
172457429Smarkm		/* Check if we found the requested port among those permitted. */
172557429Smarkm		if (i >= num_permitted_opens) {
172657429Smarkm			/* The port is not permitted. */
172757429Smarkm			log("Received request to connect to %.100s:%d, but the request was denied.",
172857429Smarkm			    host, host_port);
172960573Skris			denied = 1;
173057429Smarkm		}
173157429Smarkm	}
173260573Skris	sock = denied ? -1 : channel_connect_to(host, host_port);
173360573Skris	if (sock > 0) {
173460573Skris		/* Allocate a channel for this connection. */
173560573Skris		newch = channel_allocate(SSH_CHANNEL_OPEN, sock, originator_string);
173660573Skris		channels[newch].remote_id = remote_channel;
173757429Smarkm
173860573Skris		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
173960573Skris		packet_put_int(remote_channel);
174060573Skris		packet_put_int(newch);
174160573Skris		packet_send();
174260573Skris	} else {
174360573Skris		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
174460573Skris		packet_put_int(remote_channel);
174560573Skris		packet_send();
174657429Smarkm	}
174757429Smarkm	xfree(host);
174857429Smarkm}
174957429Smarkm
175057429Smarkm/*
175157429Smarkm * Creates an internet domain socket for listening for X11 connections.
175257429Smarkm * Returns a suitable value for the DISPLAY variable, or NULL if an error
175357429Smarkm * occurs.
175457429Smarkm */
175557429Smarkm
175657429Smarkm#define	NUM_SOCKS	10
175757429Smarkm
175857429Smarkmchar *
175957429Smarkmx11_create_display_inet(int screen_number, int x11_display_offset)
176057429Smarkm{
176157429Smarkm	int display_number, sock;
176257429Smarkm	u_short port;
176357429Smarkm	struct addrinfo hints, *ai, *aitop;
176457429Smarkm	char strport[NI_MAXSERV];
176557429Smarkm	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
176657429Smarkm	char display[512];
176757429Smarkm	char hostname[MAXHOSTNAMELEN];
176857429Smarkm
176957429Smarkm	for (display_number = x11_display_offset;
177057429Smarkm	     display_number < MAX_DISPLAYS;
177157429Smarkm	     display_number++) {
177257429Smarkm		port = 6000 + display_number;
177357429Smarkm		memset(&hints, 0, sizeof(hints));
177457429Smarkm		hints.ai_family = IPv4or6;
177557429Smarkm		hints.ai_flags = AI_PASSIVE;		/* XXX loopback only ? */
177657429Smarkm		hints.ai_socktype = SOCK_STREAM;
177757429Smarkm		snprintf(strport, sizeof strport, "%d", port);
177857429Smarkm		if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
177957429Smarkm			error("getaddrinfo: %.100s", gai_strerror(gaierr));
178057429Smarkm			return NULL;
178157429Smarkm		}
178257429Smarkm		for (ai = aitop; ai; ai = ai->ai_next) {
178357429Smarkm			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
178457429Smarkm				continue;
178557429Smarkm			sock = socket(ai->ai_family, SOCK_STREAM, 0);
178657429Smarkm			if (sock < 0) {
178757429Smarkm				error("socket: %.100s", strerror(errno));
178857429Smarkm				return NULL;
178957429Smarkm			}
179057429Smarkm			if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
179157429Smarkm				debug("bind port %d: %.100s", port, strerror(errno));
179257429Smarkm				shutdown(sock, SHUT_RDWR);
179357429Smarkm				close(sock);
179457429Smarkm				for (n = 0; n < num_socks; n++) {
179557429Smarkm					shutdown(socks[n], SHUT_RDWR);
179657429Smarkm					close(socks[n]);
179757429Smarkm				}
179857429Smarkm				num_socks = 0;
179957429Smarkm				break;
180057429Smarkm			}
180157429Smarkm			socks[num_socks++] = sock;
180257429Smarkm			if (num_socks == NUM_SOCKS)
180357429Smarkm				break;
180457429Smarkm		}
180557429Smarkm		if (num_socks > 0)
180657429Smarkm			break;
180757429Smarkm	}
180857429Smarkm	if (display_number >= MAX_DISPLAYS) {
180957429Smarkm		error("Failed to allocate internet-domain X11 display socket.");
181057429Smarkm		return NULL;
181157429Smarkm	}
181257429Smarkm	/* Start listening for connections on the socket. */
181357429Smarkm	for (n = 0; n < num_socks; n++) {
181457429Smarkm		sock = socks[n];
181557429Smarkm		if (listen(sock, 5) < 0) {
181657429Smarkm			error("listen: %.100s", strerror(errno));
181757429Smarkm			shutdown(sock, SHUT_RDWR);
181857429Smarkm			close(sock);
181957429Smarkm			return NULL;
182057429Smarkm		}
182157429Smarkm	}
182257429Smarkm
182357429Smarkm	/* Set up a suitable value for the DISPLAY variable. */
182457429Smarkm	if (gethostname(hostname, sizeof(hostname)) < 0)
182557429Smarkm		fatal("gethostname: %.100s", strerror(errno));
182657429Smarkm	snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
182757429Smarkm		 display_number, screen_number);
182857429Smarkm
182957429Smarkm	/* Allocate a channel for each socket. */
183057429Smarkm	for (n = 0; n < num_socks; n++) {
183157429Smarkm		sock = socks[n];
183260573Skris		(void) channel_new("x11 listener",
183360573Skris		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
183460573Skris		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
183569587Sgreen		    0, xstrdup("X11 inet listener"), 1);
183657429Smarkm	}
183757429Smarkm
183857429Smarkm	/* Return a suitable value for the DISPLAY environment variable. */
183957429Smarkm	return xstrdup(display);
184057429Smarkm}
184157429Smarkm
184257429Smarkm#ifndef X_UNIX_PATH
184357429Smarkm#define X_UNIX_PATH "/tmp/.X11-unix/X"
184457429Smarkm#endif
184557429Smarkm
184657429Smarkmstatic
184757429Smarkmint
184857429Smarkmconnect_local_xsocket(unsigned int dnr)
184957429Smarkm{
185057429Smarkm	static const char *const x_sockets[] = {
185157429Smarkm		X_UNIX_PATH "%u",
185257429Smarkm		"/var/X/.X11-unix/X" "%u",
185357429Smarkm		"/usr/spool/sockets/X11/" "%u",
185457429Smarkm		NULL
185557429Smarkm	};
185657429Smarkm	int sock;
185757429Smarkm	struct sockaddr_un addr;
185857429Smarkm	const char *const * path;
185957429Smarkm
186057429Smarkm	for (path = x_sockets; *path; ++path) {
186157429Smarkm		sock = socket(AF_UNIX, SOCK_STREAM, 0);
186257429Smarkm		if (sock < 0)
186357429Smarkm			error("socket: %.100s", strerror(errno));
186457429Smarkm		memset(&addr, 0, sizeof(addr));
186557429Smarkm		addr.sun_family = AF_UNIX;
186657429Smarkm		snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
186757429Smarkm		if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
186857429Smarkm			return sock;
186957429Smarkm		close(sock);
187057429Smarkm	}
187157429Smarkm	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
187257429Smarkm	return -1;
187357429Smarkm}
187457429Smarkm
187560573Skrisint
187660573Skrisx11_connect_display(void)
187757429Smarkm{
187860573Skris	int display_number, sock = 0;
187957429Smarkm	const char *display;
188060573Skris	char buf[1024], *cp;
188157429Smarkm	struct addrinfo hints, *ai, *aitop;
188257429Smarkm	char strport[NI_MAXSERV];
188357429Smarkm	int gaierr;
188457429Smarkm
188557429Smarkm	/* Try to open a socket for the local X server. */
188657429Smarkm	display = getenv("DISPLAY");
188757429Smarkm	if (!display) {
188857429Smarkm		error("DISPLAY not set.");
188960573Skris		return -1;
189057429Smarkm	}
189157429Smarkm	/*
189257429Smarkm	 * Now we decode the value of the DISPLAY variable and make a
189357429Smarkm	 * connection to the real X server.
189457429Smarkm	 */
189557429Smarkm
189657429Smarkm	/*
189757429Smarkm	 * Check if it is a unix domain socket.  Unix domain displays are in
189857429Smarkm	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
189957429Smarkm	 */
190057429Smarkm	if (strncmp(display, "unix:", 5) == 0 ||
190157429Smarkm	    display[0] == ':') {
190257429Smarkm		/* Connect to the unix domain socket. */
190357429Smarkm		if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
190457429Smarkm			error("Could not parse display number from DISPLAY: %.100s",
190557429Smarkm			      display);
190660573Skris			return -1;
190757429Smarkm		}
190857429Smarkm		/* Create a socket. */
190957429Smarkm		sock = connect_local_xsocket(display_number);
191057429Smarkm		if (sock < 0)
191160573Skris			return -1;
191257429Smarkm
191357429Smarkm		/* OK, we now have a connection to the display. */
191460573Skris		return sock;
191557429Smarkm	}
191657429Smarkm	/*
191757429Smarkm	 * Connect to an inet socket.  The DISPLAY value is supposedly
191857429Smarkm	 * hostname:d[.s], where hostname may also be numeric IP address.
191957429Smarkm	 */
192057429Smarkm	strncpy(buf, display, sizeof(buf));
192157429Smarkm	buf[sizeof(buf) - 1] = 0;
192257429Smarkm	cp = strchr(buf, ':');
192357429Smarkm	if (!cp) {
192457429Smarkm		error("Could not find ':' in DISPLAY: %.100s", display);
192560573Skris		return -1;
192657429Smarkm	}
192757429Smarkm	*cp = 0;
192857429Smarkm	/* buf now contains the host name.  But first we parse the display number. */
192957429Smarkm	if (sscanf(cp + 1, "%d", &display_number) != 1) {
193057429Smarkm		error("Could not parse display number from DISPLAY: %.100s",
193157429Smarkm		      display);
193260573Skris		return -1;
193357429Smarkm	}
193457429Smarkm
193557429Smarkm	/* Look up the host address */
193657429Smarkm	memset(&hints, 0, sizeof(hints));
193757429Smarkm	hints.ai_family = IPv4or6;
193857429Smarkm	hints.ai_socktype = SOCK_STREAM;
193957429Smarkm	snprintf(strport, sizeof strport, "%d", 6000 + display_number);
194057429Smarkm	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
194157429Smarkm		error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
194260573Skris		return -1;
194357429Smarkm	}
194457429Smarkm	for (ai = aitop; ai; ai = ai->ai_next) {
194557429Smarkm		/* Create a socket. */
194657429Smarkm		sock = socket(ai->ai_family, SOCK_STREAM, 0);
194757429Smarkm		if (sock < 0) {
194857429Smarkm			debug("socket: %.100s", strerror(errno));
194960573Skris			continue;
195060573Skris		}
195160573Skris		/* Connect it to the display. */
195260573Skris		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
195360573Skris			debug("connect %.100s port %d: %.100s", buf,
195460573Skris			    6000 + display_number, strerror(errno));
195560573Skris			close(sock);
195660573Skris			continue;
195760573Skris		}
195860573Skris		/* Success */
195960573Skris		break;
196057429Smarkm	}
196157429Smarkm	freeaddrinfo(aitop);
196257429Smarkm	if (!ai) {
196360573Skris		error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
196457429Smarkm		    strerror(errno));
196560573Skris		return -1;
196657429Smarkm	}
196760573Skris	return sock;
196860573Skris}
196957429Smarkm
197060573Skris/*
197160573Skris * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
197260573Skris * the remote channel number.  We should do whatever we want, and respond
197360573Skris * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
197460573Skris */
197557429Smarkm
197660573Skrisvoid
197769587Sgreenx11_input_open(int type, int plen, void *ctxt)
197860573Skris{
197960573Skris	int remote_channel, sock = 0, newch;
198060573Skris	char *remote_host;
198160573Skris	unsigned int remote_len;
198257429Smarkm
198360573Skris	/* Get remote channel number. */
198460573Skris	remote_channel = packet_get_int();
198557429Smarkm
198660573Skris	/* Get remote originator name. */
198760573Skris	if (have_hostname_in_open) {
198860573Skris		remote_host = packet_get_string(&remote_len);
198960573Skris		remote_len += 4;
199060573Skris	} else {
199160573Skris		remote_host = xstrdup("unknown (remote did not supply name)");
199260573Skris		remote_len = 0;
199360573Skris	}
199460573Skris
199560573Skris	debug("Received X11 open request.");
199660573Skris	packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
199760573Skris
199860573Skris	/* Obtain a connection to the real X display. */
199960573Skris	sock = x11_connect_display();
200060573Skris	if (sock == -1) {
200160573Skris		/* Send refusal to the remote host. */
200260573Skris		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
200360573Skris		packet_put_int(remote_channel);
200460573Skris		packet_send();
200560573Skris	} else {
200660573Skris		/* Allocate a channel for this connection. */
200760573Skris		newch = channel_allocate(
200860573Skris		     (x11_saved_proto == NULL) ?
200960573Skris		     SSH_CHANNEL_OPEN : SSH_CHANNEL_X11_OPEN,
201060573Skris		     sock, remote_host);
201160573Skris		channels[newch].remote_id = remote_channel;
201260573Skris
201360573Skris		/* Send a confirmation to the remote host. */
201460573Skris		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
201560573Skris		packet_put_int(remote_channel);
201660573Skris		packet_put_int(newch);
201760573Skris		packet_send();
201860573Skris	}
201957429Smarkm}
202057429Smarkm
202169587Sgreen/* dummy protocol handler that denies SSH-1 requests (agent/x11) */
202269587Sgreenvoid
202369587Sgreendeny_input_open(int type, int plen, void *ctxt)
202469587Sgreen{
202569587Sgreen	int rchan = packet_get_int();
202669587Sgreen	switch(type){
202769587Sgreen	case SSH_SMSG_AGENT_OPEN:
202869587Sgreen		error("Warning: ssh server tried agent forwarding.");
202969587Sgreen		break;
203069587Sgreen	case SSH_SMSG_X11_OPEN:
203169587Sgreen		error("Warning: ssh server tried X11 forwarding.");
203269587Sgreen		break;
203369587Sgreen	default:
203469587Sgreen		error("deny_input_open: type %d plen %d", type, plen);
203569587Sgreen		break;
203669587Sgreen	}
203769587Sgreen	error("Warning: this is probably a break in attempt by a malicious server.");
203869587Sgreen	packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
203969587Sgreen	packet_put_int(rchan);
204069587Sgreen	packet_send();
204169587Sgreen}
204269587Sgreen
204357429Smarkm/*
204457429Smarkm * Requests forwarding of X11 connections, generates fake authentication
204557429Smarkm * data, and enables authentication spoofing.
204657429Smarkm */
204757429Smarkm
204860573Skrisvoid
204960573Skrisx11_request_forwarding_with_spoofing(int client_session_id,
205060573Skris    const char *proto, const char *data)
205157429Smarkm{
205257429Smarkm	unsigned int data_len = (unsigned int) strlen(data) / 2;
205357429Smarkm	unsigned int i, value;
205457429Smarkm	char *new_data;
205557429Smarkm	int screen_number;
205657429Smarkm	const char *cp;
205757429Smarkm	u_int32_t rand = 0;
205857429Smarkm
205957429Smarkm	cp = getenv("DISPLAY");
206057429Smarkm	if (cp)
206157429Smarkm		cp = strchr(cp, ':');
206257429Smarkm	if (cp)
206357429Smarkm		cp = strchr(cp, '.');
206457429Smarkm	if (cp)
206557429Smarkm		screen_number = atoi(cp + 1);
206657429Smarkm	else
206757429Smarkm		screen_number = 0;
206857429Smarkm
206957429Smarkm	/* Save protocol name. */
207057429Smarkm	x11_saved_proto = xstrdup(proto);
207157429Smarkm
207257429Smarkm	/*
207357429Smarkm	 * Extract real authentication data and generate fake data of the
207457429Smarkm	 * same length.
207557429Smarkm	 */
207657429Smarkm	x11_saved_data = xmalloc(data_len);
207757429Smarkm	x11_fake_data = xmalloc(data_len);
207857429Smarkm	for (i = 0; i < data_len; i++) {
207957429Smarkm		if (sscanf(data + 2 * i, "%2x", &value) != 1)
208057429Smarkm			fatal("x11_request_forwarding: bad authentication data: %.100s", data);
208157429Smarkm		if (i % 4 == 0)
208257429Smarkm			rand = arc4random();
208357429Smarkm		x11_saved_data[i] = value;
208457429Smarkm		x11_fake_data[i] = rand & 0xff;
208557429Smarkm		rand >>= 8;
208657429Smarkm	}
208757429Smarkm	x11_saved_data_len = data_len;
208857429Smarkm	x11_fake_data_len = data_len;
208957429Smarkm
209057429Smarkm	/* Convert the fake data into hex. */
209157429Smarkm	new_data = xmalloc(2 * data_len + 1);
209257429Smarkm	for (i = 0; i < data_len; i++)
209357429Smarkm		sprintf(new_data + 2 * i, "%02x", (unsigned char) x11_fake_data[i]);
209457429Smarkm
209557429Smarkm	/* Send the request packet. */
209660573Skris	if (compat20) {
209760573Skris		channel_request_start(client_session_id, "x11-req", 0);
209860573Skris		packet_put_char(0);	/* XXX bool single connection */
209960573Skris	} else {
210060573Skris		packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
210160573Skris	}
210260573Skris	packet_put_cstring(proto);
210360573Skris	packet_put_cstring(new_data);
210457429Smarkm	packet_put_int(screen_number);
210557429Smarkm	packet_send();
210657429Smarkm	packet_write_wait();
210757429Smarkm	xfree(new_data);
210857429Smarkm}
210957429Smarkm
211057429Smarkm/* Sends a message to the server to request authentication fd forwarding. */
211157429Smarkm
211260573Skrisvoid
211357429Smarkmauth_request_forwarding()
211457429Smarkm{
211557429Smarkm	packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
211657429Smarkm	packet_send();
211757429Smarkm	packet_write_wait();
211857429Smarkm}
211957429Smarkm
212057429Smarkm/*
212157429Smarkm * Returns the name of the forwarded authentication socket.  Returns NULL if
212257429Smarkm * there is no forwarded authentication socket.  The returned value points to
212357429Smarkm * a static buffer.
212457429Smarkm */
212557429Smarkm
212657429Smarkmchar *
212757429Smarkmauth_get_socket_name()
212857429Smarkm{
212957429Smarkm	return channel_forwarded_auth_socket_name;
213057429Smarkm}
213157429Smarkm
213257429Smarkm/* removes the agent forwarding socket */
213357429Smarkm
213460573Skrisvoid
213557429Smarkmcleanup_socket(void)
213657429Smarkm{
213757429Smarkm	remove(channel_forwarded_auth_socket_name);
213857429Smarkm	rmdir(channel_forwarded_auth_socket_dir);
213957429Smarkm}
214057429Smarkm
214157429Smarkm/*
214261199Skris * This is called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
214357429Smarkm * This starts forwarding authentication requests.
214457429Smarkm */
214557429Smarkm
214661199Skrisint
214757429Smarkmauth_input_request_forwarding(struct passwd * pw)
214857429Smarkm{
214957429Smarkm	int sock, newch;
215057429Smarkm	struct sockaddr_un sunaddr;
215157429Smarkm
215257429Smarkm	if (auth_get_socket_name() != NULL)
215357429Smarkm		fatal("Protocol error: authentication forwarding requested twice.");
215457429Smarkm
215557429Smarkm	/* Temporarily drop privileged uid for mkdir/bind. */
215657429Smarkm	temporarily_use_uid(pw->pw_uid);
215757429Smarkm
215857429Smarkm	/* Allocate a buffer for the socket name, and format the name. */
215957429Smarkm	channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
216057429Smarkm	channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
216157429Smarkm	strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
216257429Smarkm
216357429Smarkm	/* Create private directory for socket */
216461199Skris	if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL) {
216561199Skris		packet_send_debug("Agent forwarding disabled: mkdtemp() failed: %.100s",
216661199Skris		    strerror(errno));
216761199Skris		restore_uid();
216861199Skris		xfree(channel_forwarded_auth_socket_name);
216961199Skris		xfree(channel_forwarded_auth_socket_dir);
217061199Skris		channel_forwarded_auth_socket_name = NULL;
217161199Skris		channel_forwarded_auth_socket_dir = NULL;
217261199Skris		return 0;
217361199Skris	}
217457429Smarkm	snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
217557429Smarkm		 channel_forwarded_auth_socket_dir, (int) getpid());
217657429Smarkm
217757429Smarkm	if (atexit(cleanup_socket) < 0) {
217857429Smarkm		int saved = errno;
217957429Smarkm		cleanup_socket();
218057429Smarkm		packet_disconnect("socket: %.100s", strerror(saved));
218157429Smarkm	}
218257429Smarkm	/* Create the socket. */
218357429Smarkm	sock = socket(AF_UNIX, SOCK_STREAM, 0);
218457429Smarkm	if (sock < 0)
218557429Smarkm		packet_disconnect("socket: %.100s", strerror(errno));
218657429Smarkm
218757429Smarkm	/* Bind it to the name. */
218857429Smarkm	memset(&sunaddr, 0, sizeof(sunaddr));
218957429Smarkm	sunaddr.sun_family = AF_UNIX;
219057429Smarkm	strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
219157429Smarkm		sizeof(sunaddr.sun_path));
219257429Smarkm
219357429Smarkm	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
219457429Smarkm		packet_disconnect("bind: %.100s", strerror(errno));
219557429Smarkm
219657429Smarkm	/* Restore the privileged uid. */
219757429Smarkm	restore_uid();
219857429Smarkm
219957429Smarkm	/* Start listening on the socket. */
220057429Smarkm	if (listen(sock, 5) < 0)
220157429Smarkm		packet_disconnect("listen: %.100s", strerror(errno));
220257429Smarkm
220357429Smarkm	/* Allocate a channel for the authentication agent socket. */
220457429Smarkm	newch = channel_allocate(SSH_CHANNEL_AUTH_SOCKET, sock,
220557429Smarkm				 xstrdup("auth socket"));
220657429Smarkm	strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
220757429Smarkm	    sizeof(channels[newch].path));
220861199Skris	return 1;
220957429Smarkm}
221057429Smarkm
221157429Smarkm/* This is called to process an SSH_SMSG_AGENT_OPEN message. */
221257429Smarkm
221360573Skrisvoid
221469587Sgreenauth_input_open_request(int type, int plen, void *ctxt)
221557429Smarkm{
221657429Smarkm	int remch, sock, newch;
221757429Smarkm	char *dummyname;
221857429Smarkm
221960573Skris	packet_integrity_check(plen, 4, type);
222060573Skris
222157429Smarkm	/* Read the remote channel number from the message. */
222257429Smarkm	remch = packet_get_int();
222357429Smarkm
222457429Smarkm	/*
222557429Smarkm	 * Get a connection to the local authentication agent (this may again
222657429Smarkm	 * get forwarded).
222757429Smarkm	 */
222857429Smarkm	sock = ssh_get_authentication_socket();
222957429Smarkm
223057429Smarkm	/*
223157429Smarkm	 * If we could not connect the agent, send an error message back to
223257429Smarkm	 * the server. This should never happen unless the agent dies,
223357429Smarkm	 * because authentication forwarding is only enabled if we have an
223457429Smarkm	 * agent.
223557429Smarkm	 */
223657429Smarkm	if (sock < 0) {
223757429Smarkm		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
223857429Smarkm		packet_put_int(remch);
223957429Smarkm		packet_send();
224057429Smarkm		return;
224157429Smarkm	}
224257429Smarkm	debug("Forwarding authentication connection.");
224357429Smarkm
224457429Smarkm	/*
224557429Smarkm	 * Dummy host name.  This will be freed when the channel is freed; it
224657429Smarkm	 * will still be valid in the packet_put_string below since the
224757429Smarkm	 * channel cannot yet be freed at that point.
224857429Smarkm	 */
224957429Smarkm	dummyname = xstrdup("authentication agent connection");
225057429Smarkm
225157429Smarkm	newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
225257429Smarkm	channels[newch].remote_id = remch;
225357429Smarkm
225457429Smarkm	/* Send a confirmation to the remote host. */
225557429Smarkm	packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
225657429Smarkm	packet_put_int(remch);
225757429Smarkm	packet_put_int(newch);
225857429Smarkm	packet_send();
225957429Smarkm}
226060573Skris
226160573Skrisvoid
226260573Skrischannel_start_open(int id)
226360573Skris{
226460573Skris	Channel *c = channel_lookup(id);
226560573Skris	if (c == NULL) {
226660573Skris		log("channel_open: %d: bad id", id);
226760573Skris		return;
226860573Skris	}
226960573Skris	debug("send channel open %d", id);
227060573Skris	packet_start(SSH2_MSG_CHANNEL_OPEN);
227160573Skris	packet_put_cstring(c->ctype);
227260573Skris	packet_put_int(c->self);
227360573Skris	packet_put_int(c->local_window);
227460573Skris	packet_put_int(c->local_maxpacket);
227560573Skris}
227660573Skrisvoid
227760573Skrischannel_open(int id)
227860573Skris{
227960573Skris	/* XXX REMOVE ME */
228060573Skris	channel_start_open(id);
228160573Skris	packet_send();
228260573Skris}
228360573Skrisvoid
228460573Skrischannel_request(int id, char *service, int wantconfirm)
228560573Skris{
228660573Skris	channel_request_start(id, service, wantconfirm);
228760573Skris	packet_send();
228860573Skris	debug("channel request %d: %s", id, service) ;
228960573Skris}
229060573Skrisvoid
229160573Skrischannel_request_start(int id, char *service, int wantconfirm)
229260573Skris{
229360573Skris	Channel *c = channel_lookup(id);
229460573Skris	if (c == NULL) {
229560573Skris		log("channel_request: %d: bad id", id);
229660573Skris		return;
229760573Skris	}
229860573Skris	packet_start(SSH2_MSG_CHANNEL_REQUEST);
229960573Skris	packet_put_int(c->remote_id);
230060573Skris	packet_put_cstring(service);
230160573Skris	packet_put_char(wantconfirm);
230260573Skris}
230360573Skrisvoid
230460573Skrischannel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
230560573Skris{
230660573Skris	Channel *c = channel_lookup(id);
230760573Skris	if (c == NULL) {
230860573Skris		log("channel_register_callback: %d: bad id", id);
230960573Skris		return;
231060573Skris	}
231160573Skris	c->cb_event = mtype;
231260573Skris	c->cb_fn = fn;
231360573Skris	c->cb_arg = arg;
231460573Skris}
231560573Skrisvoid
231660573Skrischannel_register_cleanup(int id, channel_callback_fn *fn)
231760573Skris{
231860573Skris	Channel *c = channel_lookup(id);
231960573Skris	if (c == NULL) {
232060573Skris		log("channel_register_cleanup: %d: bad id", id);
232160573Skris		return;
232260573Skris	}
232360573Skris	c->dettach_user = fn;
232460573Skris}
232560573Skrisvoid
232660573Skrischannel_cancel_cleanup(int id)
232760573Skris{
232860573Skris	Channel *c = channel_lookup(id);
232960573Skris	if (c == NULL) {
233060573Skris		log("channel_cancel_cleanup: %d: bad id", id);
233160573Skris		return;
233260573Skris	}
233360573Skris	c->dettach_user = NULL;
233460573Skris}
233565668Skrisvoid
233665668Skrischannel_register_filter(int id, channel_filter_fn *fn)
233765668Skris{
233865668Skris	Channel *c = channel_lookup(id);
233965668Skris	if (c == NULL) {
234065668Skris		log("channel_register_filter: %d: bad id", id);
234165668Skris		return;
234265668Skris	}
234365668Skris	c->input_filter = fn;
234465668Skris}
234560573Skris
234660573Skrisvoid
234769587Sgreenchannel_set_fds(int id, int rfd, int wfd, int efd,
234869587Sgreen    int extusage, int nonblock)
234960573Skris{
235060573Skris	Channel *c = channel_lookup(id);
235160573Skris	if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
235260573Skris		fatal("channel_activate for non-larval channel %d.", id);
235369587Sgreen	channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
235460573Skris	c->type = SSH_CHANNEL_OPEN;
235560573Skris	/* XXX window size? */
235665668Skris	c->local_window = c->local_window_max = c->local_maxpacket * 2;
235760573Skris	packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
235860573Skris	packet_put_int(c->remote_id);
235960573Skris	packet_put_int(c->local_window);
236060573Skris	packet_send();
236160573Skris}
2362