xref: /freebsd/crypto/openssh/channels.c (revision 1b6c76a2fe091c74f08427e6c870851025a9cf67)
1 /*
2  * Author: Tatu Ylonen <ylo@cs.hut.fi>
3  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4  *                    All rights reserved
5  * This file contains functions for generic socket connection forwarding.
6  * There is also code for initiating connection forwarding for X11 connections,
7  * arbitrary tcp/ip connections, and the authentication agent connection.
8  *
9  * As far as I am concerned, the code I have written for this software
10  * can be used freely for any purpose.  Any derived versions of this
11  * software must be clearly marked as such, and if the derived work is
12  * incompatible with the protocol description in the RFC file, it must be
13  * called by a name other than "ssh" or "Secure Shell".
14  *
15  *
16  * SSH2 support added by Markus Friedl.
17  * Copyright (c) 1999,2000 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 "includes.h"
43 RCSID("$OpenBSD: channels.c,v 1.109 2001/04/17 12:55:03 markus Exp $");
44 RCSID("$FreeBSD$");
45 
46 #include <openssl/rsa.h>
47 #include <openssl/dsa.h>
48 
49 #include "ssh.h"
50 #include "ssh1.h"
51 #include "ssh2.h"
52 #include "packet.h"
53 #include "xmalloc.h"
54 #include "buffer.h"
55 #include "bufaux.h"
56 #include "uidswap.h"
57 #include "log.h"
58 #include "misc.h"
59 #include "channels.h"
60 #include "nchan.h"
61 #include "compat.h"
62 #include "canohost.h"
63 #include "key.h"
64 #include "authfd.h"
65 
66 /* Maximum number of fake X11 displays to try. */
67 #define MAX_DISPLAYS  1000
68 
69 /* Max len of agent socket */
70 #define MAX_SOCKET_NAME 100
71 
72 /*
73  * Pointer to an array containing all allocated channels.  The array is
74  * dynamically extended as needed.
75  */
76 static Channel *channels = NULL;
77 
78 /*
79  * Size of the channel array.  All slots of the array must always be
80  * initialized (at least the type field); unused slots are marked with type
81  * SSH_CHANNEL_FREE.
82  */
83 static int channels_alloc = 0;
84 
85 /*
86  * Maximum file descriptor value used in any of the channels.  This is
87  * updated in channel_allocate.
88  */
89 static int channel_max_fd = 0;
90 
91 /* Name and directory of socket for authentication agent forwarding. */
92 static char *channel_forwarded_auth_socket_name = NULL;
93 static char *channel_forwarded_auth_socket_dir = NULL;
94 
95 /* Saved X11 authentication protocol name. */
96 char *x11_saved_proto = NULL;
97 
98 /* Saved X11 authentication data.  This is the real data. */
99 char *x11_saved_data = NULL;
100 u_int x11_saved_data_len = 0;
101 
102 /*
103  * Fake X11 authentication data.  This is what the server will be sending us;
104  * we should replace any occurrences of this by the real data.
105  */
106 char *x11_fake_data = NULL;
107 u_int x11_fake_data_len;
108 
109 /*
110  * Data structure for storing which hosts are permitted for forward requests.
111  * The local sides of any remote forwards are stored in this array to prevent
112  * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
113  * network (which might be behind a firewall).
114  */
115 typedef struct {
116 	char *host_to_connect;		/* Connect to 'host'. */
117 	u_short port_to_connect;	/* Connect to 'port'. */
118 	u_short listen_port;		/* Remote side should listen port number. */
119 } ForwardPermission;
120 
121 /* List of all permitted host/port pairs to connect. */
122 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
123 /* Number of permitted host/port pairs in the array. */
124 static int num_permitted_opens = 0;
125 /*
126  * If this is true, all opens are permitted.  This is the case on the server
127  * on which we have to trust the client anyway, and the user could do
128  * anything after logging in anyway.
129  */
130 static int all_opens_permitted = 0;
131 
132 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
133 static int have_hostname_in_open = 0;
134 
135 /* AF_UNSPEC or AF_INET or AF_INET6 */
136 extern int IPv4or6;
137 
138 void	 port_open_helper(Channel *c, char *rtype);
139 
140 /* Sets specific protocol options. */
141 
142 void
143 channel_set_options(int hostname_in_open)
144 {
145 	have_hostname_in_open = hostname_in_open;
146 }
147 
148 /* lookup channel by id */
149 
150 Channel *
151 channel_lookup(int id)
152 {
153 	Channel *c;
154 	if (id < 0 || id > channels_alloc) {
155 		log("channel_lookup: %d: bad id", id);
156 		return NULL;
157 	}
158 	c = &channels[id];
159 	if (c->type == SSH_CHANNEL_FREE) {
160 		log("channel_lookup: %d: bad id: channel free", id);
161 		return NULL;
162 	}
163 	return c;
164 }
165 
166 /*
167  * Register filedescriptors for a channel, used when allocating a channel or
168  * when the channel consumer/producer is ready, e.g. shell exec'd
169  */
170 
171 void
172 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
173     int extusage, int nonblock)
174 {
175 	/* Update the maximum file descriptor value. */
176 	channel_max_fd = MAX(channel_max_fd, rfd);
177 	channel_max_fd = MAX(channel_max_fd, wfd);
178 	channel_max_fd = MAX(channel_max_fd, efd);
179 
180 	/* XXX set close-on-exec -markus */
181 
182 	c->rfd = rfd;
183 	c->wfd = wfd;
184 	c->sock = (rfd == wfd) ? rfd : -1;
185 	c->efd = efd;
186 	c->extended_usage = extusage;
187 
188 	/* XXX ugly hack: nonblock is only set by the server */
189 	if (nonblock && isatty(c->rfd)) {
190 		debug("channel %d: rfd %d isatty", c->self, c->rfd);
191 		c->isatty = 1;
192 		if (!isatty(c->wfd)) {
193 			error("channel %d: wfd %d is not a tty?",
194 			    c->self, c->wfd);
195 		}
196 	} else {
197 		c->isatty = 0;
198 	}
199 
200 	/* enable nonblocking mode */
201 	if (nonblock) {
202 		if (rfd != -1)
203 			set_nonblock(rfd);
204 		if (wfd != -1)
205 			set_nonblock(wfd);
206 		if (efd != -1)
207 			set_nonblock(efd);
208 	}
209 }
210 
211 /*
212  * Allocate a new channel object and set its type and socket. This will cause
213  * remote_name to be freed.
214  */
215 
216 int
217 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
218     int window, int maxpack, int extusage, char *remote_name, int nonblock)
219 {
220 	int i, found;
221 	Channel *c;
222 
223 	/* Do initial allocation if this is the first call. */
224 	if (channels_alloc == 0) {
225 		chan_init();
226 		channels_alloc = 10;
227 		channels = xmalloc(channels_alloc * sizeof(Channel));
228 		for (i = 0; i < channels_alloc; i++)
229 			channels[i].type = SSH_CHANNEL_FREE;
230 		/*
231 		 * Kludge: arrange a call to channel_stop_listening if we
232 		 * terminate with fatal().
233 		 */
234 		fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
235 	}
236 	/* Try to find a free slot where to put the new channel. */
237 	for (found = -1, i = 0; i < channels_alloc; i++)
238 		if (channels[i].type == SSH_CHANNEL_FREE) {
239 			/* Found a free slot. */
240 			found = i;
241 			break;
242 		}
243 	if (found == -1) {
244 		/* There are no free slots.  Take last+1 slot and expand the array.  */
245 		found = channels_alloc;
246 		channels_alloc += 10;
247 		debug2("channel: expanding %d", channels_alloc);
248 		channels = xrealloc(channels, channels_alloc * sizeof(Channel));
249 		for (i = found; i < channels_alloc; i++)
250 			channels[i].type = SSH_CHANNEL_FREE;
251 	}
252 	/* Initialize and return new channel number. */
253 	c = &channels[found];
254 	buffer_init(&c->input);
255 	buffer_init(&c->output);
256 	buffer_init(&c->extended);
257 	chan_init_iostates(c);
258 	channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
259 	c->self = found;
260 	c->type = type;
261 	c->ctype = ctype;
262 	c->local_window = window;
263 	c->local_window_max = window;
264 	c->local_consumed = 0;
265 	c->local_maxpacket = maxpack;
266 	c->remote_id = -1;
267 	c->remote_name = remote_name;
268 	c->remote_window = 0;
269 	c->remote_maxpacket = 0;
270 	c->cb_fn = NULL;
271 	c->cb_arg = NULL;
272 	c->cb_event = 0;
273 	c->dettach_user = NULL;
274 	c->input_filter = NULL;
275 	debug("channel %d: new [%s]", found, remote_name);
276 	return found;
277 }
278 /* old interface XXX */
279 int
280 channel_allocate(int type, int sock, char *remote_name)
281 {
282 	return channel_new("", type, sock, sock, -1, 0, 0, 0, remote_name, 1);
283 }
284 
285 
286 /* Close all channel fd/socket. */
287 
288 void
289 channel_close_fds(Channel *c)
290 {
291 	if (c->sock != -1) {
292 		close(c->sock);
293 		c->sock = -1;
294 	}
295 	if (c->rfd != -1) {
296 		close(c->rfd);
297 		c->rfd = -1;
298 	}
299 	if (c->wfd != -1) {
300 		close(c->wfd);
301 		c->wfd = -1;
302 	}
303 	if (c->efd != -1) {
304 		close(c->efd);
305 		c->efd = -1;
306 	}
307 }
308 
309 /* Free the channel and close its fd/socket. */
310 
311 void
312 channel_free(int id)
313 {
314 	Channel *c = channel_lookup(id);
315 	char *s = channel_open_message();
316 
317 	if (c == NULL)
318 		packet_disconnect("channel free: bad local channel %d", id);
319 	debug("channel_free: channel %d: status: %s", id, s);
320 	xfree(s);
321 
322 	if (c->dettach_user != NULL) {
323 		debug("channel_free: channel %d: dettaching channel user", id);
324 		c->dettach_user(c->self, NULL);
325 	}
326 	if (c->sock != -1)
327 		shutdown(c->sock, SHUT_RDWR);
328 	channel_close_fds(c);
329 	buffer_free(&c->input);
330 	buffer_free(&c->output);
331 	buffer_free(&c->extended);
332 	c->type = SSH_CHANNEL_FREE;
333 	if (c->remote_name) {
334 		xfree(c->remote_name);
335 		c->remote_name = NULL;
336 	}
337 }
338 
339 /*
340  * 'channel_pre*' are called just before select() to add any bits relevant to
341  * channels in the select bitmasks.
342  */
343 /*
344  * 'channel_post*': perform any appropriate operations for channels which
345  * have events pending.
346  */
347 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
348 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
349 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
350 
351 void
352 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
353 {
354 	FD_SET(c->sock, readset);
355 }
356 
357 void
358 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
359 {
360 	debug3("channel %d: waiting for connection", c->self);
361 	FD_SET(c->sock, writeset);
362 }
363 
364 void
365 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
366 {
367 	if (buffer_len(&c->input) < packet_get_maxsize())
368 		FD_SET(c->sock, readset);
369 	if (buffer_len(&c->output) > 0)
370 		FD_SET(c->sock, writeset);
371 }
372 
373 void
374 channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
375 {
376 	/* test whether sockets are 'alive' for read/write */
377 	if (c->istate == CHAN_INPUT_OPEN)
378 		if (buffer_len(&c->input) < packet_get_maxsize())
379 			FD_SET(c->sock, readset);
380 	if (c->ostate == CHAN_OUTPUT_OPEN ||
381 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
382 		if (buffer_len(&c->output) > 0) {
383 			FD_SET(c->sock, writeset);
384 		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
385 			chan_obuf_empty(c);
386 		}
387 	}
388 }
389 
390 void
391 channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
392 {
393 	if (c->istate == CHAN_INPUT_OPEN &&
394 	    c->remote_window > 0 &&
395 	    buffer_len(&c->input) < c->remote_window)
396 		FD_SET(c->rfd, readset);
397 	if (c->ostate == CHAN_OUTPUT_OPEN ||
398 	    c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
399 		if (buffer_len(&c->output) > 0) {
400 			FD_SET(c->wfd, writeset);
401 		} else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
402 			chan_obuf_empty(c);
403 		}
404 	}
405 	/** XXX check close conditions, too */
406 	if (c->efd != -1) {
407 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
408 		    buffer_len(&c->extended) > 0)
409 			FD_SET(c->efd, writeset);
410 		else if (c->extended_usage == CHAN_EXTENDED_READ &&
411 		    buffer_len(&c->extended) < c->remote_window)
412 			FD_SET(c->efd, readset);
413 	}
414 }
415 
416 void
417 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
418 {
419 	if (buffer_len(&c->input) == 0) {
420 		packet_start(SSH_MSG_CHANNEL_CLOSE);
421 		packet_put_int(c->remote_id);
422 		packet_send();
423 		c->type = SSH_CHANNEL_CLOSED;
424 		debug("channel %d: closing after input drain.", c->self);
425 	}
426 }
427 
428 void
429 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
430 {
431 	if (buffer_len(&c->output) == 0)
432 		channel_free(c->self);
433 	else
434 		FD_SET(c->sock, writeset);
435 }
436 
437 /*
438  * This is a special state for X11 authentication spoofing.  An opened X11
439  * connection (when authentication spoofing is being done) remains in this
440  * state until the first packet has been completely read.  The authentication
441  * data in that packet is then substituted by the real data if it matches the
442  * fake data, and the channel is put into normal mode.
443  * XXX All this happens at the client side.
444  */
445 int
446 x11_open_helper(Channel *c)
447 {
448 	u_char *ucp;
449 	u_int proto_len, data_len;
450 
451 	/* Check if the fixed size part of the packet is in buffer. */
452 	if (buffer_len(&c->output) < 12)
453 		return 0;
454 
455 	/* Parse the lengths of variable-length fields. */
456 	ucp = (u_char *) buffer_ptr(&c->output);
457 	if (ucp[0] == 0x42) {	/* Byte order MSB first. */
458 		proto_len = 256 * ucp[6] + ucp[7];
459 		data_len = 256 * ucp[8] + ucp[9];
460 	} else if (ucp[0] == 0x6c) {	/* Byte order LSB first. */
461 		proto_len = ucp[6] + 256 * ucp[7];
462 		data_len = ucp[8] + 256 * ucp[9];
463 	} else {
464 		debug("Initial X11 packet contains bad byte order byte: 0x%x",
465 		      ucp[0]);
466 		return -1;
467 	}
468 
469 	/* Check if the whole packet is in buffer. */
470 	if (buffer_len(&c->output) <
471 	    12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
472 		return 0;
473 
474 	/* Check if authentication protocol matches. */
475 	if (proto_len != strlen(x11_saved_proto) ||
476 	    memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
477 		debug("X11 connection uses different authentication protocol.");
478 		return -1;
479 	}
480 	/* Check if authentication data matches our fake data. */
481 	if (data_len != x11_fake_data_len ||
482 	    memcmp(ucp + 12 + ((proto_len + 3) & ~3),
483 		x11_fake_data, x11_fake_data_len) != 0) {
484 		debug("X11 auth data does not match fake data.");
485 		return -1;
486 	}
487 	/* Check fake data length */
488 	if (x11_fake_data_len != x11_saved_data_len) {
489 		error("X11 fake_data_len %d != saved_data_len %d",
490 		    x11_fake_data_len, x11_saved_data_len);
491 		return -1;
492 	}
493 	/*
494 	 * Received authentication protocol and data match
495 	 * our fake data. Substitute the fake data with real
496 	 * data.
497 	 */
498 	memcpy(ucp + 12 + ((proto_len + 3) & ~3),
499 	    x11_saved_data, x11_saved_data_len);
500 	return 1;
501 }
502 
503 void
504 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
505 {
506 	int ret = x11_open_helper(c);
507 	if (ret == 1) {
508 		/* Start normal processing for the channel. */
509 		c->type = SSH_CHANNEL_OPEN;
510 		channel_pre_open_13(c, readset, writeset);
511 	} else if (ret == -1) {
512 		/*
513 		 * We have received an X11 connection that has bad
514 		 * authentication information.
515 		 */
516 		log("X11 connection rejected because of wrong authentication.");
517 		buffer_clear(&c->input);
518 		buffer_clear(&c->output);
519 		close(c->sock);
520 		c->sock = -1;
521 		c->type = SSH_CHANNEL_CLOSED;
522 		packet_start(SSH_MSG_CHANNEL_CLOSE);
523 		packet_put_int(c->remote_id);
524 		packet_send();
525 	}
526 }
527 
528 void
529 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
530 {
531 	int ret = x11_open_helper(c);
532 	if (ret == 1) {
533 		c->type = SSH_CHANNEL_OPEN;
534 		if (compat20)
535 			channel_pre_open_20(c, readset, writeset);
536 		else
537 			channel_pre_open_15(c, readset, writeset);
538 	} else if (ret == -1) {
539 		debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
540 		chan_read_failed(c);	/** force close? */
541 		chan_write_failed(c);
542 		debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
543 	}
544 }
545 
546 /* try to decode a socks4 header */
547 int
548 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
549 {
550 	u_char *p, *host;
551 	int len, have, i, found;
552 	char username[256];
553 	struct {
554 		u_int8_t version;
555 		u_int8_t command;
556 		u_int16_t dest_port;
557 		struct in_addr dest_addr;
558 	} s4_req, s4_rsp;
559 
560 	debug2("channel %d: decode socks4", c->self);
561 
562 	have = buffer_len(&c->input);
563 	len = sizeof(s4_req);
564 	if (have < len)
565 		return 0;
566 	p = buffer_ptr(&c->input);
567 	for (found = 0, i = len; i < have; i++) {
568 		if (p[i] == '\0') {
569 			found = 1;
570 			break;
571 		}
572 		if (i > 1024) {
573 			/* the peer is probably sending garbage */
574 			debug("channel %d: decode socks4: too long",
575 			    c->self);
576 			return -1;
577 		}
578 	}
579 	if (!found)
580 		return 0;
581 	buffer_get(&c->input, (char *)&s4_req.version, 1);
582 	buffer_get(&c->input, (char *)&s4_req.command, 1);
583 	buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
584 	buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
585 	have = buffer_len(&c->input);
586 	p = buffer_ptr(&c->input);
587 	len = strlen(p);
588 	debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
589 	if (len > have)
590 		fatal("channel %d: decode socks4: len %d > have %d",
591 		    c->self, len, have);
592 	strlcpy(username, p, sizeof(username));
593 	buffer_consume(&c->input, len);
594 	buffer_consume(&c->input, 1);		/* trailing '\0' */
595 
596 	host = inet_ntoa(s4_req.dest_addr);
597 	strlcpy(c->path, host, sizeof(c->path));
598 	c->host_port = ntohs(s4_req.dest_port);
599 
600 	debug("channel %d: dynamic request: socks4 host %s port %u command %u",
601 	    c->self, host, c->host_port, s4_req.command);
602 
603 	if (s4_req.command != 1) {
604 		debug("channel %d: cannot handle: socks4 cn %d",
605 		    c->self, s4_req.command);
606 		return -1;
607 	}
608 	s4_rsp.version = 0;			/* vn: 0 for reply */
609 	s4_rsp.command = 90;			/* cd: req granted */
610 	s4_rsp.dest_port = 0;			/* ignored */
611 	s4_rsp.dest_addr.s_addr = INADDR_ANY;	/* ignored */
612 	buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
613 	return 1;
614 }
615 
616 /* dynamic port forwarding */
617 void
618 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
619 {
620 	u_char *p;
621 	int have, ret;
622 
623 	have = buffer_len(&c->input);
624 
625 	debug2("channel %d: pre_dynamic: have %d", c->self, have);
626 	/* buffer_dump(&c->input); */
627 	/* check if the fixed size part of the packet is in buffer. */
628 	if (have < 4) {
629 		/* need more */
630 		FD_SET(c->sock, readset);
631 		return;
632 	}
633 	/* try to guess the protocol */
634 	p = buffer_ptr(&c->input);
635 	switch (p[0]) {
636 	case 0x04:
637 		ret = channel_decode_socks4(c, readset, writeset);
638 		break;
639 	default:
640 		ret = -1;
641 		break;
642 	}
643 	if (ret < 0) {
644 		channel_free(c->self);
645 	} else if (ret == 0) {
646 		debug2("channel %d: pre_dynamic: need more", c->self);
647 		/* need more */
648 		FD_SET(c->sock, readset);
649 	} else {
650 		/* switch to the next state */
651 		c->type = SSH_CHANNEL_OPENING;
652 		port_open_helper(c, "direct-tcpip");
653 	}
654 }
655 
656 /* This is our fake X11 server socket. */
657 void
658 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
659 {
660 	struct sockaddr addr;
661 	int newsock, newch;
662 	socklen_t addrlen;
663 	char buf[16384], *remote_ipaddr;
664 	int remote_port;
665 
666 	if (FD_ISSET(c->sock, readset)) {
667 		debug("X11 connection requested.");
668 		addrlen = sizeof(addr);
669 		newsock = accept(c->sock, &addr, &addrlen);
670 		if (newsock < 0) {
671 			error("accept: %.100s", strerror(errno));
672 			return;
673 		}
674 		remote_ipaddr = get_peer_ipaddr(newsock);
675 		remote_port = get_peer_port(newsock);
676 		snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
677 		    remote_ipaddr, remote_port);
678 
679 		newch = channel_new("x11",
680 		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
681 		    c->local_window_max, c->local_maxpacket,
682 		    0, xstrdup(buf), 1);
683 		if (compat20) {
684 			packet_start(SSH2_MSG_CHANNEL_OPEN);
685 			packet_put_cstring("x11");
686 			packet_put_int(newch);
687 			packet_put_int(c->local_window_max);
688 			packet_put_int(c->local_maxpacket);
689 			/* originator ipaddr and port */
690 			packet_put_cstring(remote_ipaddr);
691 			if (datafellows & SSH_BUG_X11FWD) {
692 				debug("ssh2 x11 bug compat mode");
693 			} else {
694 				packet_put_int(remote_port);
695 			}
696 			packet_send();
697 		} else {
698 			packet_start(SSH_SMSG_X11_OPEN);
699 			packet_put_int(newch);
700 			if (have_hostname_in_open)
701 				packet_put_string(buf, strlen(buf));
702 			packet_send();
703 		}
704 		xfree(remote_ipaddr);
705 	}
706 }
707 
708 void
709 port_open_helper(Channel *c, char *rtype)
710 {
711 	int direct;
712 	char buf[1024];
713 	char *remote_ipaddr = get_peer_ipaddr(c->sock);
714 	u_short remote_port = get_peer_port(c->sock);
715 
716 	direct = (strcmp(rtype, "direct-tcpip") == 0);
717 
718 	snprintf(buf, sizeof buf,
719 	    "%s: listening port %d for %.100s port %d, "
720 	    "connect from %.200s port %d",
721 	    rtype, c->listening_port, c->path, c->host_port,
722 	    remote_ipaddr, remote_port);
723 
724 	xfree(c->remote_name);
725 	c->remote_name = xstrdup(buf);
726 
727 	if (compat20) {
728 		packet_start(SSH2_MSG_CHANNEL_OPEN);
729 		packet_put_cstring(rtype);
730 		packet_put_int(c->self);
731 		packet_put_int(c->local_window_max);
732 		packet_put_int(c->local_maxpacket);
733 		if (direct) {
734 			/* target host, port */
735 			packet_put_cstring(c->path);
736 			packet_put_int(c->host_port);
737 		} else {
738 			/* listen address, port */
739 			packet_put_cstring(c->path);
740 			packet_put_int(c->listening_port);
741 		}
742 		/* originator host and port */
743 		packet_put_cstring(remote_ipaddr);
744 		packet_put_int(remote_port);
745 		packet_send();
746 	} else {
747 		packet_start(SSH_MSG_PORT_OPEN);
748 		packet_put_int(c->self);
749 		packet_put_cstring(c->path);
750 		packet_put_int(c->host_port);
751 		if (have_hostname_in_open)
752 			packet_put_cstring(c->remote_name);
753 		packet_send();
754 	}
755 	xfree(remote_ipaddr);
756 }
757 
758 /*
759  * This socket is listening for connections to a forwarded TCP/IP port.
760  */
761 void
762 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
763 {
764 	Channel *nc;
765 	struct sockaddr addr;
766 	int newsock, newch, nextstate;
767 	socklen_t addrlen;
768 	char *rtype;
769 
770 	if (FD_ISSET(c->sock, readset)) {
771 		debug("Connection to port %d forwarding "
772 		    "to %.100s port %d requested.",
773 		    c->listening_port, c->path, c->host_port);
774 
775 		rtype = (c->type == SSH_CHANNEL_RPORT_LISTENER) ?
776 		    "forwarded-tcpip" : "direct-tcpip";
777 		nextstate = (c->host_port == 0) ? SSH_CHANNEL_DYNAMIC :
778 		    SSH_CHANNEL_OPENING;
779 
780 		addrlen = sizeof(addr);
781 		newsock = accept(c->sock, &addr, &addrlen);
782 		if (newsock < 0) {
783 			error("accept: %.100s", strerror(errno));
784 			return;
785 		}
786 		newch = channel_new(rtype,
787 		    nextstate, newsock, newsock, -1,
788 		    c->local_window_max, c->local_maxpacket,
789 		    0, xstrdup(rtype), 1);
790 
791 		nc = channel_lookup(newch);
792 		if (nc == NULL) {
793 			error("xxx: no new channel:");
794 			return;
795 		}
796 		nc->listening_port = c->listening_port;
797 		nc->host_port = c->host_port;
798 		strlcpy(nc->path, c->path, sizeof(nc->path));
799 
800 		if (nextstate != SSH_CHANNEL_DYNAMIC)
801 			port_open_helper(nc, rtype);
802 	}
803 }
804 
805 /*
806  * This is the authentication agent socket listening for connections from
807  * clients.
808  */
809 void
810 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
811 {
812 	struct sockaddr addr;
813 	int newsock, newch;
814 	socklen_t addrlen;
815 
816 	if (FD_ISSET(c->sock, readset)) {
817 		addrlen = sizeof(addr);
818 		newsock = accept(c->sock, &addr, &addrlen);
819 		if (newsock < 0) {
820 			error("accept from auth socket: %.100s", strerror(errno));
821 			return;
822 		}
823 		newch = channel_new("accepted auth socket",
824 		    SSH_CHANNEL_OPENING, newsock, newsock, -1,
825 		    c->local_window_max, c->local_maxpacket,
826 		    0, xstrdup("accepted auth socket"), 1);
827 		if (compat20) {
828 			packet_start(SSH2_MSG_CHANNEL_OPEN);
829 			packet_put_cstring("auth-agent@openssh.com");
830 			packet_put_int(newch);
831 			packet_put_int(c->local_window_max);
832 			packet_put_int(c->local_maxpacket);
833 		} else {
834 			packet_start(SSH_SMSG_AGENT_OPEN);
835 			packet_put_int(newch);
836 		}
837 		packet_send();
838 	}
839 }
840 
841 void
842 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
843 {
844 	if (FD_ISSET(c->sock, writeset)) {
845 		int err = 0;
846 		int sz = sizeof(err);
847 		c->type = SSH_CHANNEL_OPEN;
848 		if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, (char *)&err, &sz) < 0) {
849 			debug("getsockopt SO_ERROR failed");
850 		} else {
851 			if (err == 0) {
852 				debug("channel %d: connected)", c->self);
853 			} else {
854 				debug("channel %d: not connected: %s",
855 				    c->self, strerror(err));
856 				chan_read_failed(c);
857 				chan_write_failed(c);
858 			}
859 		}
860 	}
861 }
862 
863 int
864 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
865 {
866 	char buf[16*1024];
867 	int len;
868 
869 	if (c->rfd != -1 &&
870 	    FD_ISSET(c->rfd, readset)) {
871 		len = read(c->rfd, buf, sizeof(buf));
872 		if (len < 0 && (errno == EINTR || errno == EAGAIN))
873 			return 1;
874 		if (len <= 0) {
875 			debug("channel %d: read<=0 rfd %d len %d",
876 			    c->self, c->rfd, len);
877 			if (c->type != SSH_CHANNEL_OPEN) {
878 				debug("channel %d: not open", c->self);
879 				channel_free(c->self);
880 				return -1;
881 			} else if (compat13) {
882 				buffer_consume(&c->output, buffer_len(&c->output));
883 				c->type = SSH_CHANNEL_INPUT_DRAINING;
884 				debug("channel %d: status set to input draining.", c->self);
885 			} else {
886 				chan_read_failed(c);
887 			}
888 			return -1;
889 		}
890 		if(c->input_filter != NULL) {
891 			if (c->input_filter(c, buf, len) == -1) {
892 				debug("channel %d: filter stops", c->self);
893 				chan_read_failed(c);
894 			}
895 		} else {
896 			buffer_append(&c->input, buf, len);
897 		}
898 	}
899 	return 1;
900 }
901 int
902 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
903 {
904 	struct termios tio;
905 	int len;
906 
907 	/* Send buffered output data to the socket. */
908 	if (c->wfd != -1 &&
909 	    FD_ISSET(c->wfd, writeset) &&
910 	    buffer_len(&c->output) > 0) {
911 		len = write(c->wfd, buffer_ptr(&c->output),
912 		    buffer_len(&c->output));
913 		if (len < 0 && (errno == EINTR || errno == EAGAIN))
914 			return 1;
915 		if (len <= 0) {
916 			if (c->type != SSH_CHANNEL_OPEN) {
917 				debug("channel %d: not open", c->self);
918 				channel_free(c->self);
919 				return -1;
920 			} else if (compat13) {
921 				buffer_consume(&c->output, buffer_len(&c->output));
922 				debug("channel %d: status set to input draining.", c->self);
923 				c->type = SSH_CHANNEL_INPUT_DRAINING;
924 			} else {
925 				chan_write_failed(c);
926 			}
927 			return -1;
928 		}
929 		if (compat20 && c->isatty) {
930 			if (tcgetattr(c->wfd, &tio) == 0 &&
931 			    !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
932 				/*
933 				 * Simulate echo to reduce the impact of
934 				 * traffic analysis. We need to match the
935 				 * size of a SSH2_MSG_CHANNEL_DATA message
936 				 * (4 byte channel id + data)
937 				 */
938 				packet_send_ignore(4 + len);
939 				packet_send();
940 			}
941 		}
942 		buffer_consume(&c->output, len);
943 		if (compat20 && len > 0) {
944 			c->local_consumed += len;
945 		}
946 	}
947 	return 1;
948 }
949 int
950 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
951 {
952 	char buf[16*1024];
953 	int len;
954 
955 /** XXX handle drain efd, too */
956 	if (c->efd != -1) {
957 		if (c->extended_usage == CHAN_EXTENDED_WRITE &&
958 		    FD_ISSET(c->efd, writeset) &&
959 		    buffer_len(&c->extended) > 0) {
960 			len = write(c->efd, buffer_ptr(&c->extended),
961 			    buffer_len(&c->extended));
962 			debug2("channel %d: written %d to efd %d",
963 			    c->self, len, c->efd);
964 			if (len < 0 && (errno == EINTR || errno == EAGAIN))
965 				return 1;
966 			if (len <= 0) {
967 				debug2("channel %d: closing write-efd %d",
968 				    c->self, c->efd);
969 				close(c->efd);
970 				c->efd = -1;
971 			} else {
972 				buffer_consume(&c->extended, len);
973 				c->local_consumed += len;
974 			}
975 		} else if (c->extended_usage == CHAN_EXTENDED_READ &&
976 		    FD_ISSET(c->efd, readset)) {
977 			len = read(c->efd, buf, sizeof(buf));
978 			debug2("channel %d: read %d from efd %d",
979 			     c->self, len, c->efd);
980 			if (len < 0 && (errno == EINTR || errno == EAGAIN))
981 				return 1;
982 			if (len <= 0) {
983 				debug2("channel %d: closing read-efd %d",
984 				    c->self, c->efd);
985 				close(c->efd);
986 				c->efd = -1;
987 			} else {
988 				buffer_append(&c->extended, buf, len);
989 			}
990 		}
991 	}
992 	return 1;
993 }
994 int
995 channel_check_window(Channel *c)
996 {
997 	if (c->type == SSH_CHANNEL_OPEN &&
998 	    !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
999 	    c->local_window < c->local_window_max/2 &&
1000 	    c->local_consumed > 0) {
1001 		packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1002 		packet_put_int(c->remote_id);
1003 		packet_put_int(c->local_consumed);
1004 		packet_send();
1005 		debug2("channel %d: window %d sent adjust %d",
1006 		    c->self, c->local_window,
1007 		    c->local_consumed);
1008 		c->local_window += c->local_consumed;
1009 		c->local_consumed = 0;
1010 	}
1011 	return 1;
1012 }
1013 
1014 void
1015 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
1016 {
1017 	channel_handle_rfd(c, readset, writeset);
1018 	channel_handle_wfd(c, readset, writeset);
1019 }
1020 
1021 void
1022 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
1023 {
1024 	channel_handle_rfd(c, readset, writeset);
1025 	channel_handle_wfd(c, readset, writeset);
1026 	channel_handle_efd(c, readset, writeset);
1027 
1028 	channel_check_window(c);
1029 }
1030 
1031 void
1032 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1033 {
1034 	int len;
1035 	/* Send buffered output data to the socket. */
1036 	if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1037 		len = write(c->sock, buffer_ptr(&c->output),
1038 			    buffer_len(&c->output));
1039 		if (len <= 0)
1040 			buffer_consume(&c->output, buffer_len(&c->output));
1041 		else
1042 			buffer_consume(&c->output, len);
1043 	}
1044 }
1045 
1046 void
1047 channel_handler_init_20(void)
1048 {
1049 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_20;
1050 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
1051 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1052 	channel_pre[SSH_CHANNEL_RPORT_LISTENER] =	&channel_pre_listener;
1053 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1054 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1055 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1056 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1057 
1058 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_2;
1059 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1060 	channel_post[SSH_CHANNEL_RPORT_LISTENER] =	&channel_post_port_listener;
1061 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1062 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1063 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1064 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open_2;
1065 }
1066 
1067 void
1068 channel_handler_init_13(void)
1069 {
1070 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_13;
1071 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open_13;
1072 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1073 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1074 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1075 	channel_pre[SSH_CHANNEL_INPUT_DRAINING] =	&channel_pre_input_draining;
1076 	channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_pre_output_draining;
1077 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1078 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1079 
1080 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_1;
1081 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1082 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1083 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1084 	channel_post[SSH_CHANNEL_OUTPUT_DRAINING] =	&channel_post_output_drain_13;
1085 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1086 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open_1;
1087 }
1088 
1089 void
1090 channel_handler_init_15(void)
1091 {
1092 	channel_pre[SSH_CHANNEL_OPEN] =			&channel_pre_open_15;
1093 	channel_pre[SSH_CHANNEL_X11_OPEN] =		&channel_pre_x11_open;
1094 	channel_pre[SSH_CHANNEL_X11_LISTENER] =		&channel_pre_listener;
1095 	channel_pre[SSH_CHANNEL_PORT_LISTENER] =	&channel_pre_listener;
1096 	channel_pre[SSH_CHANNEL_AUTH_SOCKET] =		&channel_pre_listener;
1097 	channel_pre[SSH_CHANNEL_CONNECTING] =		&channel_pre_connecting;
1098 	channel_pre[SSH_CHANNEL_DYNAMIC] =		&channel_pre_dynamic;
1099 
1100 	channel_post[SSH_CHANNEL_X11_LISTENER] =	&channel_post_x11_listener;
1101 	channel_post[SSH_CHANNEL_PORT_LISTENER] =	&channel_post_port_listener;
1102 	channel_post[SSH_CHANNEL_AUTH_SOCKET] =		&channel_post_auth_listener;
1103 	channel_post[SSH_CHANNEL_OPEN] =		&channel_post_open_1;
1104 	channel_post[SSH_CHANNEL_CONNECTING] =		&channel_post_connecting;
1105 	channel_post[SSH_CHANNEL_DYNAMIC] =		&channel_post_open_1;
1106 }
1107 
1108 void
1109 channel_handler_init(void)
1110 {
1111 	int i;
1112 	for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1113 		channel_pre[i] = NULL;
1114 		channel_post[i] = NULL;
1115 	}
1116 	if (compat20)
1117 		channel_handler_init_20();
1118 	else if (compat13)
1119 		channel_handler_init_13();
1120 	else
1121 		channel_handler_init_15();
1122 }
1123 
1124 void
1125 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1126 {
1127 	static int did_init = 0;
1128 	int i;
1129 	Channel *c;
1130 
1131 	if (!did_init) {
1132 		channel_handler_init();
1133 		did_init = 1;
1134 	}
1135 	for (i = 0; i < channels_alloc; i++) {
1136 		c = &channels[i];
1137 		if (c->type == SSH_CHANNEL_FREE)
1138 			continue;
1139 		if (ftab[c->type] == NULL)
1140 			continue;
1141 		(*ftab[c->type])(c, readset, writeset);
1142 		if (chan_is_dead(c)) {
1143 			/*
1144 			 * we have to remove the fd's from the select mask
1145 			 * before the channels are free'd and the fd's are
1146 			 * closed
1147 			 */
1148 			if (c->wfd != -1)
1149 				FD_CLR(c->wfd, writeset);
1150 			if (c->rfd != -1)
1151 				FD_CLR(c->rfd, readset);
1152 			if (c->efd != -1) {
1153 				if (c->extended_usage == CHAN_EXTENDED_READ)
1154 					FD_CLR(c->efd, readset);
1155 				if (c->extended_usage == CHAN_EXTENDED_WRITE)
1156 					FD_CLR(c->efd, writeset);
1157 			}
1158 			channel_free(c->self);
1159 		}
1160 	}
1161 }
1162 
1163 void
1164 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1165     int rekeying)
1166 {
1167 	int n;
1168 	u_int sz;
1169 
1170 	n = MAX(*maxfdp, channel_max_fd);
1171 
1172 	sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1173 	if (*readsetp == NULL || n > *maxfdp) {
1174 		if (*readsetp)
1175 			xfree(*readsetp);
1176 		if (*writesetp)
1177 			xfree(*writesetp);
1178 		*readsetp = xmalloc(sz);
1179 		*writesetp = xmalloc(sz);
1180 		*maxfdp = n;
1181 	}
1182 	memset(*readsetp, 0, sz);
1183 	memset(*writesetp, 0, sz);
1184 
1185 	if (!rekeying)
1186 		channel_handler(channel_pre, *readsetp, *writesetp);
1187 }
1188 
1189 void
1190 channel_after_select(fd_set * readset, fd_set * writeset)
1191 {
1192 	channel_handler(channel_post, readset, writeset);
1193 }
1194 
1195 /* If there is data to send to the connection, enqueue some of it now. */
1196 
1197 void
1198 channel_output_poll()
1199 {
1200 	int len, i;
1201 	Channel *c;
1202 
1203 	for (i = 0; i < channels_alloc; i++) {
1204 		c = &channels[i];
1205 
1206 		/* We are only interested in channels that can have buffered incoming data. */
1207 		if (compat13) {
1208 			if (c->type != SSH_CHANNEL_OPEN &&
1209 			    c->type != SSH_CHANNEL_INPUT_DRAINING)
1210 				continue;
1211 		} else {
1212 			if (c->type != SSH_CHANNEL_OPEN)
1213 				continue;
1214 		}
1215 		if (compat20 &&
1216 		    (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1217 			/* XXX is this true? */
1218 			debug2("channel %d: no data after CLOSE", c->self);
1219 			continue;
1220 		}
1221 
1222 		/* Get the amount of buffered data for this channel. */
1223 		if ((c->istate == CHAN_INPUT_OPEN ||
1224 		    c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1225 		    (len = buffer_len(&c->input)) > 0) {
1226 			/* Send some data for the other side over the secure connection. */
1227 			if (compat20) {
1228 				if (len > c->remote_window)
1229 					len = c->remote_window;
1230 				if (len > c->remote_maxpacket)
1231 					len = c->remote_maxpacket;
1232 			} else {
1233 				if (packet_is_interactive()) {
1234 					if (len > 1024)
1235 						len = 512;
1236 				} else {
1237 					/* Keep the packets at reasonable size. */
1238 					if (len > packet_get_maxsize()/2)
1239 						len = packet_get_maxsize()/2;
1240 				}
1241 			}
1242 			if (len > 0) {
1243 				packet_start(compat20 ?
1244 				    SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1245 				packet_put_int(c->remote_id);
1246 				packet_put_string(buffer_ptr(&c->input), len);
1247 				packet_send();
1248 				buffer_consume(&c->input, len);
1249 				c->remote_window -= len;
1250 			}
1251 		} else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1252 			if (compat13)
1253 				fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1254 			/*
1255 			 * input-buffer is empty and read-socket shutdown:
1256 			 * tell peer, that we will not send more data: send IEOF
1257 			 */
1258 			chan_ibuf_empty(c);
1259 		}
1260 		/* Send extended data, i.e. stderr */
1261 		if (compat20 &&
1262 		    c->remote_window > 0 &&
1263 		    (len = buffer_len(&c->extended)) > 0 &&
1264 		    c->extended_usage == CHAN_EXTENDED_READ) {
1265 			debug2("channel %d: rwin %d elen %d euse %d",
1266 			    c->self, c->remote_window, buffer_len(&c->extended),
1267 			    c->extended_usage);
1268 			if (len > c->remote_window)
1269 				len = c->remote_window;
1270 			if (len > c->remote_maxpacket)
1271 				len = c->remote_maxpacket;
1272 			packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1273 			packet_put_int(c->remote_id);
1274 			packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1275 			packet_put_string(buffer_ptr(&c->extended), len);
1276 			packet_send();
1277 			buffer_consume(&c->extended, len);
1278 			c->remote_window -= len;
1279 			debug2("channel %d: sent ext data %d", c->self, len);
1280 		}
1281 	}
1282 }
1283 
1284 /*
1285  * This is called when a packet of type CHANNEL_DATA has just been received.
1286  * The message type has already been consumed, but channel number and data is
1287  * still there.
1288  */
1289 
1290 void
1291 channel_input_data(int type, int plen, void *ctxt)
1292 {
1293 	int id;
1294 	char *data;
1295 	u_int data_len;
1296 	Channel *c;
1297 
1298 	/* Get the channel number and verify it. */
1299 	id = packet_get_int();
1300 	c = channel_lookup(id);
1301 	if (c == NULL)
1302 		packet_disconnect("Received data for nonexistent channel %d.", id);
1303 
1304 	/* Ignore any data for non-open channels (might happen on close) */
1305 	if (c->type != SSH_CHANNEL_OPEN &&
1306 	    c->type != SSH_CHANNEL_X11_OPEN)
1307 		return;
1308 
1309 	/* same for protocol 1.5 if output end is no longer open */
1310 	if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1311 		return;
1312 
1313 	/* Get the data. */
1314 	data = packet_get_string(&data_len);
1315 	packet_done();
1316 
1317 	if (compat20){
1318 		if (data_len > c->local_maxpacket) {
1319 			log("channel %d: rcvd big packet %d, maxpack %d",
1320 			    c->self, data_len, c->local_maxpacket);
1321 		}
1322 		if (data_len > c->local_window) {
1323 			log("channel %d: rcvd too much data %d, win %d",
1324 			    c->self, data_len, c->local_window);
1325 			xfree(data);
1326 			return;
1327 		}
1328 		c->local_window -= data_len;
1329 	}else{
1330 		packet_integrity_check(plen, 4 + 4 + data_len, type);
1331 	}
1332 	buffer_append(&c->output, data, data_len);
1333 	xfree(data);
1334 }
1335 void
1336 channel_input_extended_data(int type, int plen, void *ctxt)
1337 {
1338 	int id;
1339 	int tcode;
1340 	char *data;
1341 	u_int data_len;
1342 	Channel *c;
1343 
1344 	/* Get the channel number and verify it. */
1345 	id = packet_get_int();
1346 	c = channel_lookup(id);
1347 
1348 	if (c == NULL)
1349 		packet_disconnect("Received extended_data for bad channel %d.", id);
1350 	if (c->type != SSH_CHANNEL_OPEN) {
1351 		log("channel %d: ext data for non open", id);
1352 		return;
1353 	}
1354 	tcode = packet_get_int();
1355 	if (c->efd == -1 ||
1356 	    c->extended_usage != CHAN_EXTENDED_WRITE ||
1357 	    tcode != SSH2_EXTENDED_DATA_STDERR) {
1358 		log("channel %d: bad ext data", c->self);
1359 		return;
1360 	}
1361 	data = packet_get_string(&data_len);
1362 	packet_done();
1363 	if (data_len > c->local_window) {
1364 		log("channel %d: rcvd too much extended_data %d, win %d",
1365 		    c->self, data_len, c->local_window);
1366 		xfree(data);
1367 		return;
1368 	}
1369 	debug2("channel %d: rcvd ext data %d", c->self, data_len);
1370 	c->local_window -= data_len;
1371 	buffer_append(&c->extended, data, data_len);
1372 	xfree(data);
1373 }
1374 
1375 
1376 /*
1377  * Returns true if no channel has too much buffered data, and false if one or
1378  * more channel is overfull.
1379  */
1380 
1381 int
1382 channel_not_very_much_buffered_data()
1383 {
1384 	u_int i;
1385 	Channel *c;
1386 
1387 	for (i = 0; i < channels_alloc; i++) {
1388 		c = &channels[i];
1389 		if (c->type == SSH_CHANNEL_OPEN) {
1390 			if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1391 				debug("channel %d: big input buffer %d",
1392 				    c->self, buffer_len(&c->input));
1393 				return 0;
1394 			}
1395 			if (buffer_len(&c->output) > packet_get_maxsize()) {
1396 				debug("channel %d: big output buffer %d",
1397 				    c->self, buffer_len(&c->output));
1398 				return 0;
1399 			}
1400 		}
1401 	}
1402 	return 1;
1403 }
1404 
1405 void
1406 channel_input_ieof(int type, int plen, void *ctxt)
1407 {
1408 	int id;
1409 	Channel *c;
1410 
1411 	packet_integrity_check(plen, 4, type);
1412 
1413 	id = packet_get_int();
1414 	c = channel_lookup(id);
1415 	if (c == NULL)
1416 		packet_disconnect("Received ieof for nonexistent channel %d.", id);
1417 	chan_rcvd_ieof(c);
1418 }
1419 
1420 void
1421 channel_input_close(int type, int plen, void *ctxt)
1422 {
1423 	int id;
1424 	Channel *c;
1425 
1426 	packet_integrity_check(plen, 4, type);
1427 
1428 	id = packet_get_int();
1429 	c = channel_lookup(id);
1430 	if (c == NULL)
1431 		packet_disconnect("Received close for nonexistent channel %d.", id);
1432 
1433 	/*
1434 	 * Send a confirmation that we have closed the channel and no more
1435 	 * data is coming for it.
1436 	 */
1437 	packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1438 	packet_put_int(c->remote_id);
1439 	packet_send();
1440 
1441 	/*
1442 	 * If the channel is in closed state, we have sent a close request,
1443 	 * and the other side will eventually respond with a confirmation.
1444 	 * Thus, we cannot free the channel here, because then there would be
1445 	 * no-one to receive the confirmation.  The channel gets freed when
1446 	 * the confirmation arrives.
1447 	 */
1448 	if (c->type != SSH_CHANNEL_CLOSED) {
1449 		/*
1450 		 * Not a closed channel - mark it as draining, which will
1451 		 * cause it to be freed later.
1452 		 */
1453 		buffer_consume(&c->input, buffer_len(&c->input));
1454 		c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1455 	}
1456 }
1457 
1458 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1459 void
1460 channel_input_oclose(int type, int plen, void *ctxt)
1461 {
1462 	int id = packet_get_int();
1463 	Channel *c = channel_lookup(id);
1464 	packet_integrity_check(plen, 4, type);
1465 	if (c == NULL)
1466 		packet_disconnect("Received oclose for nonexistent channel %d.", id);
1467 	chan_rcvd_oclose(c);
1468 }
1469 
1470 void
1471 channel_input_close_confirmation(int type, int plen, void *ctxt)
1472 {
1473 	int id = packet_get_int();
1474 	Channel *c = channel_lookup(id);
1475 
1476 	packet_done();
1477 	if (c == NULL)
1478 		packet_disconnect("Received close confirmation for "
1479 		    "out-of-range channel %d.", id);
1480 	if (c->type != SSH_CHANNEL_CLOSED)
1481 		packet_disconnect("Received close confirmation for "
1482 		    "non-closed channel %d (type %d).", id, c->type);
1483 	channel_free(c->self);
1484 }
1485 
1486 void
1487 channel_input_open_confirmation(int type, int plen, void *ctxt)
1488 {
1489 	int id, remote_id;
1490 	Channel *c;
1491 
1492 	if (!compat20)
1493 		packet_integrity_check(plen, 4 + 4, type);
1494 
1495 	id = packet_get_int();
1496 	c = channel_lookup(id);
1497 
1498 	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1499 		packet_disconnect("Received open confirmation for "
1500 		    "non-opening channel %d.", id);
1501 	remote_id = packet_get_int();
1502 	/* Record the remote channel number and mark that the channel is now open. */
1503 	c->remote_id = remote_id;
1504 	c->type = SSH_CHANNEL_OPEN;
1505 
1506 	if (compat20) {
1507 		c->remote_window = packet_get_int();
1508 		c->remote_maxpacket = packet_get_int();
1509 		packet_done();
1510 		if (c->cb_fn != NULL && c->cb_event == type) {
1511 			debug2("callback start");
1512 			c->cb_fn(c->self, c->cb_arg);
1513 			debug2("callback done");
1514 		}
1515 		debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1516 		    c->remote_window, c->remote_maxpacket);
1517 	}
1518 }
1519 
1520 void
1521 channel_input_open_failure(int type, int plen, void *ctxt)
1522 {
1523 	int id, reason;
1524 	char *msg = NULL, *lang = NULL;
1525 	Channel *c;
1526 
1527 	if (!compat20)
1528 		packet_integrity_check(plen, 4, type);
1529 
1530 	id = packet_get_int();
1531 	c = channel_lookup(id);
1532 
1533 	if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1534 		packet_disconnect("Received open failure for "
1535 		    "non-opening channel %d.", id);
1536 	if (compat20) {
1537 		reason = packet_get_int();
1538 		if (packet_remaining() > 0) {
1539 			msg  = packet_get_string(NULL);
1540 			lang = packet_get_string(NULL);
1541 		}
1542 		packet_done();
1543 		log("channel_open_failure: %d: reason %d %s", id,
1544 		    reason, msg ? msg : "<no additional info>");
1545 		if (msg != NULL)
1546 			xfree(msg);
1547 		if (lang != NULL)
1548 			xfree(lang);
1549 	}
1550 	/* Free the channel.  This will also close the socket. */
1551 	channel_free(id);
1552 }
1553 
1554 void
1555 channel_input_channel_request(int type, int plen, void *ctxt)
1556 {
1557 	int id;
1558 	Channel *c;
1559 
1560 	id = packet_get_int();
1561 	c = channel_lookup(id);
1562 
1563 	if (c == NULL ||
1564 	    (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1565 		packet_disconnect("Received request for "
1566 		    "non-open channel %d.", id);
1567 	if (c->cb_fn != NULL && c->cb_event == type) {
1568 		debug2("callback start");
1569 		c->cb_fn(c->self, c->cb_arg);
1570 		debug2("callback done");
1571 	} else {
1572 		char *service = packet_get_string(NULL);
1573 		debug("channel %d: rcvd request for %s", c->self, service);
1574 		debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1575 		xfree(service);
1576 	}
1577 }
1578 
1579 void
1580 channel_input_window_adjust(int type, int plen, void *ctxt)
1581 {
1582 	Channel *c;
1583 	int id, adjust;
1584 
1585 	if (!compat20)
1586 		return;
1587 
1588 	/* Get the channel number and verify it. */
1589 	id = packet_get_int();
1590 	c = channel_lookup(id);
1591 
1592 	if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1593 		log("Received window adjust for "
1594 		    "non-open channel %d.", id);
1595 		return;
1596 	}
1597 	adjust = packet_get_int();
1598 	packet_done();
1599 	debug2("channel %d: rcvd adjust %d", id, adjust);
1600 	c->remote_window += adjust;
1601 }
1602 
1603 /*
1604  * Stops listening for channels, and removes any unix domain sockets that we
1605  * might have.
1606  */
1607 
1608 void
1609 channel_stop_listening()
1610 {
1611 	int i;
1612 	for (i = 0; i < channels_alloc; i++) {
1613 		switch (channels[i].type) {
1614 		case SSH_CHANNEL_AUTH_SOCKET:
1615 			close(channels[i].sock);
1616 			/* auth_sock_cleanup_proc deletes the socket */
1617 			channel_free(i);
1618 			break;
1619 		case SSH_CHANNEL_PORT_LISTENER:
1620 		case SSH_CHANNEL_RPORT_LISTENER:
1621 		case SSH_CHANNEL_X11_LISTENER:
1622 			close(channels[i].sock);
1623 			channel_free(i);
1624 			break;
1625 		default:
1626 			break;
1627 		}
1628 	}
1629 }
1630 
1631 /*
1632  * Closes the sockets/fds of all channels.  This is used to close extra file
1633  * descriptors after a fork.
1634  */
1635 
1636 void
1637 channel_close_all()
1638 {
1639 	int i;
1640 	for (i = 0; i < channels_alloc; i++)
1641 		if (channels[i].type != SSH_CHANNEL_FREE)
1642 			channel_close_fds(&channels[i]);
1643 }
1644 
1645 /* Returns true if any channel is still open. */
1646 
1647 int
1648 channel_still_open()
1649 {
1650 	u_int i;
1651 	for (i = 0; i < channels_alloc; i++)
1652 		switch (channels[i].type) {
1653 		case SSH_CHANNEL_FREE:
1654 		case SSH_CHANNEL_X11_LISTENER:
1655 		case SSH_CHANNEL_PORT_LISTENER:
1656 		case SSH_CHANNEL_RPORT_LISTENER:
1657 		case SSH_CHANNEL_CLOSED:
1658 		case SSH_CHANNEL_AUTH_SOCKET:
1659 		case SSH_CHANNEL_DYNAMIC:
1660 		case SSH_CHANNEL_CONNECTING: 	/* XXX ??? */
1661 			continue;
1662 		case SSH_CHANNEL_LARVAL:
1663 			if (!compat20)
1664 				fatal("cannot happen: SSH_CHANNEL_LARVAL");
1665 			continue;
1666 		case SSH_CHANNEL_OPENING:
1667 		case SSH_CHANNEL_OPEN:
1668 		case SSH_CHANNEL_X11_OPEN:
1669 			return 1;
1670 		case SSH_CHANNEL_INPUT_DRAINING:
1671 		case SSH_CHANNEL_OUTPUT_DRAINING:
1672 			if (!compat13)
1673 				fatal("cannot happen: OUT_DRAIN");
1674 			return 1;
1675 		default:
1676 			fatal("channel_still_open: bad channel type %d", channels[i].type);
1677 			/* NOTREACHED */
1678 		}
1679 	return 0;
1680 }
1681 
1682 /* Returns the id of an open channel suitable for keepaliving */
1683 
1684 int
1685 channel_find_open()
1686 {
1687 	u_int i;
1688 	for (i = 0; i < channels_alloc; i++)
1689 		switch (channels[i].type) {
1690 		case SSH_CHANNEL_CLOSED:
1691 		case SSH_CHANNEL_DYNAMIC:
1692 		case SSH_CHANNEL_FREE:
1693 		case SSH_CHANNEL_X11_LISTENER:
1694 		case SSH_CHANNEL_PORT_LISTENER:
1695 		case SSH_CHANNEL_RPORT_LISTENER:
1696 		case SSH_CHANNEL_OPENING:
1697 			continue;
1698 		case SSH_CHANNEL_LARVAL:
1699 		case SSH_CHANNEL_AUTH_SOCKET:
1700 		case SSH_CHANNEL_CONNECTING: 	/* XXX ??? */
1701 		case SSH_CHANNEL_OPEN:
1702 		case SSH_CHANNEL_X11_OPEN:
1703 			return i;
1704 		case SSH_CHANNEL_INPUT_DRAINING:
1705 		case SSH_CHANNEL_OUTPUT_DRAINING:
1706 			if (!compat13)
1707 				fatal("cannot happen: OUT_DRAIN");
1708 			return i;
1709 		default:
1710 			fatal("channel_find_open: bad channel type %d", channels[i].type);
1711 			/* NOTREACHED */
1712 		}
1713 	return -1;
1714 }
1715 
1716 
1717 /*
1718  * Returns a message describing the currently open forwarded connections,
1719  * suitable for sending to the client.  The message contains crlf pairs for
1720  * newlines.
1721  */
1722 
1723 char *
1724 channel_open_message()
1725 {
1726 	Buffer buffer;
1727 	int i;
1728 	char buf[512], *cp;
1729 
1730 	buffer_init(&buffer);
1731 	snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1732 	buffer_append(&buffer, buf, strlen(buf));
1733 	for (i = 0; i < channels_alloc; i++) {
1734 		Channel *c = &channels[i];
1735 		switch (c->type) {
1736 		case SSH_CHANNEL_FREE:
1737 		case SSH_CHANNEL_X11_LISTENER:
1738 		case SSH_CHANNEL_PORT_LISTENER:
1739 		case SSH_CHANNEL_RPORT_LISTENER:
1740 		case SSH_CHANNEL_CLOSED:
1741 		case SSH_CHANNEL_AUTH_SOCKET:
1742 			continue;
1743 		case SSH_CHANNEL_LARVAL:
1744 		case SSH_CHANNEL_OPENING:
1745 		case SSH_CHANNEL_CONNECTING:
1746 		case SSH_CHANNEL_DYNAMIC:
1747 		case SSH_CHANNEL_OPEN:
1748 		case SSH_CHANNEL_X11_OPEN:
1749 		case SSH_CHANNEL_INPUT_DRAINING:
1750 		case SSH_CHANNEL_OUTPUT_DRAINING:
1751 			snprintf(buf, sizeof buf, "  #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1752 			    c->self, c->remote_name,
1753 			    c->type, c->remote_id,
1754 			    c->istate, buffer_len(&c->input),
1755 			    c->ostate, buffer_len(&c->output),
1756 			    c->rfd, c->wfd);
1757 			buffer_append(&buffer, buf, strlen(buf));
1758 			continue;
1759 		default:
1760 			fatal("channel_open_message: bad channel type %d", c->type);
1761 			/* NOTREACHED */
1762 		}
1763 	}
1764 	buffer_append(&buffer, "\0", 1);
1765 	cp = xstrdup(buffer_ptr(&buffer));
1766 	buffer_free(&buffer);
1767 	return cp;
1768 }
1769 
1770 /*
1771  * Initiate forwarding of connections to local port "port" through the secure
1772  * channel to host:port from remote side.
1773  */
1774 int
1775 channel_request_local_forwarding(u_short listen_port, const char *host_to_connect,
1776     u_short port_to_connect, int gateway_ports)
1777 {
1778 	return channel_request_forwarding(
1779 	    NULL, listen_port,
1780 	    host_to_connect, port_to_connect,
1781 	    gateway_ports, /*remote_fwd*/ 0);
1782 }
1783 
1784 /*
1785  * If 'remote_fwd' is true we have a '-R style' listener for protocol 2
1786  * (SSH_CHANNEL_RPORT_LISTENER).
1787  */
1788 int
1789 channel_request_forwarding(
1790     const char *listen_address, u_short listen_port,
1791     const char *host_to_connect, u_short port_to_connect,
1792     int gateway_ports, int remote_fwd)
1793 {
1794 	int success, ch, sock, on = 1, ctype;
1795 	struct addrinfo hints, *ai, *aitop;
1796 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1797 	const char *host;
1798 	struct linger linger;
1799 
1800 	success = 0;
1801 
1802 	if (remote_fwd) {
1803 		host = listen_address;
1804 		ctype = SSH_CHANNEL_RPORT_LISTENER;
1805 	} else {
1806 		host = host_to_connect;
1807 		ctype  =SSH_CHANNEL_PORT_LISTENER;
1808 	}
1809 
1810 	if (strlen(host) > sizeof(channels[0].path) - 1) {
1811 		error("Forward host name too long.");
1812 		return success;
1813 	}
1814 
1815 	/* XXX listen_address is currently ignored */
1816 	/*
1817 	 * getaddrinfo returns a loopback address if the hostname is
1818 	 * set to NULL and hints.ai_flags is not AI_PASSIVE
1819 	 */
1820 	memset(&hints, 0, sizeof(hints));
1821 	hints.ai_family = IPv4or6;
1822 	hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1823 	hints.ai_socktype = SOCK_STREAM;
1824 	snprintf(strport, sizeof strport, "%d", listen_port);
1825 	if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1826 		packet_disconnect("getaddrinfo: fatal error");
1827 
1828 	for (ai = aitop; ai; ai = ai->ai_next) {
1829 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1830 			continue;
1831 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1832 		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1833 			error("channel_request_forwarding: getnameinfo failed");
1834 			continue;
1835 		}
1836 		/* Create a port to listen for the host. */
1837 		sock = socket(ai->ai_family, SOCK_STREAM, 0);
1838 		if (sock < 0) {
1839 			/* this is no error since kernel may not support ipv6 */
1840 			verbose("socket: %.100s", strerror(errno));
1841 			continue;
1842 		}
1843 		/*
1844 		 * Set socket options.  We would like the socket to disappear
1845 		 * as soon as it has been closed for whatever reason.
1846 		 */
1847 		setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1848 		linger.l_onoff = 1;
1849 		linger.l_linger = 5;
1850 		setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1851 		debug("Local forwarding listening on %s port %s.", ntop, strport);
1852 
1853 		/* Bind the socket to the address. */
1854 		if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1855 			/* address can be in use ipv6 address is already bound */
1856 			verbose("bind: %.100s", strerror(errno));
1857 			close(sock);
1858 			continue;
1859 		}
1860 		/* Start listening for connections on the socket. */
1861 		if (listen(sock, 5) < 0) {
1862 			error("listen: %.100s", strerror(errno));
1863 			close(sock);
1864 			continue;
1865 		}
1866 		/* Allocate a channel number for the socket. */
1867 		ch = channel_new("port listener", ctype, sock, sock, -1,
1868 		    CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1869 		    0, xstrdup("port listener"), 1);
1870 		strlcpy(channels[ch].path, host, sizeof(channels[ch].path));
1871 		channels[ch].host_port = port_to_connect;
1872 		channels[ch].listening_port = listen_port;
1873 		success = 1;
1874 	}
1875 	if (success == 0)
1876 		error("channel_request_forwarding: cannot listen to port: %d",
1877 		    listen_port);
1878 	freeaddrinfo(aitop);
1879 	return success;
1880 }
1881 
1882 /*
1883  * Initiate forwarding of connections to port "port" on remote host through
1884  * the secure channel to host:port from local side.
1885  */
1886 
1887 void
1888 channel_request_remote_forwarding(u_short listen_port,
1889     const char *host_to_connect, u_short port_to_connect)
1890 {
1891 	int payload_len, type, success = 0;
1892 
1893 	/* Record locally that connection to this host/port is permitted. */
1894 	if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1895 		fatal("channel_request_remote_forwarding: too many forwards");
1896 
1897 	/* Send the forward request to the remote side. */
1898 	if (compat20) {
1899 		const char *address_to_bind = "0.0.0.0";
1900 		packet_start(SSH2_MSG_GLOBAL_REQUEST);
1901 		packet_put_cstring("tcpip-forward");
1902 		packet_put_char(0);			/* boolean: want reply */
1903 		packet_put_cstring(address_to_bind);
1904 		packet_put_int(listen_port);
1905 		packet_send();
1906 		packet_write_wait();
1907 		/* Assume that server accepts the request */
1908 		success = 1;
1909 	} else {
1910 		packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1911 		packet_put_int(listen_port);
1912 		packet_put_cstring(host_to_connect);
1913 		packet_put_int(port_to_connect);
1914 		packet_send();
1915 		packet_write_wait();
1916 
1917 		/* Wait for response from the remote side. */
1918 		type = packet_read(&payload_len);
1919 		switch (type) {
1920 		case SSH_SMSG_SUCCESS:
1921 			success = 1;
1922 			break;
1923 		case SSH_SMSG_FAILURE:
1924 			log("Warning: Server denied remote port forwarding.");
1925 			break;
1926 		default:
1927 			/* Unknown packet */
1928 			packet_disconnect("Protocol error for port forward request:"
1929 			    "received packet type %d.", type);
1930 		}
1931 	}
1932 	if (success) {
1933 		permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
1934 		permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
1935 		permitted_opens[num_permitted_opens].listen_port = listen_port;
1936 		num_permitted_opens++;
1937 	}
1938 }
1939 
1940 /*
1941  * This is called after receiving CHANNEL_FORWARDING_REQUEST.  This initates
1942  * listening for the port, and sends back a success reply (or disconnect
1943  * message if there was an error).  This never returns if there was an error.
1944  */
1945 
1946 void
1947 channel_input_port_forward_request(int is_root, int gateway_ports)
1948 {
1949 	u_short port, host_port;
1950 	char *hostname;
1951 
1952 	/* Get arguments from the packet. */
1953 	port = packet_get_int();
1954 	hostname = packet_get_string(NULL);
1955 	host_port = packet_get_int();
1956 
1957 	/*
1958 	 * Check that an unprivileged user is not trying to forward a
1959 	 * privileged port.
1960 	 */
1961 	if (port < IPPORT_RESERVED && !is_root)
1962 		packet_disconnect("Requested forwarding of port %d but user is not root.",
1963 				  port);
1964 	/* Initiate forwarding */
1965 	channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
1966 
1967 	/* Free the argument string. */
1968 	xfree(hostname);
1969 }
1970 
1971 /*
1972  * Permits opening to any host/port if permitted_opens[] is empty.  This is
1973  * usually called by the server, because the user could connect to any port
1974  * anyway, and the server has no way to know but to trust the client anyway.
1975  */
1976 void
1977 channel_permit_all_opens()
1978 {
1979 	if (num_permitted_opens == 0)
1980 		all_opens_permitted = 1;
1981 }
1982 
1983 void
1984 channel_add_permitted_opens(char *host, int port)
1985 {
1986 	if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1987 		fatal("channel_request_remote_forwarding: too many forwards");
1988 	debug("allow port forwarding to host %s port %d", host, port);
1989 
1990 	permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
1991 	permitted_opens[num_permitted_opens].port_to_connect = port;
1992 	num_permitted_opens++;
1993 
1994 	all_opens_permitted = 0;
1995 }
1996 
1997 void
1998 channel_clear_permitted_opens(void)
1999 {
2000 	int i;
2001 
2002 	for (i = 0; i < num_permitted_opens; i++)
2003 		xfree(permitted_opens[i].host_to_connect);
2004 	num_permitted_opens = 0;
2005 
2006 }
2007 
2008 
2009 /* return socket to remote host, port */
2010 int
2011 connect_to(const char *host, u_short port)
2012 {
2013 	struct addrinfo hints, *ai, *aitop;
2014 	char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2015 	int gaierr;
2016 	int sock = -1;
2017 
2018 	memset(&hints, 0, sizeof(hints));
2019 	hints.ai_family = IPv4or6;
2020 	hints.ai_socktype = SOCK_STREAM;
2021 	snprintf(strport, sizeof strport, "%d", port);
2022 	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2023 		error("connect_to %.100s: unknown host (%s)", host,
2024 		    gai_strerror(gaierr));
2025 		return -1;
2026 	}
2027 	for (ai = aitop; ai; ai = ai->ai_next) {
2028 		if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2029 			continue;
2030 		if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2031 		    strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2032 			error("connect_to: getnameinfo failed");
2033 			continue;
2034 		}
2035 		sock = socket(ai->ai_family, SOCK_STREAM, 0);
2036 		if (sock < 0) {
2037 			error("socket: %.100s", strerror(errno));
2038 			continue;
2039 		}
2040 		if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2041 			fatal("connect_to: F_SETFL: %s", strerror(errno));
2042 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2043 		    errno != EINPROGRESS) {
2044 			error("connect_to %.100s port %s: %.100s", ntop, strport,
2045 			    strerror(errno));
2046 			close(sock);
2047 			continue;	/* fail -- try next */
2048 		}
2049 		break; /* success */
2050 
2051 	}
2052 	freeaddrinfo(aitop);
2053 	if (!ai) {
2054 		error("connect_to %.100s port %d: failed.", host, port);
2055 		return -1;
2056 	}
2057 	/* success */
2058 	return sock;
2059 }
2060 
2061 int
2062 channel_connect_by_listen_adress(u_short listen_port)
2063 {
2064 	int i;
2065 
2066 	for (i = 0; i < num_permitted_opens; i++)
2067 		if (permitted_opens[i].listen_port == listen_port)
2068 			return connect_to(
2069 			    permitted_opens[i].host_to_connect,
2070 			    permitted_opens[i].port_to_connect);
2071 	error("WARNING: Server requests forwarding for unknown listen_port %d",
2072 	    listen_port);
2073 	return -1;
2074 }
2075 
2076 /* Check if connecting to that port is permitted and connect. */
2077 int
2078 channel_connect_to(const char *host, u_short port)
2079 {
2080 	int i, permit;
2081 
2082 	permit = all_opens_permitted;
2083 	if (!permit) {
2084 		for (i = 0; i < num_permitted_opens; i++)
2085 			if (permitted_opens[i].port_to_connect == port &&
2086 			    strcmp(permitted_opens[i].host_to_connect, host) == 0)
2087 				permit = 1;
2088 
2089 	}
2090 	if (!permit) {
2091 		log("Received request to connect to host %.100s port %d, "
2092 		    "but the request was denied.", host, port);
2093 		return -1;
2094 	}
2095 	return connect_to(host, port);
2096 }
2097 
2098 /*
2099  * This is called after receiving PORT_OPEN message.  This attempts to
2100  * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
2101  * or CHANNEL_OPEN_FAILURE.
2102  */
2103 
2104 void
2105 channel_input_port_open(int type, int plen, void *ctxt)
2106 {
2107 	u_short host_port;
2108 	char *host, *originator_string;
2109 	int remote_channel, sock = -1, newch;
2110 
2111 	remote_channel = packet_get_int();
2112 	host = packet_get_string(NULL);
2113 	host_port = packet_get_int();
2114 
2115 	if (have_hostname_in_open) {
2116 		originator_string = packet_get_string(NULL);
2117 	} else {
2118 		originator_string = xstrdup("unknown (remote did not supply name)");
2119 	}
2120 	packet_done();
2121 	sock = channel_connect_to(host, host_port);
2122 	if (sock != -1) {
2123 		newch = channel_allocate(SSH_CHANNEL_CONNECTING,
2124 		    sock, originator_string);
2125 		channels[newch].remote_id = remote_channel;
2126 
2127 		/*XXX delay answer? */
2128 		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2129 		packet_put_int(remote_channel);
2130 		packet_put_int(newch);
2131 		packet_send();
2132 	} else {
2133 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2134 		packet_put_int(remote_channel);
2135 		packet_send();
2136 	}
2137 	xfree(host);
2138 }
2139 
2140 /*
2141  * Creates an internet domain socket for listening for X11 connections.
2142  * Returns a suitable value for the DISPLAY variable, or NULL if an error
2143  * occurs.
2144  */
2145 
2146 #define	NUM_SOCKS	10
2147 
2148 char *
2149 x11_create_display_inet(int screen_number, int x11_display_offset)
2150 {
2151 	int display_number, sock;
2152 	u_short port;
2153 	struct addrinfo hints, *ai, *aitop;
2154 	char strport[NI_MAXSERV];
2155 	int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2156 	char display[512];
2157 	char hostname[MAXHOSTNAMELEN];
2158 
2159 	for (display_number = x11_display_offset;
2160 	     display_number < MAX_DISPLAYS;
2161 	     display_number++) {
2162 		port = 6000 + display_number;
2163 		memset(&hints, 0, sizeof(hints));
2164 		hints.ai_family = IPv4or6;
2165 		hints.ai_flags = AI_PASSIVE;		/* XXX loopback only ? */
2166 		hints.ai_socktype = SOCK_STREAM;
2167 		snprintf(strport, sizeof strport, "%d", port);
2168 		if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2169 			error("getaddrinfo: %.100s", gai_strerror(gaierr));
2170 			return NULL;
2171 		}
2172 		for (ai = aitop; ai; ai = ai->ai_next) {
2173 			if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2174 				continue;
2175 			sock = socket(ai->ai_family, SOCK_STREAM, 0);
2176 			if (sock < 0) {
2177 				error("socket: %.100s", strerror(errno));
2178 				return NULL;
2179 			}
2180 			if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2181 				debug("bind port %d: %.100s", port, strerror(errno));
2182 				shutdown(sock, SHUT_RDWR);
2183 				close(sock);
2184 				for (n = 0; n < num_socks; n++) {
2185 					shutdown(socks[n], SHUT_RDWR);
2186 					close(socks[n]);
2187 				}
2188 				num_socks = 0;
2189 				break;
2190 			}
2191 			socks[num_socks++] = sock;
2192 			if (num_socks == NUM_SOCKS)
2193 				break;
2194 		}
2195 		freeaddrinfo(aitop);
2196 		if (num_socks > 0)
2197 			break;
2198 	}
2199 	if (display_number >= MAX_DISPLAYS) {
2200 		error("Failed to allocate internet-domain X11 display socket.");
2201 		return NULL;
2202 	}
2203 	/* Start listening for connections on the socket. */
2204 	for (n = 0; n < num_socks; n++) {
2205 		sock = socks[n];
2206 		if (listen(sock, 5) < 0) {
2207 			error("listen: %.100s", strerror(errno));
2208 			shutdown(sock, SHUT_RDWR);
2209 			close(sock);
2210 			return NULL;
2211 		}
2212 	}
2213 
2214 	/* Set up a suitable value for the DISPLAY variable. */
2215 	if (gethostname(hostname, sizeof(hostname)) < 0)
2216 		fatal("gethostname: %.100s", strerror(errno));
2217 	snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
2218 		 display_number, screen_number);
2219 
2220 	/* Allocate a channel for each socket. */
2221 	for (n = 0; n < num_socks; n++) {
2222 		sock = socks[n];
2223 		(void) channel_new("x11 listener",
2224 		    SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2225 		    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2226 		    0, xstrdup("X11 inet listener"), 1);
2227 	}
2228 
2229 	/* Return a suitable value for the DISPLAY environment variable. */
2230 	return xstrdup(display);
2231 }
2232 
2233 #ifndef X_UNIX_PATH
2234 #define X_UNIX_PATH "/tmp/.X11-unix/X"
2235 #endif
2236 
2237 static
2238 int
2239 connect_local_xsocket(u_int dnr)
2240 {
2241 	static const char *const x_sockets[] = {
2242 		X_UNIX_PATH "%u",
2243 		"/var/X/.X11-unix/X" "%u",
2244 		"/usr/spool/sockets/X11/" "%u",
2245 		NULL
2246 	};
2247 	int sock;
2248 	struct sockaddr_un addr;
2249 	const char *const * path;
2250 
2251 	for (path = x_sockets; *path; ++path) {
2252 		sock = socket(AF_UNIX, SOCK_STREAM, 0);
2253 		if (sock < 0)
2254 			error("socket: %.100s", strerror(errno));
2255 		memset(&addr, 0, sizeof(addr));
2256 		addr.sun_family = AF_UNIX;
2257 		snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
2258 		if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2259 			return sock;
2260 		close(sock);
2261 	}
2262 	error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2263 	return -1;
2264 }
2265 
2266 int
2267 x11_connect_display(void)
2268 {
2269 	int display_number, sock = 0;
2270 	const char *display;
2271 	char buf[1024], *cp;
2272 	struct addrinfo hints, *ai, *aitop;
2273 	char strport[NI_MAXSERV];
2274 	int gaierr;
2275 
2276 	/* Try to open a socket for the local X server. */
2277 	display = getenv("DISPLAY");
2278 	if (!display) {
2279 		error("DISPLAY not set.");
2280 		return -1;
2281 	}
2282 	/*
2283 	 * Now we decode the value of the DISPLAY variable and make a
2284 	 * connection to the real X server.
2285 	 */
2286 
2287 	/*
2288 	 * Check if it is a unix domain socket.  Unix domain displays are in
2289 	 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2290 	 */
2291 	if (strncmp(display, "unix:", 5) == 0 ||
2292 	    display[0] == ':') {
2293 		/* Connect to the unix domain socket. */
2294 		if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2295 			error("Could not parse display number from DISPLAY: %.100s",
2296 			      display);
2297 			return -1;
2298 		}
2299 		/* Create a socket. */
2300 		sock = connect_local_xsocket(display_number);
2301 		if (sock < 0)
2302 			return -1;
2303 
2304 		/* OK, we now have a connection to the display. */
2305 		return sock;
2306 	}
2307 	/*
2308 	 * Connect to an inet socket.  The DISPLAY value is supposedly
2309 	 * hostname:d[.s], where hostname may also be numeric IP address.
2310 	 */
2311 	strncpy(buf, display, sizeof(buf));
2312 	buf[sizeof(buf) - 1] = 0;
2313 	cp = strchr(buf, ':');
2314 	if (!cp) {
2315 		error("Could not find ':' in DISPLAY: %.100s", display);
2316 		return -1;
2317 	}
2318 	*cp = 0;
2319 	/* buf now contains the host name.  But first we parse the display number. */
2320 	if (sscanf(cp + 1, "%d", &display_number) != 1) {
2321 		error("Could not parse display number from DISPLAY: %.100s",
2322 		      display);
2323 		return -1;
2324 	}
2325 
2326 	/* Look up the host address */
2327 	memset(&hints, 0, sizeof(hints));
2328 	hints.ai_family = IPv4or6;
2329 	hints.ai_socktype = SOCK_STREAM;
2330 	snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2331 	if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2332 		error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2333 		return -1;
2334 	}
2335 	for (ai = aitop; ai; ai = ai->ai_next) {
2336 		/* Create a socket. */
2337 		sock = socket(ai->ai_family, SOCK_STREAM, 0);
2338 		if (sock < 0) {
2339 			debug("socket: %.100s", strerror(errno));
2340 			continue;
2341 		}
2342 		/* Connect it to the display. */
2343 		if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2344 			debug("connect %.100s port %d: %.100s", buf,
2345 			    6000 + display_number, strerror(errno));
2346 			close(sock);
2347 			continue;
2348 		}
2349 		/* Success */
2350 		break;
2351 	}
2352 	freeaddrinfo(aitop);
2353 	if (!ai) {
2354 		error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2355 		    strerror(errno));
2356 		return -1;
2357 	}
2358 	return sock;
2359 }
2360 
2361 /*
2362  * This is called when SSH_SMSG_X11_OPEN is received.  The packet contains
2363  * the remote channel number.  We should do whatever we want, and respond
2364  * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2365  */
2366 
2367 void
2368 x11_input_open(int type, int plen, void *ctxt)
2369 {
2370 	int remote_channel, sock = 0, newch;
2371 	char *remote_host;
2372 	u_int remote_len;
2373 
2374 	/* Get remote channel number. */
2375 	remote_channel = packet_get_int();
2376 
2377 	/* Get remote originator name. */
2378 	if (have_hostname_in_open) {
2379 		remote_host = packet_get_string(&remote_len);
2380 		remote_len += 4;
2381 	} else {
2382 		remote_host = xstrdup("unknown (remote did not supply name)");
2383 		remote_len = 0;
2384 	}
2385 
2386 	debug("Received X11 open request.");
2387 	packet_integrity_check(plen, 4 + remote_len, SSH_SMSG_X11_OPEN);
2388 
2389 	/* Obtain a connection to the real X display. */
2390 	sock = x11_connect_display();
2391 	if (sock == -1) {
2392 		/* Send refusal to the remote host. */
2393 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2394 		packet_put_int(remote_channel);
2395 		packet_send();
2396 	} else {
2397 		/* Allocate a channel for this connection. */
2398 		newch = channel_allocate(
2399 		     (x11_saved_proto == NULL) ?
2400 		     SSH_CHANNEL_OPEN : SSH_CHANNEL_X11_OPEN,
2401 		     sock, remote_host);
2402 		channels[newch].remote_id = remote_channel;
2403 
2404 		/* Send a confirmation to the remote host. */
2405 		packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2406 		packet_put_int(remote_channel);
2407 		packet_put_int(newch);
2408 		packet_send();
2409 	}
2410 }
2411 
2412 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2413 void
2414 deny_input_open(int type, int plen, void *ctxt)
2415 {
2416 	int rchan = packet_get_int();
2417 	switch(type){
2418 	case SSH_SMSG_AGENT_OPEN:
2419 		error("Warning: ssh server tried agent forwarding.");
2420 		break;
2421 	case SSH_SMSG_X11_OPEN:
2422 		error("Warning: ssh server tried X11 forwarding.");
2423 		break;
2424 	default:
2425 		error("deny_input_open: type %d plen %d", type, plen);
2426 		break;
2427 	}
2428 	error("Warning: this is probably a break in attempt by a malicious server.");
2429 	packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2430 	packet_put_int(rchan);
2431 	packet_send();
2432 }
2433 
2434 /*
2435  * Requests forwarding of X11 connections, generates fake authentication
2436  * data, and enables authentication spoofing.
2437  */
2438 
2439 void
2440 x11_request_forwarding_with_spoofing(int client_session_id,
2441     const char *proto, const char *data)
2442 {
2443 	u_int data_len = (u_int) strlen(data) / 2;
2444 	u_int i, value, len;
2445 	char *new_data;
2446 	int screen_number;
2447 	const char *cp;
2448 	u_int32_t rand = 0;
2449 
2450 	cp = getenv("DISPLAY");
2451 	if (cp)
2452 		cp = strchr(cp, ':');
2453 	if (cp)
2454 		cp = strchr(cp, '.');
2455 	if (cp)
2456 		screen_number = atoi(cp + 1);
2457 	else
2458 		screen_number = 0;
2459 
2460 	/* Save protocol name. */
2461 	x11_saved_proto = xstrdup(proto);
2462 
2463 	/*
2464 	 * Extract real authentication data and generate fake data of the
2465 	 * same length.
2466 	 */
2467 	x11_saved_data = xmalloc(data_len);
2468 	x11_fake_data = xmalloc(data_len);
2469 	for (i = 0; i < data_len; i++) {
2470 		if (sscanf(data + 2 * i, "%2x", &value) != 1)
2471 			fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2472 		if (i % 4 == 0)
2473 			rand = arc4random();
2474 		x11_saved_data[i] = value;
2475 		x11_fake_data[i] = rand & 0xff;
2476 		rand >>= 8;
2477 	}
2478 	x11_saved_data_len = data_len;
2479 	x11_fake_data_len = data_len;
2480 
2481 	/* Convert the fake data into hex. */
2482 	len = 2 * data_len + 1;
2483 	new_data = xmalloc(len);
2484 	for (i = 0; i < data_len; i++)
2485 		snprintf(new_data + 2 * i, len - 2 * i,
2486 		    "%02x", (u_char) x11_fake_data[i]);
2487 
2488 	/* Send the request packet. */
2489 	if (compat20) {
2490 		channel_request_start(client_session_id, "x11-req", 0);
2491 		packet_put_char(0);	/* XXX bool single connection */
2492 	} else {
2493 		packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2494 	}
2495 	packet_put_cstring(proto);
2496 	packet_put_cstring(new_data);
2497 	packet_put_int(screen_number);
2498 	packet_send();
2499 	packet_write_wait();
2500 	xfree(new_data);
2501 }
2502 
2503 /* Sends a message to the server to request authentication fd forwarding. */
2504 
2505 void
2506 auth_request_forwarding()
2507 {
2508 	packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2509 	packet_send();
2510 	packet_write_wait();
2511 }
2512 
2513 /*
2514  * Returns the name of the forwarded authentication socket.  Returns NULL if
2515  * there is no forwarded authentication socket.  The returned value points to
2516  * a static buffer.
2517  */
2518 
2519 char *
2520 auth_get_socket_name()
2521 {
2522 	return channel_forwarded_auth_socket_name;
2523 }
2524 
2525 /* removes the agent forwarding socket */
2526 
2527 void
2528 auth_sock_cleanup_proc(void *_pw)
2529 {
2530 	struct passwd *pw = _pw;
2531 
2532 	if (channel_forwarded_auth_socket_name) {
2533 		temporarily_use_uid(pw);
2534 		unlink(channel_forwarded_auth_socket_name);
2535 		rmdir(channel_forwarded_auth_socket_dir);
2536 		channel_forwarded_auth_socket_name = NULL;
2537 		restore_uid();
2538 	}
2539 }
2540 
2541 /*
2542  * This is called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2543  * This starts forwarding authentication requests.
2544  */
2545 
2546 int
2547 auth_input_request_forwarding(struct passwd * pw)
2548 {
2549 	int sock, newch;
2550 	struct sockaddr_un sunaddr;
2551 
2552 	if (auth_get_socket_name() != NULL)
2553 		fatal("Protocol error: authentication forwarding requested twice.");
2554 
2555 	/* Temporarily drop privileged uid for mkdir/bind. */
2556 	temporarily_use_uid(pw);
2557 
2558 	/* Allocate a buffer for the socket name, and format the name. */
2559 	channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2560 	channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2561 	strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2562 
2563 	/* Create private directory for socket */
2564 	if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL) {
2565 		packet_send_debug("Agent forwarding disabled: mkdtemp() failed: %.100s",
2566 		    strerror(errno));
2567 		restore_uid();
2568 		xfree(channel_forwarded_auth_socket_name);
2569 		xfree(channel_forwarded_auth_socket_dir);
2570 		channel_forwarded_auth_socket_name = NULL;
2571 		channel_forwarded_auth_socket_dir = NULL;
2572 		return 0;
2573 	}
2574 	snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2575 		 channel_forwarded_auth_socket_dir, (int) getpid());
2576 
2577 	/* delete agent socket on fatal() */
2578 	fatal_add_cleanup(auth_sock_cleanup_proc, pw);
2579 
2580 	/* Create the socket. */
2581 	sock = socket(AF_UNIX, SOCK_STREAM, 0);
2582 	if (sock < 0)
2583 		packet_disconnect("socket: %.100s", strerror(errno));
2584 
2585 	/* Bind it to the name. */
2586 	memset(&sunaddr, 0, sizeof(sunaddr));
2587 	sunaddr.sun_family = AF_UNIX;
2588 	strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2589 		sizeof(sunaddr.sun_path));
2590 
2591 	if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2592 		packet_disconnect("bind: %.100s", strerror(errno));
2593 
2594 	/* Restore the privileged uid. */
2595 	restore_uid();
2596 
2597 	/* Start listening on the socket. */
2598 	if (listen(sock, 5) < 0)
2599 		packet_disconnect("listen: %.100s", strerror(errno));
2600 
2601 	/* Allocate a channel for the authentication agent socket. */
2602 	newch = channel_new("auth socket",
2603 	    SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
2604 	    CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2605 	    0, xstrdup("auth socket"), 1);
2606 
2607 	strlcpy(channels[newch].path, channel_forwarded_auth_socket_name,
2608 	    sizeof(channels[newch].path));
2609 	return 1;
2610 }
2611 
2612 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2613 
2614 void
2615 auth_input_open_request(int type, int plen, void *ctxt)
2616 {
2617 	int remch, sock, newch;
2618 	char *dummyname;
2619 
2620 	packet_integrity_check(plen, 4, type);
2621 
2622 	/* Read the remote channel number from the message. */
2623 	remch = packet_get_int();
2624 
2625 	/*
2626 	 * Get a connection to the local authentication agent (this may again
2627 	 * get forwarded).
2628 	 */
2629 	sock = ssh_get_authentication_socket();
2630 
2631 	/*
2632 	 * If we could not connect the agent, send an error message back to
2633 	 * the server. This should never happen unless the agent dies,
2634 	 * because authentication forwarding is only enabled if we have an
2635 	 * agent.
2636 	 */
2637 	if (sock < 0) {
2638 		packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2639 		packet_put_int(remch);
2640 		packet_send();
2641 		return;
2642 	}
2643 	debug("Forwarding authentication connection.");
2644 
2645 	/*
2646 	 * Dummy host name.  This will be freed when the channel is freed; it
2647 	 * will still be valid in the packet_put_string below since the
2648 	 * channel cannot yet be freed at that point.
2649 	 */
2650 	dummyname = xstrdup("authentication agent connection");
2651 
2652 	newch = channel_allocate(SSH_CHANNEL_OPEN, sock, dummyname);
2653 	channels[newch].remote_id = remch;
2654 
2655 	/* Send a confirmation to the remote host. */
2656 	packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2657 	packet_put_int(remch);
2658 	packet_put_int(newch);
2659 	packet_send();
2660 }
2661 
2662 void
2663 channel_start_open(int id)
2664 {
2665 	Channel *c = channel_lookup(id);
2666 	if (c == NULL) {
2667 		log("channel_open: %d: bad id", id);
2668 		return;
2669 	}
2670 	debug("send channel open %d", id);
2671 	packet_start(SSH2_MSG_CHANNEL_OPEN);
2672 	packet_put_cstring(c->ctype);
2673 	packet_put_int(c->self);
2674 	packet_put_int(c->local_window);
2675 	packet_put_int(c->local_maxpacket);
2676 }
2677 void
2678 channel_open(int id)
2679 {
2680 	/* XXX REMOVE ME */
2681 	channel_start_open(id);
2682 	packet_send();
2683 }
2684 void
2685 channel_request(int id, char *service, int wantconfirm)
2686 {
2687 	channel_request_start(id, service, wantconfirm);
2688 	packet_send();
2689 	debug("channel request %d: %s", id, service) ;
2690 }
2691 void
2692 channel_request_start(int id, char *service, int wantconfirm)
2693 {
2694 	Channel *c = channel_lookup(id);
2695 	if (c == NULL) {
2696 		log("channel_request: %d: bad id", id);
2697 		return;
2698 	}
2699 	packet_start(SSH2_MSG_CHANNEL_REQUEST);
2700 	packet_put_int(c->remote_id);
2701 	packet_put_cstring(service);
2702 	packet_put_char(wantconfirm);
2703 }
2704 void
2705 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2706 {
2707 	Channel *c = channel_lookup(id);
2708 	if (c == NULL) {
2709 		log("channel_register_callback: %d: bad id", id);
2710 		return;
2711 	}
2712 	c->cb_event = mtype;
2713 	c->cb_fn = fn;
2714 	c->cb_arg = arg;
2715 }
2716 void
2717 channel_register_cleanup(int id, channel_callback_fn *fn)
2718 {
2719 	Channel *c = channel_lookup(id);
2720 	if (c == NULL) {
2721 		log("channel_register_cleanup: %d: bad id", id);
2722 		return;
2723 	}
2724 	c->dettach_user = fn;
2725 }
2726 void
2727 channel_cancel_cleanup(int id)
2728 {
2729 	Channel *c = channel_lookup(id);
2730 	if (c == NULL) {
2731 		log("channel_cancel_cleanup: %d: bad id", id);
2732 		return;
2733 	}
2734 	c->dettach_user = NULL;
2735 }
2736 void
2737 channel_register_filter(int id, channel_filter_fn *fn)
2738 {
2739 	Channel *c = channel_lookup(id);
2740 	if (c == NULL) {
2741 		log("channel_register_filter: %d: bad id", id);
2742 		return;
2743 	}
2744 	c->input_filter = fn;
2745 }
2746 
2747 void
2748 channel_set_fds(int id, int rfd, int wfd, int efd,
2749     int extusage, int nonblock)
2750 {
2751 	Channel *c = channel_lookup(id);
2752 	if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2753 		fatal("channel_activate for non-larval channel %d.", id);
2754 	channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
2755 	c->type = SSH_CHANNEL_OPEN;
2756 	/* XXX window size? */
2757 	c->local_window = c->local_window_max = c->local_maxpacket * 2;
2758 	packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2759 	packet_put_int(c->remote_id);
2760 	packet_put_int(c->local_window);
2761 	packet_send();
2762 }
2763