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