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