- djm@cvs.openbsd.org 2006/07/10 12:03:20
[openssh-git.git] / channels.c
blob5796a8bb92c89b7bdc7938b673d85f4eca2c1000
1 /* $OpenBSD: channels.c,v 1.251 2006/07/03 17:59:32 stevesk 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.
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".
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.
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.
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.
42 #include "includes.h"
44 #include <sys/ioctl.h>
45 #include <sys/types.h>
46 #include <sys/un.h>
47 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
52 #include <termios.h>
54 #include "ssh.h"
55 #include "ssh1.h"
56 #include "ssh2.h"
57 #include "packet.h"
58 #include "xmalloc.h"
59 #include "log.h"
60 #include "misc.h"
61 #include "channels.h"
62 #include "compat.h"
63 #include "canohost.h"
64 #include "key.h"
65 #include "authfd.h"
66 #include "pathnames.h"
67 #include "bufaux.h"
69 /* -- channel core */
72 * Pointer to an array containing all allocated channels. The array is
73 * dynamically extended as needed.
75 static Channel **channels = NULL;
78 * Size of the channel array. All slots of the array must always be
79 * initialized (at least the type field); unused slots set to NULL
81 static u_int channels_alloc = 0;
84 * Maximum file descriptor value used in any of the channels. This is
85 * updated in channel_new.
87 static int channel_max_fd = 0;
90 /* -- tcp forwarding */
93 * Data structure for storing which hosts are permitted for forward requests.
94 * The local sides of any remote forwards are stored in this array to prevent
95 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
96 * network (which might be behind a firewall).
98 typedef struct {
99 char *host_to_connect; /* Connect to 'host'. */
100 u_short port_to_connect; /* Connect to 'port'. */
101 u_short listen_port; /* Remote side should listen port number. */
102 } ForwardPermission;
104 /* List of all permitted host/port pairs to connect. */
105 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
107 /* Number of permitted host/port pairs in the array. */
108 static int num_permitted_opens = 0;
110 * If this is true, all opens are permitted. This is the case on the server
111 * on which we have to trust the client anyway, and the user could do
112 * anything after logging in anyway.
114 static int all_opens_permitted = 0;
117 /* -- X11 forwarding */
119 /* Maximum number of fake X11 displays to try. */
120 #define MAX_DISPLAYS 1000
122 /* Saved X11 local (client) display. */
123 static char *x11_saved_display = NULL;
125 /* Saved X11 authentication protocol name. */
126 static char *x11_saved_proto = NULL;
128 /* Saved X11 authentication data. This is the real data. */
129 static char *x11_saved_data = NULL;
130 static u_int x11_saved_data_len = 0;
133 * Fake X11 authentication data. This is what the server will be sending us;
134 * we should replace any occurrences of this by the real data.
136 static u_char *x11_fake_data = NULL;
137 static u_int x11_fake_data_len;
140 /* -- agent forwarding */
142 #define NUM_SOCKS 10
144 /* AF_UNSPEC or AF_INET or AF_INET6 */
145 static int IPv4or6 = AF_UNSPEC;
147 /* helper */
148 static void port_open_helper(Channel *c, char *rtype);
150 /* -- channel core */
152 Channel *
153 channel_by_id(int id)
155 Channel *c;
157 if (id < 0 || (u_int)id >= channels_alloc) {
158 logit("channel_by_id: %d: bad id", id);
159 return NULL;
161 c = channels[id];
162 if (c == NULL) {
163 logit("channel_by_id: %d: bad id: channel free", id);
164 return NULL;
166 return c;
170 * Returns the channel if it is allowed to receive protocol messages.
171 * Private channels, like listening sockets, may not receive messages.
173 Channel *
174 channel_lookup(int id)
176 Channel *c;
178 if ((c = channel_by_id(id)) == NULL)
179 return (NULL);
181 switch (c->type) {
182 case SSH_CHANNEL_X11_OPEN:
183 case SSH_CHANNEL_LARVAL:
184 case SSH_CHANNEL_CONNECTING:
185 case SSH_CHANNEL_DYNAMIC:
186 case SSH_CHANNEL_OPENING:
187 case SSH_CHANNEL_OPEN:
188 case SSH_CHANNEL_INPUT_DRAINING:
189 case SSH_CHANNEL_OUTPUT_DRAINING:
190 return (c);
192 logit("Non-public channel %d, type %d.", id, c->type);
193 return (NULL);
197 * Register filedescriptors for a channel, used when allocating a channel or
198 * when the channel consumer/producer is ready, e.g. shell exec'd
200 static void
201 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
202 int extusage, int nonblock)
204 /* Update the maximum file descriptor value. */
205 channel_max_fd = MAX(channel_max_fd, rfd);
206 channel_max_fd = MAX(channel_max_fd, wfd);
207 channel_max_fd = MAX(channel_max_fd, efd);
209 /* XXX set close-on-exec -markus */
211 c->rfd = rfd;
212 c->wfd = wfd;
213 c->sock = (rfd == wfd) ? rfd : -1;
214 c->ctl_fd = -1; /* XXX: set elsewhere */
215 c->efd = efd;
216 c->extended_usage = extusage;
218 /* XXX ugly hack: nonblock is only set by the server */
219 if (nonblock && isatty(c->rfd)) {
220 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
221 c->isatty = 1;
222 if (!isatty(c->wfd)) {
223 error("channel %d: wfd %d is not a tty?",
224 c->self, c->wfd);
226 } else {
227 c->isatty = 0;
229 c->wfd_isatty = isatty(c->wfd);
231 /* enable nonblocking mode */
232 if (nonblock) {
233 if (rfd != -1)
234 set_nonblock(rfd);
235 if (wfd != -1)
236 set_nonblock(wfd);
237 if (efd != -1)
238 set_nonblock(efd);
243 * Allocate a new channel object and set its type and socket. This will cause
244 * remote_name to be freed.
246 Channel *
247 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
248 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
250 int found;
251 u_int i;
252 Channel *c;
254 /* Do initial allocation if this is the first call. */
255 if (channels_alloc == 0) {
256 channels_alloc = 10;
257 channels = xcalloc(channels_alloc, sizeof(Channel *));
258 for (i = 0; i < channels_alloc; i++)
259 channels[i] = NULL;
261 /* Try to find a free slot where to put the new channel. */
262 for (found = -1, i = 0; i < channels_alloc; i++)
263 if (channels[i] == NULL) {
264 /* Found a free slot. */
265 found = (int)i;
266 break;
268 if (found < 0) {
269 /* There are no free slots. Take last+1 slot and expand the array. */
270 found = channels_alloc;
271 if (channels_alloc > 10000)
272 fatal("channel_new: internal error: channels_alloc %d "
273 "too big.", channels_alloc);
274 channels = xrealloc(channels, channels_alloc + 10,
275 sizeof(Channel *));
276 channels_alloc += 10;
277 debug2("channel: expanding %d", channels_alloc);
278 for (i = found; i < channels_alloc; i++)
279 channels[i] = NULL;
281 /* Initialize and return new channel. */
282 c = channels[found] = xcalloc(1, sizeof(Channel));
283 buffer_init(&c->input);
284 buffer_init(&c->output);
285 buffer_init(&c->extended);
286 c->ostate = CHAN_OUTPUT_OPEN;
287 c->istate = CHAN_INPUT_OPEN;
288 c->flags = 0;
289 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
290 c->self = found;
291 c->type = type;
292 c->ctype = ctype;
293 c->local_window = window;
294 c->local_window_max = window;
295 c->local_consumed = 0;
296 c->local_maxpacket = maxpack;
297 c->remote_id = -1;
298 c->remote_name = xstrdup(remote_name);
299 c->remote_window = 0;
300 c->remote_maxpacket = 0;
301 c->force_drain = 0;
302 c->single_connection = 0;
303 c->detach_user = NULL;
304 c->detach_close = 0;
305 c->confirm = NULL;
306 c->confirm_ctx = NULL;
307 c->input_filter = NULL;
308 c->output_filter = NULL;
309 debug("channel %d: new [%s]", found, remote_name);
310 return c;
313 static int
314 channel_find_maxfd(void)
316 u_int i;
317 int max = 0;
318 Channel *c;
320 for (i = 0; i < channels_alloc; i++) {
321 c = channels[i];
322 if (c != NULL) {
323 max = MAX(max, c->rfd);
324 max = MAX(max, c->wfd);
325 max = MAX(max, c->efd);
328 return max;
332 channel_close_fd(int *fdp)
334 int ret = 0, fd = *fdp;
336 if (fd != -1) {
337 ret = close(fd);
338 *fdp = -1;
339 if (fd == channel_max_fd)
340 channel_max_fd = channel_find_maxfd();
342 return ret;
345 /* Close all channel fd/socket. */
346 static void
347 channel_close_fds(Channel *c)
349 debug3("channel %d: close_fds r %d w %d e %d c %d",
350 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
352 channel_close_fd(&c->sock);
353 channel_close_fd(&c->ctl_fd);
354 channel_close_fd(&c->rfd);
355 channel_close_fd(&c->wfd);
356 channel_close_fd(&c->efd);
359 /* Free the channel and close its fd/socket. */
360 void
361 channel_free(Channel *c)
363 char *s;
364 u_int i, n;
366 for (n = 0, i = 0; i < channels_alloc; i++)
367 if (channels[i])
368 n++;
369 debug("channel %d: free: %s, nchannels %u", c->self,
370 c->remote_name ? c->remote_name : "???", n);
372 s = channel_open_message();
373 debug3("channel %d: status: %s", c->self, s);
374 xfree(s);
376 if (c->sock != -1)
377 shutdown(c->sock, SHUT_RDWR);
378 if (c->ctl_fd != -1)
379 shutdown(c->ctl_fd, SHUT_RDWR);
380 channel_close_fds(c);
381 buffer_free(&c->input);
382 buffer_free(&c->output);
383 buffer_free(&c->extended);
384 if (c->remote_name) {
385 xfree(c->remote_name);
386 c->remote_name = NULL;
388 channels[c->self] = NULL;
389 xfree(c);
392 void
393 channel_free_all(void)
395 u_int i;
397 for (i = 0; i < channels_alloc; i++)
398 if (channels[i] != NULL)
399 channel_free(channels[i]);
403 * Closes the sockets/fds of all channels. This is used to close extra file
404 * descriptors after a fork.
406 void
407 channel_close_all(void)
409 u_int i;
411 for (i = 0; i < channels_alloc; i++)
412 if (channels[i] != NULL)
413 channel_close_fds(channels[i]);
417 * Stop listening to channels.
419 void
420 channel_stop_listening(void)
422 u_int i;
423 Channel *c;
425 for (i = 0; i < channels_alloc; i++) {
426 c = channels[i];
427 if (c != NULL) {
428 switch (c->type) {
429 case SSH_CHANNEL_AUTH_SOCKET:
430 case SSH_CHANNEL_PORT_LISTENER:
431 case SSH_CHANNEL_RPORT_LISTENER:
432 case SSH_CHANNEL_X11_LISTENER:
433 channel_close_fd(&c->sock);
434 channel_free(c);
435 break;
442 * Returns true if no channel has too much buffered data, and false if one or
443 * more channel is overfull.
446 channel_not_very_much_buffered_data(void)
448 u_int i;
449 Channel *c;
451 for (i = 0; i < channels_alloc; i++) {
452 c = channels[i];
453 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
454 #if 0
455 if (!compat20 &&
456 buffer_len(&c->input) > packet_get_maxsize()) {
457 debug2("channel %d: big input buffer %d",
458 c->self, buffer_len(&c->input));
459 return 0;
461 #endif
462 if (buffer_len(&c->output) > packet_get_maxsize()) {
463 debug2("channel %d: big output buffer %u > %u",
464 c->self, buffer_len(&c->output),
465 packet_get_maxsize());
466 return 0;
470 return 1;
473 /* Returns true if any channel is still open. */
475 channel_still_open(void)
477 u_int i;
478 Channel *c;
480 for (i = 0; i < channels_alloc; i++) {
481 c = channels[i];
482 if (c == NULL)
483 continue;
484 switch (c->type) {
485 case SSH_CHANNEL_X11_LISTENER:
486 case SSH_CHANNEL_PORT_LISTENER:
487 case SSH_CHANNEL_RPORT_LISTENER:
488 case SSH_CHANNEL_CLOSED:
489 case SSH_CHANNEL_AUTH_SOCKET:
490 case SSH_CHANNEL_DYNAMIC:
491 case SSH_CHANNEL_CONNECTING:
492 case SSH_CHANNEL_ZOMBIE:
493 continue;
494 case SSH_CHANNEL_LARVAL:
495 if (!compat20)
496 fatal("cannot happen: SSH_CHANNEL_LARVAL");
497 continue;
498 case SSH_CHANNEL_OPENING:
499 case SSH_CHANNEL_OPEN:
500 case SSH_CHANNEL_X11_OPEN:
501 return 1;
502 case SSH_CHANNEL_INPUT_DRAINING:
503 case SSH_CHANNEL_OUTPUT_DRAINING:
504 if (!compat13)
505 fatal("cannot happen: OUT_DRAIN");
506 return 1;
507 default:
508 fatal("channel_still_open: bad channel type %d", c->type);
509 /* NOTREACHED */
512 return 0;
515 /* Returns the id of an open channel suitable for keepaliving */
517 channel_find_open(void)
519 u_int i;
520 Channel *c;
522 for (i = 0; i < channels_alloc; i++) {
523 c = channels[i];
524 if (c == NULL || c->remote_id < 0)
525 continue;
526 switch (c->type) {
527 case SSH_CHANNEL_CLOSED:
528 case SSH_CHANNEL_DYNAMIC:
529 case SSH_CHANNEL_X11_LISTENER:
530 case SSH_CHANNEL_PORT_LISTENER:
531 case SSH_CHANNEL_RPORT_LISTENER:
532 case SSH_CHANNEL_OPENING:
533 case SSH_CHANNEL_CONNECTING:
534 case SSH_CHANNEL_ZOMBIE:
535 continue;
536 case SSH_CHANNEL_LARVAL:
537 case SSH_CHANNEL_AUTH_SOCKET:
538 case SSH_CHANNEL_OPEN:
539 case SSH_CHANNEL_X11_OPEN:
540 return i;
541 case SSH_CHANNEL_INPUT_DRAINING:
542 case SSH_CHANNEL_OUTPUT_DRAINING:
543 if (!compat13)
544 fatal("cannot happen: OUT_DRAIN");
545 return i;
546 default:
547 fatal("channel_find_open: bad channel type %d", c->type);
548 /* NOTREACHED */
551 return -1;
556 * Returns a message describing the currently open forwarded connections,
557 * suitable for sending to the client. The message contains crlf pairs for
558 * newlines.
560 char *
561 channel_open_message(void)
563 Buffer buffer;
564 Channel *c;
565 char buf[1024], *cp;
566 u_int i;
568 buffer_init(&buffer);
569 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
570 buffer_append(&buffer, buf, strlen(buf));
571 for (i = 0; i < channels_alloc; i++) {
572 c = channels[i];
573 if (c == NULL)
574 continue;
575 switch (c->type) {
576 case SSH_CHANNEL_X11_LISTENER:
577 case SSH_CHANNEL_PORT_LISTENER:
578 case SSH_CHANNEL_RPORT_LISTENER:
579 case SSH_CHANNEL_CLOSED:
580 case SSH_CHANNEL_AUTH_SOCKET:
581 case SSH_CHANNEL_ZOMBIE:
582 continue;
583 case SSH_CHANNEL_LARVAL:
584 case SSH_CHANNEL_OPENING:
585 case SSH_CHANNEL_CONNECTING:
586 case SSH_CHANNEL_DYNAMIC:
587 case SSH_CHANNEL_OPEN:
588 case SSH_CHANNEL_X11_OPEN:
589 case SSH_CHANNEL_INPUT_DRAINING:
590 case SSH_CHANNEL_OUTPUT_DRAINING:
591 snprintf(buf, sizeof buf,
592 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
593 c->self, c->remote_name,
594 c->type, c->remote_id,
595 c->istate, buffer_len(&c->input),
596 c->ostate, buffer_len(&c->output),
597 c->rfd, c->wfd, c->ctl_fd);
598 buffer_append(&buffer, buf, strlen(buf));
599 continue;
600 default:
601 fatal("channel_open_message: bad channel type %d", c->type);
602 /* NOTREACHED */
605 buffer_append(&buffer, "\0", 1);
606 cp = xstrdup(buffer_ptr(&buffer));
607 buffer_free(&buffer);
608 return cp;
611 void
612 channel_send_open(int id)
614 Channel *c = channel_lookup(id);
616 if (c == NULL) {
617 logit("channel_send_open: %d: bad id", id);
618 return;
620 debug2("channel %d: send open", id);
621 packet_start(SSH2_MSG_CHANNEL_OPEN);
622 packet_put_cstring(c->ctype);
623 packet_put_int(c->self);
624 packet_put_int(c->local_window);
625 packet_put_int(c->local_maxpacket);
626 packet_send();
629 void
630 channel_request_start(int id, char *service, int wantconfirm)
632 Channel *c = channel_lookup(id);
634 if (c == NULL) {
635 logit("channel_request_start: %d: unknown channel id", id);
636 return;
638 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
639 packet_start(SSH2_MSG_CHANNEL_REQUEST);
640 packet_put_int(c->remote_id);
641 packet_put_cstring(service);
642 packet_put_char(wantconfirm);
645 void
646 channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
648 Channel *c = channel_lookup(id);
650 if (c == NULL) {
651 logit("channel_register_comfirm: %d: bad id", id);
652 return;
654 c->confirm = fn;
655 c->confirm_ctx = ctx;
658 void
659 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
661 Channel *c = channel_by_id(id);
663 if (c == NULL) {
664 logit("channel_register_cleanup: %d: bad id", id);
665 return;
667 c->detach_user = fn;
668 c->detach_close = do_close;
671 void
672 channel_cancel_cleanup(int id)
674 Channel *c = channel_by_id(id);
676 if (c == NULL) {
677 logit("channel_cancel_cleanup: %d: bad id", id);
678 return;
680 c->detach_user = NULL;
681 c->detach_close = 0;
684 void
685 channel_register_filter(int id, channel_infilter_fn *ifn,
686 channel_outfilter_fn *ofn)
688 Channel *c = channel_lookup(id);
690 if (c == NULL) {
691 logit("channel_register_filter: %d: bad id", id);
692 return;
694 c->input_filter = ifn;
695 c->output_filter = ofn;
698 void
699 channel_set_fds(int id, int rfd, int wfd, int efd,
700 int extusage, int nonblock, u_int window_max)
702 Channel *c = channel_lookup(id);
704 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
705 fatal("channel_activate for non-larval channel %d.", id);
706 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
707 c->type = SSH_CHANNEL_OPEN;
708 c->local_window = c->local_window_max = window_max;
709 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
710 packet_put_int(c->remote_id);
711 packet_put_int(c->local_window);
712 packet_send();
716 * 'channel_pre*' are called just before select() to add any bits relevant to
717 * channels in the select bitmasks.
720 * 'channel_post*': perform any appropriate operations for channels which
721 * have events pending.
723 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
724 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
725 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
727 static void
728 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
730 FD_SET(c->sock, readset);
733 static void
734 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
736 debug3("channel %d: waiting for connection", c->self);
737 FD_SET(c->sock, writeset);
740 static void
741 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
743 if (buffer_len(&c->input) < packet_get_maxsize())
744 FD_SET(c->sock, readset);
745 if (buffer_len(&c->output) > 0)
746 FD_SET(c->sock, writeset);
749 static void
750 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
752 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
754 if (c->istate == CHAN_INPUT_OPEN &&
755 limit > 0 &&
756 buffer_len(&c->input) < limit &&
757 buffer_check_alloc(&c->input, CHAN_RBUF))
758 FD_SET(c->rfd, readset);
759 if (c->ostate == CHAN_OUTPUT_OPEN ||
760 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
761 if (buffer_len(&c->output) > 0) {
762 FD_SET(c->wfd, writeset);
763 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
764 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
765 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
766 c->self, c->efd, buffer_len(&c->extended));
767 else
768 chan_obuf_empty(c);
771 /** XXX check close conditions, too */
772 if (compat20 && c->efd != -1) {
773 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
774 buffer_len(&c->extended) > 0)
775 FD_SET(c->efd, writeset);
776 else if (!(c->flags & CHAN_EOF_SENT) &&
777 c->extended_usage == CHAN_EXTENDED_READ &&
778 buffer_len(&c->extended) < c->remote_window)
779 FD_SET(c->efd, readset);
781 /* XXX: What about efd? races? */
782 if (compat20 && c->ctl_fd != -1 &&
783 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
784 FD_SET(c->ctl_fd, readset);
787 static void
788 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
790 if (buffer_len(&c->input) == 0) {
791 packet_start(SSH_MSG_CHANNEL_CLOSE);
792 packet_put_int(c->remote_id);
793 packet_send();
794 c->type = SSH_CHANNEL_CLOSED;
795 debug2("channel %d: closing after input drain.", c->self);
799 static void
800 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
802 if (buffer_len(&c->output) == 0)
803 chan_mark_dead(c);
804 else
805 FD_SET(c->sock, writeset);
809 * This is a special state for X11 authentication spoofing. An opened X11
810 * connection (when authentication spoofing is being done) remains in this
811 * state until the first packet has been completely read. The authentication
812 * data in that packet is then substituted by the real data if it matches the
813 * fake data, and the channel is put into normal mode.
814 * XXX All this happens at the client side.
815 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
817 static int
818 x11_open_helper(Buffer *b)
820 u_char *ucp;
821 u_int proto_len, data_len;
823 /* Check if the fixed size part of the packet is in buffer. */
824 if (buffer_len(b) < 12)
825 return 0;
827 /* Parse the lengths of variable-length fields. */
828 ucp = buffer_ptr(b);
829 if (ucp[0] == 0x42) { /* Byte order MSB first. */
830 proto_len = 256 * ucp[6] + ucp[7];
831 data_len = 256 * ucp[8] + ucp[9];
832 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
833 proto_len = ucp[6] + 256 * ucp[7];
834 data_len = ucp[8] + 256 * ucp[9];
835 } else {
836 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
837 ucp[0]);
838 return -1;
841 /* Check if the whole packet is in buffer. */
842 if (buffer_len(b) <
843 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
844 return 0;
846 /* Check if authentication protocol matches. */
847 if (proto_len != strlen(x11_saved_proto) ||
848 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
849 debug2("X11 connection uses different authentication protocol.");
850 return -1;
852 /* Check if authentication data matches our fake data. */
853 if (data_len != x11_fake_data_len ||
854 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
855 x11_fake_data, x11_fake_data_len) != 0) {
856 debug2("X11 auth data does not match fake data.");
857 return -1;
859 /* Check fake data length */
860 if (x11_fake_data_len != x11_saved_data_len) {
861 error("X11 fake_data_len %d != saved_data_len %d",
862 x11_fake_data_len, x11_saved_data_len);
863 return -1;
866 * Received authentication protocol and data match
867 * our fake data. Substitute the fake data with real
868 * data.
870 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
871 x11_saved_data, x11_saved_data_len);
872 return 1;
875 static void
876 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
878 int ret = x11_open_helper(&c->output);
880 if (ret == 1) {
881 /* Start normal processing for the channel. */
882 c->type = SSH_CHANNEL_OPEN;
883 channel_pre_open_13(c, readset, writeset);
884 } else if (ret == -1) {
886 * We have received an X11 connection that has bad
887 * authentication information.
889 logit("X11 connection rejected because of wrong authentication.");
890 buffer_clear(&c->input);
891 buffer_clear(&c->output);
892 channel_close_fd(&c->sock);
893 c->sock = -1;
894 c->type = SSH_CHANNEL_CLOSED;
895 packet_start(SSH_MSG_CHANNEL_CLOSE);
896 packet_put_int(c->remote_id);
897 packet_send();
901 static void
902 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
904 int ret = x11_open_helper(&c->output);
906 /* c->force_drain = 1; */
908 if (ret == 1) {
909 c->type = SSH_CHANNEL_OPEN;
910 channel_pre_open(c, readset, writeset);
911 } else if (ret == -1) {
912 logit("X11 connection rejected because of wrong authentication.");
913 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
914 chan_read_failed(c);
915 buffer_clear(&c->input);
916 chan_ibuf_empty(c);
917 buffer_clear(&c->output);
918 /* for proto v1, the peer will send an IEOF */
919 if (compat20)
920 chan_write_failed(c);
921 else
922 c->type = SSH_CHANNEL_OPEN;
923 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
927 /* try to decode a socks4 header */
928 static int
929 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
931 char *p, *host;
932 u_int len, have, i, found;
933 char username[256];
934 struct {
935 u_int8_t version;
936 u_int8_t command;
937 u_int16_t dest_port;
938 struct in_addr dest_addr;
939 } s4_req, s4_rsp;
941 debug2("channel %d: decode socks4", c->self);
943 have = buffer_len(&c->input);
944 len = sizeof(s4_req);
945 if (have < len)
946 return 0;
947 p = buffer_ptr(&c->input);
948 for (found = 0, i = len; i < have; i++) {
949 if (p[i] == '\0') {
950 found = 1;
951 break;
953 if (i > 1024) {
954 /* the peer is probably sending garbage */
955 debug("channel %d: decode socks4: too long",
956 c->self);
957 return -1;
960 if (!found)
961 return 0;
962 buffer_get(&c->input, (char *)&s4_req.version, 1);
963 buffer_get(&c->input, (char *)&s4_req.command, 1);
964 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
965 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
966 have = buffer_len(&c->input);
967 p = buffer_ptr(&c->input);
968 len = strlen(p);
969 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
970 if (len > have)
971 fatal("channel %d: decode socks4: len %d > have %d",
972 c->self, len, have);
973 strlcpy(username, p, sizeof(username));
974 buffer_consume(&c->input, len);
975 buffer_consume(&c->input, 1); /* trailing '\0' */
977 host = inet_ntoa(s4_req.dest_addr);
978 strlcpy(c->path, host, sizeof(c->path));
979 c->host_port = ntohs(s4_req.dest_port);
981 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
982 c->self, host, c->host_port, s4_req.command);
984 if (s4_req.command != 1) {
985 debug("channel %d: cannot handle: socks4 cn %d",
986 c->self, s4_req.command);
987 return -1;
989 s4_rsp.version = 0; /* vn: 0 for reply */
990 s4_rsp.command = 90; /* cd: req granted */
991 s4_rsp.dest_port = 0; /* ignored */
992 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
993 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
994 return 1;
997 /* try to decode a socks5 header */
998 #define SSH_SOCKS5_AUTHDONE 0x1000
999 #define SSH_SOCKS5_NOAUTH 0x00
1000 #define SSH_SOCKS5_IPV4 0x01
1001 #define SSH_SOCKS5_DOMAIN 0x03
1002 #define SSH_SOCKS5_IPV6 0x04
1003 #define SSH_SOCKS5_CONNECT 0x01
1004 #define SSH_SOCKS5_SUCCESS 0x00
1006 static int
1007 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1009 struct {
1010 u_int8_t version;
1011 u_int8_t command;
1012 u_int8_t reserved;
1013 u_int8_t atyp;
1014 } s5_req, s5_rsp;
1015 u_int16_t dest_port;
1016 u_char *p, dest_addr[255+1];
1017 u_int have, i, found, nmethods, addrlen, af;
1019 debug2("channel %d: decode socks5", c->self);
1020 p = buffer_ptr(&c->input);
1021 if (p[0] != 0x05)
1022 return -1;
1023 have = buffer_len(&c->input);
1024 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1025 /* format: ver | nmethods | methods */
1026 if (have < 2)
1027 return 0;
1028 nmethods = p[1];
1029 if (have < nmethods + 2)
1030 return 0;
1031 /* look for method: "NO AUTHENTICATION REQUIRED" */
1032 for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1033 if (p[i] == SSH_SOCKS5_NOAUTH ) {
1034 found = 1;
1035 break;
1038 if (!found) {
1039 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1040 c->self);
1041 return -1;
1043 buffer_consume(&c->input, nmethods + 2);
1044 buffer_put_char(&c->output, 0x05); /* version */
1045 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1046 FD_SET(c->sock, writeset);
1047 c->flags |= SSH_SOCKS5_AUTHDONE;
1048 debug2("channel %d: socks5 auth done", c->self);
1049 return 0; /* need more */
1051 debug2("channel %d: socks5 post auth", c->self);
1052 if (have < sizeof(s5_req)+1)
1053 return 0; /* need more */
1054 memcpy(&s5_req, p, sizeof(s5_req));
1055 if (s5_req.version != 0x05 ||
1056 s5_req.command != SSH_SOCKS5_CONNECT ||
1057 s5_req.reserved != 0x00) {
1058 debug2("channel %d: only socks5 connect supported", c->self);
1059 return -1;
1061 switch (s5_req.atyp){
1062 case SSH_SOCKS5_IPV4:
1063 addrlen = 4;
1064 af = AF_INET;
1065 break;
1066 case SSH_SOCKS5_DOMAIN:
1067 addrlen = p[sizeof(s5_req)];
1068 af = -1;
1069 break;
1070 case SSH_SOCKS5_IPV6:
1071 addrlen = 16;
1072 af = AF_INET6;
1073 break;
1074 default:
1075 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1076 return -1;
1078 if (have < 4 + addrlen + 2)
1079 return 0;
1080 buffer_consume(&c->input, sizeof(s5_req));
1081 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1082 buffer_consume(&c->input, 1); /* host string length */
1083 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1084 buffer_get(&c->input, (char *)&dest_port, 2);
1085 dest_addr[addrlen] = '\0';
1086 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1087 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1088 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1089 return -1;
1090 c->host_port = ntohs(dest_port);
1092 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1093 c->self, c->path, c->host_port, s5_req.command);
1095 s5_rsp.version = 0x05;
1096 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1097 s5_rsp.reserved = 0; /* ignored */
1098 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1099 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1100 dest_port = 0; /* ignored */
1102 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1103 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1104 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1105 return 1;
1108 /* dynamic port forwarding */
1109 static void
1110 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1112 u_char *p;
1113 u_int have;
1114 int ret;
1116 have = buffer_len(&c->input);
1117 c->delayed = 0;
1118 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1119 /* buffer_dump(&c->input); */
1120 /* check if the fixed size part of the packet is in buffer. */
1121 if (have < 3) {
1122 /* need more */
1123 FD_SET(c->sock, readset);
1124 return;
1126 /* try to guess the protocol */
1127 p = buffer_ptr(&c->input);
1128 switch (p[0]) {
1129 case 0x04:
1130 ret = channel_decode_socks4(c, readset, writeset);
1131 break;
1132 case 0x05:
1133 ret = channel_decode_socks5(c, readset, writeset);
1134 break;
1135 default:
1136 ret = -1;
1137 break;
1139 if (ret < 0) {
1140 chan_mark_dead(c);
1141 } else if (ret == 0) {
1142 debug2("channel %d: pre_dynamic: need more", c->self);
1143 /* need more */
1144 FD_SET(c->sock, readset);
1145 } else {
1146 /* switch to the next state */
1147 c->type = SSH_CHANNEL_OPENING;
1148 port_open_helper(c, "direct-tcpip");
1152 /* This is our fake X11 server socket. */
1153 static void
1154 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1156 Channel *nc;
1157 struct sockaddr addr;
1158 int newsock;
1159 socklen_t addrlen;
1160 char buf[16384], *remote_ipaddr;
1161 int remote_port;
1163 if (FD_ISSET(c->sock, readset)) {
1164 debug("X11 connection requested.");
1165 addrlen = sizeof(addr);
1166 newsock = accept(c->sock, &addr, &addrlen);
1167 if (c->single_connection) {
1168 debug2("single_connection: closing X11 listener.");
1169 channel_close_fd(&c->sock);
1170 chan_mark_dead(c);
1172 if (newsock < 0) {
1173 error("accept: %.100s", strerror(errno));
1174 return;
1176 set_nodelay(newsock);
1177 remote_ipaddr = get_peer_ipaddr(newsock);
1178 remote_port = get_peer_port(newsock);
1179 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1180 remote_ipaddr, remote_port);
1182 nc = channel_new("accepted x11 socket",
1183 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1184 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1185 if (compat20) {
1186 packet_start(SSH2_MSG_CHANNEL_OPEN);
1187 packet_put_cstring("x11");
1188 packet_put_int(nc->self);
1189 packet_put_int(nc->local_window_max);
1190 packet_put_int(nc->local_maxpacket);
1191 /* originator ipaddr and port */
1192 packet_put_cstring(remote_ipaddr);
1193 if (datafellows & SSH_BUG_X11FWD) {
1194 debug2("ssh2 x11 bug compat mode");
1195 } else {
1196 packet_put_int(remote_port);
1198 packet_send();
1199 } else {
1200 packet_start(SSH_SMSG_X11_OPEN);
1201 packet_put_int(nc->self);
1202 if (packet_get_protocol_flags() &
1203 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1204 packet_put_cstring(buf);
1205 packet_send();
1207 xfree(remote_ipaddr);
1211 static void
1212 port_open_helper(Channel *c, char *rtype)
1214 int direct;
1215 char buf[1024];
1216 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1217 int remote_port = get_peer_port(c->sock);
1219 direct = (strcmp(rtype, "direct-tcpip") == 0);
1221 snprintf(buf, sizeof buf,
1222 "%s: listening port %d for %.100s port %d, "
1223 "connect from %.200s port %d",
1224 rtype, c->listening_port, c->path, c->host_port,
1225 remote_ipaddr, remote_port);
1227 xfree(c->remote_name);
1228 c->remote_name = xstrdup(buf);
1230 if (compat20) {
1231 packet_start(SSH2_MSG_CHANNEL_OPEN);
1232 packet_put_cstring(rtype);
1233 packet_put_int(c->self);
1234 packet_put_int(c->local_window_max);
1235 packet_put_int(c->local_maxpacket);
1236 if (direct) {
1237 /* target host, port */
1238 packet_put_cstring(c->path);
1239 packet_put_int(c->host_port);
1240 } else {
1241 /* listen address, port */
1242 packet_put_cstring(c->path);
1243 packet_put_int(c->listening_port);
1245 /* originator host and port */
1246 packet_put_cstring(remote_ipaddr);
1247 packet_put_int((u_int)remote_port);
1248 packet_send();
1249 } else {
1250 packet_start(SSH_MSG_PORT_OPEN);
1251 packet_put_int(c->self);
1252 packet_put_cstring(c->path);
1253 packet_put_int(c->host_port);
1254 if (packet_get_protocol_flags() &
1255 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1256 packet_put_cstring(c->remote_name);
1257 packet_send();
1259 xfree(remote_ipaddr);
1262 static void
1263 channel_set_reuseaddr(int fd)
1265 int on = 1;
1268 * Set socket options.
1269 * Allow local port reuse in TIME_WAIT.
1271 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1272 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1276 * This socket is listening for connections to a forwarded TCP/IP port.
1278 static void
1279 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1281 Channel *nc;
1282 struct sockaddr addr;
1283 int newsock, nextstate;
1284 socklen_t addrlen;
1285 char *rtype;
1287 if (FD_ISSET(c->sock, readset)) {
1288 debug("Connection to port %d forwarding "
1289 "to %.100s port %d requested.",
1290 c->listening_port, c->path, c->host_port);
1292 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1293 nextstate = SSH_CHANNEL_OPENING;
1294 rtype = "forwarded-tcpip";
1295 } else {
1296 if (c->host_port == 0) {
1297 nextstate = SSH_CHANNEL_DYNAMIC;
1298 rtype = "dynamic-tcpip";
1299 } else {
1300 nextstate = SSH_CHANNEL_OPENING;
1301 rtype = "direct-tcpip";
1305 addrlen = sizeof(addr);
1306 newsock = accept(c->sock, &addr, &addrlen);
1307 if (newsock < 0) {
1308 error("accept: %.100s", strerror(errno));
1309 return;
1311 set_nodelay(newsock);
1312 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1313 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1314 nc->listening_port = c->listening_port;
1315 nc->host_port = c->host_port;
1316 strlcpy(nc->path, c->path, sizeof(nc->path));
1318 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1320 * do not call the channel_post handler until
1321 * this flag has been reset by a pre-handler.
1322 * otherwise the FD_ISSET calls might overflow
1324 nc->delayed = 1;
1325 } else {
1326 port_open_helper(nc, rtype);
1332 * This is the authentication agent socket listening for connections from
1333 * clients.
1335 static void
1336 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1338 Channel *nc;
1339 int newsock;
1340 struct sockaddr addr;
1341 socklen_t addrlen;
1343 if (FD_ISSET(c->sock, readset)) {
1344 addrlen = sizeof(addr);
1345 newsock = accept(c->sock, &addr, &addrlen);
1346 if (newsock < 0) {
1347 error("accept from auth socket: %.100s", strerror(errno));
1348 return;
1350 nc = channel_new("accepted auth socket",
1351 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1352 c->local_window_max, c->local_maxpacket,
1353 0, "accepted auth socket", 1);
1354 if (compat20) {
1355 packet_start(SSH2_MSG_CHANNEL_OPEN);
1356 packet_put_cstring("auth-agent@openssh.com");
1357 packet_put_int(nc->self);
1358 packet_put_int(c->local_window_max);
1359 packet_put_int(c->local_maxpacket);
1360 } else {
1361 packet_start(SSH_SMSG_AGENT_OPEN);
1362 packet_put_int(nc->self);
1364 packet_send();
1368 static void
1369 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1371 int err = 0;
1372 socklen_t sz = sizeof(err);
1374 if (FD_ISSET(c->sock, writeset)) {
1375 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1376 err = errno;
1377 error("getsockopt SO_ERROR failed");
1379 if (err == 0) {
1380 debug("channel %d: connected", c->self);
1381 c->type = SSH_CHANNEL_OPEN;
1382 if (compat20) {
1383 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1384 packet_put_int(c->remote_id);
1385 packet_put_int(c->self);
1386 packet_put_int(c->local_window);
1387 packet_put_int(c->local_maxpacket);
1388 } else {
1389 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1390 packet_put_int(c->remote_id);
1391 packet_put_int(c->self);
1393 } else {
1394 debug("channel %d: not connected: %s",
1395 c->self, strerror(err));
1396 if (compat20) {
1397 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1398 packet_put_int(c->remote_id);
1399 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1400 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1401 packet_put_cstring(strerror(err));
1402 packet_put_cstring("");
1404 } else {
1405 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1406 packet_put_int(c->remote_id);
1408 chan_mark_dead(c);
1410 packet_send();
1414 static int
1415 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1417 char buf[CHAN_RBUF];
1418 int len;
1420 if (c->rfd != -1 &&
1421 FD_ISSET(c->rfd, readset)) {
1422 errno = 0;
1423 len = read(c->rfd, buf, sizeof(buf));
1424 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1425 return 1;
1426 #ifndef PTY_ZEROREAD
1427 if (len <= 0) {
1428 #else
1429 if ((!c->isatty && len <= 0) ||
1430 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1431 #endif
1432 debug2("channel %d: read<=0 rfd %d len %d",
1433 c->self, c->rfd, len);
1434 if (c->type != SSH_CHANNEL_OPEN) {
1435 debug2("channel %d: not open", c->self);
1436 chan_mark_dead(c);
1437 return -1;
1438 } else if (compat13) {
1439 buffer_clear(&c->output);
1440 c->type = SSH_CHANNEL_INPUT_DRAINING;
1441 debug2("channel %d: input draining.", c->self);
1442 } else {
1443 chan_read_failed(c);
1445 return -1;
1447 if (c->input_filter != NULL) {
1448 if (c->input_filter(c, buf, len) == -1) {
1449 debug2("channel %d: filter stops", c->self);
1450 chan_read_failed(c);
1452 } else if (c->datagram) {
1453 buffer_put_string(&c->input, buf, len);
1454 } else {
1455 buffer_append(&c->input, buf, len);
1458 return 1;
1461 static int
1462 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1464 struct termios tio;
1465 u_char *data = NULL, *buf;
1466 u_int dlen;
1467 int len;
1469 /* Send buffered output data to the socket. */
1470 if (c->wfd != -1 &&
1471 FD_ISSET(c->wfd, writeset) &&
1472 buffer_len(&c->output) > 0) {
1473 if (c->output_filter != NULL) {
1474 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1475 debug2("channel %d: filter stops", c->self);
1476 if (c->type != SSH_CHANNEL_OPEN)
1477 chan_mark_dead(c);
1478 else
1479 chan_write_failed(c);
1480 return -1;
1482 } else if (c->datagram) {
1483 buf = data = buffer_get_string(&c->output, &dlen);
1484 } else {
1485 buf = data = buffer_ptr(&c->output);
1486 dlen = buffer_len(&c->output);
1489 if (c->datagram) {
1490 /* ignore truncated writes, datagrams might get lost */
1491 c->local_consumed += dlen + 4;
1492 len = write(c->wfd, buf, dlen);
1493 xfree(data);
1494 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1495 return 1;
1496 if (len <= 0) {
1497 if (c->type != SSH_CHANNEL_OPEN)
1498 chan_mark_dead(c);
1499 else
1500 chan_write_failed(c);
1501 return -1;
1503 return 1;
1505 #ifdef _AIX
1506 /* XXX: Later AIX versions can't push as much data to tty */
1507 if (compat20 && c->wfd_isatty)
1508 dlen = MIN(dlen, 8*1024);
1509 #endif
1511 len = write(c->wfd, buf, dlen);
1512 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1513 return 1;
1514 if (len <= 0) {
1515 if (c->type != SSH_CHANNEL_OPEN) {
1516 debug2("channel %d: not open", c->self);
1517 chan_mark_dead(c);
1518 return -1;
1519 } else if (compat13) {
1520 buffer_clear(&c->output);
1521 debug2("channel %d: input draining.", c->self);
1522 c->type = SSH_CHANNEL_INPUT_DRAINING;
1523 } else {
1524 chan_write_failed(c);
1526 return -1;
1528 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1529 if (tcgetattr(c->wfd, &tio) == 0 &&
1530 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1532 * Simulate echo to reduce the impact of
1533 * traffic analysis. We need to match the
1534 * size of a SSH2_MSG_CHANNEL_DATA message
1535 * (4 byte channel id + buf)
1537 packet_send_ignore(4 + len);
1538 packet_send();
1541 buffer_consume(&c->output, len);
1542 if (compat20 && len > 0) {
1543 c->local_consumed += len;
1546 return 1;
1549 static int
1550 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1552 char buf[CHAN_RBUF];
1553 int len;
1555 /** XXX handle drain efd, too */
1556 if (c->efd != -1) {
1557 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1558 FD_ISSET(c->efd, writeset) &&
1559 buffer_len(&c->extended) > 0) {
1560 len = write(c->efd, buffer_ptr(&c->extended),
1561 buffer_len(&c->extended));
1562 debug2("channel %d: written %d to efd %d",
1563 c->self, len, c->efd);
1564 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1565 return 1;
1566 if (len <= 0) {
1567 debug2("channel %d: closing write-efd %d",
1568 c->self, c->efd);
1569 channel_close_fd(&c->efd);
1570 } else {
1571 buffer_consume(&c->extended, len);
1572 c->local_consumed += len;
1574 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1575 FD_ISSET(c->efd, readset)) {
1576 len = read(c->efd, buf, sizeof(buf));
1577 debug2("channel %d: read %d from efd %d",
1578 c->self, len, c->efd);
1579 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1580 return 1;
1581 if (len <= 0) {
1582 debug2("channel %d: closing read-efd %d",
1583 c->self, c->efd);
1584 channel_close_fd(&c->efd);
1585 } else {
1586 buffer_append(&c->extended, buf, len);
1590 return 1;
1593 static int
1594 channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
1596 char buf[16];
1597 int len;
1599 /* Monitor control fd to detect if the slave client exits */
1600 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1601 len = read(c->ctl_fd, buf, sizeof(buf));
1602 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1603 return 1;
1604 if (len <= 0) {
1605 debug2("channel %d: ctl read<=0", c->self);
1606 if (c->type != SSH_CHANNEL_OPEN) {
1607 debug2("channel %d: not open", c->self);
1608 chan_mark_dead(c);
1609 return -1;
1610 } else {
1611 chan_read_failed(c);
1612 chan_write_failed(c);
1614 return -1;
1615 } else
1616 fatal("%s: unexpected data on ctl fd", __func__);
1618 return 1;
1621 static int
1622 channel_check_window(Channel *c)
1624 if (c->type == SSH_CHANNEL_OPEN &&
1625 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1626 c->local_window < c->local_window_max/2 &&
1627 c->local_consumed > 0) {
1628 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1629 packet_put_int(c->remote_id);
1630 packet_put_int(c->local_consumed);
1631 packet_send();
1632 debug2("channel %d: window %d sent adjust %d",
1633 c->self, c->local_window,
1634 c->local_consumed);
1635 c->local_window += c->local_consumed;
1636 c->local_consumed = 0;
1638 return 1;
1641 static void
1642 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1644 if (c->delayed)
1645 return;
1646 channel_handle_rfd(c, readset, writeset);
1647 channel_handle_wfd(c, readset, writeset);
1648 if (!compat20)
1649 return;
1650 channel_handle_efd(c, readset, writeset);
1651 channel_handle_ctl(c, readset, writeset);
1652 channel_check_window(c);
1655 static void
1656 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1658 int len;
1660 /* Send buffered output data to the socket. */
1661 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1662 len = write(c->sock, buffer_ptr(&c->output),
1663 buffer_len(&c->output));
1664 if (len <= 0)
1665 buffer_clear(&c->output);
1666 else
1667 buffer_consume(&c->output, len);
1671 static void
1672 channel_handler_init_20(void)
1674 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1675 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1676 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1677 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1678 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1679 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1680 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1681 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1683 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1684 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1685 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1686 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1687 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1688 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1689 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1692 static void
1693 channel_handler_init_13(void)
1695 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1696 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1697 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1698 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1699 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1700 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1701 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1702 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1703 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1705 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1706 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1707 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1708 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1709 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1710 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1711 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1714 static void
1715 channel_handler_init_15(void)
1717 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1718 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1719 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1720 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1721 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1722 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1723 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1725 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1726 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1727 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1728 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1729 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1730 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1733 static void
1734 channel_handler_init(void)
1736 int i;
1738 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1739 channel_pre[i] = NULL;
1740 channel_post[i] = NULL;
1742 if (compat20)
1743 channel_handler_init_20();
1744 else if (compat13)
1745 channel_handler_init_13();
1746 else
1747 channel_handler_init_15();
1750 /* gc dead channels */
1751 static void
1752 channel_garbage_collect(Channel *c)
1754 if (c == NULL)
1755 return;
1756 if (c->detach_user != NULL) {
1757 if (!chan_is_dead(c, c->detach_close))
1758 return;
1759 debug2("channel %d: gc: notify user", c->self);
1760 c->detach_user(c->self, NULL);
1761 /* if we still have a callback */
1762 if (c->detach_user != NULL)
1763 return;
1764 debug2("channel %d: gc: user detached", c->self);
1766 if (!chan_is_dead(c, 1))
1767 return;
1768 debug2("channel %d: garbage collecting", c->self);
1769 channel_free(c);
1772 static void
1773 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1775 static int did_init = 0;
1776 u_int i;
1777 Channel *c;
1779 if (!did_init) {
1780 channel_handler_init();
1781 did_init = 1;
1783 for (i = 0; i < channels_alloc; i++) {
1784 c = channels[i];
1785 if (c == NULL)
1786 continue;
1787 if (ftab[c->type] != NULL)
1788 (*ftab[c->type])(c, readset, writeset);
1789 channel_garbage_collect(c);
1794 * Allocate/update select bitmasks and add any bits relevant to channels in
1795 * select bitmasks.
1797 void
1798 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1799 u_int *nallocp, int rekeying)
1801 u_int n, sz, nfdset;
1803 n = MAX(*maxfdp, channel_max_fd);
1805 nfdset = howmany(n+1, NFDBITS);
1806 /* Explicitly test here, because xrealloc isn't always called */
1807 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
1808 fatal("channel_prepare_select: max_fd (%d) is too large", n);
1809 sz = nfdset * sizeof(fd_mask);
1811 /* perhaps check sz < nalloc/2 and shrink? */
1812 if (*readsetp == NULL || sz > *nallocp) {
1813 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
1814 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1815 *nallocp = sz;
1817 *maxfdp = n;
1818 memset(*readsetp, 0, sz);
1819 memset(*writesetp, 0, sz);
1821 if (!rekeying)
1822 channel_handler(channel_pre, *readsetp, *writesetp);
1826 * After select, perform any appropriate operations for channels which have
1827 * events pending.
1829 void
1830 channel_after_select(fd_set *readset, fd_set *writeset)
1832 channel_handler(channel_post, readset, writeset);
1836 /* If there is data to send to the connection, enqueue some of it now. */
1837 void
1838 channel_output_poll(void)
1840 Channel *c;
1841 u_int i, len;
1843 for (i = 0; i < channels_alloc; i++) {
1844 c = channels[i];
1845 if (c == NULL)
1846 continue;
1849 * We are only interested in channels that can have buffered
1850 * incoming data.
1852 if (compat13) {
1853 if (c->type != SSH_CHANNEL_OPEN &&
1854 c->type != SSH_CHANNEL_INPUT_DRAINING)
1855 continue;
1856 } else {
1857 if (c->type != SSH_CHANNEL_OPEN)
1858 continue;
1860 if (compat20 &&
1861 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1862 /* XXX is this true? */
1863 debug3("channel %d: will not send data after close", c->self);
1864 continue;
1867 /* Get the amount of buffered data for this channel. */
1868 if ((c->istate == CHAN_INPUT_OPEN ||
1869 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1870 (len = buffer_len(&c->input)) > 0) {
1871 if (c->datagram) {
1872 if (len > 0) {
1873 u_char *data;
1874 u_int dlen;
1876 data = buffer_get_string(&c->input,
1877 &dlen);
1878 packet_start(SSH2_MSG_CHANNEL_DATA);
1879 packet_put_int(c->remote_id);
1880 packet_put_string(data, dlen);
1881 packet_send();
1882 c->remote_window -= dlen + 4;
1883 xfree(data);
1885 continue;
1888 * Send some data for the other side over the secure
1889 * connection.
1891 if (compat20) {
1892 if (len > c->remote_window)
1893 len = c->remote_window;
1894 if (len > c->remote_maxpacket)
1895 len = c->remote_maxpacket;
1896 } else {
1897 if (packet_is_interactive()) {
1898 if (len > 1024)
1899 len = 512;
1900 } else {
1901 /* Keep the packets at reasonable size. */
1902 if (len > packet_get_maxsize()/2)
1903 len = packet_get_maxsize()/2;
1906 if (len > 0) {
1907 packet_start(compat20 ?
1908 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1909 packet_put_int(c->remote_id);
1910 packet_put_string(buffer_ptr(&c->input), len);
1911 packet_send();
1912 buffer_consume(&c->input, len);
1913 c->remote_window -= len;
1915 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1916 if (compat13)
1917 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1919 * input-buffer is empty and read-socket shutdown:
1920 * tell peer, that we will not send more data: send IEOF.
1921 * hack for extended data: delay EOF if EFD still in use.
1923 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1924 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1925 c->self, c->efd, buffer_len(&c->extended));
1926 else
1927 chan_ibuf_empty(c);
1929 /* Send extended data, i.e. stderr */
1930 if (compat20 &&
1931 !(c->flags & CHAN_EOF_SENT) &&
1932 c->remote_window > 0 &&
1933 (len = buffer_len(&c->extended)) > 0 &&
1934 c->extended_usage == CHAN_EXTENDED_READ) {
1935 debug2("channel %d: rwin %u elen %u euse %d",
1936 c->self, c->remote_window, buffer_len(&c->extended),
1937 c->extended_usage);
1938 if (len > c->remote_window)
1939 len = c->remote_window;
1940 if (len > c->remote_maxpacket)
1941 len = c->remote_maxpacket;
1942 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1943 packet_put_int(c->remote_id);
1944 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1945 packet_put_string(buffer_ptr(&c->extended), len);
1946 packet_send();
1947 buffer_consume(&c->extended, len);
1948 c->remote_window -= len;
1949 debug2("channel %d: sent ext data %d", c->self, len);
1955 /* -- protocol input */
1957 /* ARGSUSED */
1958 void
1959 channel_input_data(int type, u_int32_t seq, void *ctxt)
1961 int id;
1962 char *data;
1963 u_int data_len;
1964 Channel *c;
1966 /* Get the channel number and verify it. */
1967 id = packet_get_int();
1968 c = channel_lookup(id);
1969 if (c == NULL)
1970 packet_disconnect("Received data for nonexistent channel %d.", id);
1972 /* Ignore any data for non-open channels (might happen on close) */
1973 if (c->type != SSH_CHANNEL_OPEN &&
1974 c->type != SSH_CHANNEL_X11_OPEN)
1975 return;
1977 /* Get the data. */
1978 data = packet_get_string(&data_len);
1981 * Ignore data for protocol > 1.3 if output end is no longer open.
1982 * For protocol 2 the sending side is reducing its window as it sends
1983 * data, so we must 'fake' consumption of the data in order to ensure
1984 * that window updates are sent back. Otherwise the connection might
1985 * deadlock.
1987 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
1988 if (compat20) {
1989 c->local_window -= data_len;
1990 c->local_consumed += data_len;
1992 xfree(data);
1993 return;
1996 if (compat20) {
1997 if (data_len > c->local_maxpacket) {
1998 logit("channel %d: rcvd big packet %d, maxpack %d",
1999 c->self, data_len, c->local_maxpacket);
2001 if (data_len > c->local_window) {
2002 logit("channel %d: rcvd too much data %d, win %d",
2003 c->self, data_len, c->local_window);
2004 xfree(data);
2005 return;
2007 c->local_window -= data_len;
2009 packet_check_eom();
2010 if (c->datagram)
2011 buffer_put_string(&c->output, data, data_len);
2012 else
2013 buffer_append(&c->output, data, data_len);
2014 xfree(data);
2017 /* ARGSUSED */
2018 void
2019 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2021 int id;
2022 char *data;
2023 u_int data_len, tcode;
2024 Channel *c;
2026 /* Get the channel number and verify it. */
2027 id = packet_get_int();
2028 c = channel_lookup(id);
2030 if (c == NULL)
2031 packet_disconnect("Received extended_data for bad channel %d.", id);
2032 if (c->type != SSH_CHANNEL_OPEN) {
2033 logit("channel %d: ext data for non open", id);
2034 return;
2036 if (c->flags & CHAN_EOF_RCVD) {
2037 if (datafellows & SSH_BUG_EXTEOF)
2038 debug("channel %d: accepting ext data after eof", id);
2039 else
2040 packet_disconnect("Received extended_data after EOF "
2041 "on channel %d.", id);
2043 tcode = packet_get_int();
2044 if (c->efd == -1 ||
2045 c->extended_usage != CHAN_EXTENDED_WRITE ||
2046 tcode != SSH2_EXTENDED_DATA_STDERR) {
2047 logit("channel %d: bad ext data", c->self);
2048 return;
2050 data = packet_get_string(&data_len);
2051 packet_check_eom();
2052 if (data_len > c->local_window) {
2053 logit("channel %d: rcvd too much extended_data %d, win %d",
2054 c->self, data_len, c->local_window);
2055 xfree(data);
2056 return;
2058 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2059 c->local_window -= data_len;
2060 buffer_append(&c->extended, data, data_len);
2061 xfree(data);
2064 /* ARGSUSED */
2065 void
2066 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2068 int id;
2069 Channel *c;
2071 id = packet_get_int();
2072 packet_check_eom();
2073 c = channel_lookup(id);
2074 if (c == NULL)
2075 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2076 chan_rcvd_ieof(c);
2078 /* XXX force input close */
2079 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2080 debug("channel %d: FORCE input drain", c->self);
2081 c->istate = CHAN_INPUT_WAIT_DRAIN;
2082 if (buffer_len(&c->input) == 0)
2083 chan_ibuf_empty(c);
2088 /* ARGSUSED */
2089 void
2090 channel_input_close(int type, u_int32_t seq, void *ctxt)
2092 int id;
2093 Channel *c;
2095 id = packet_get_int();
2096 packet_check_eom();
2097 c = channel_lookup(id);
2098 if (c == NULL)
2099 packet_disconnect("Received close for nonexistent channel %d.", id);
2102 * Send a confirmation that we have closed the channel and no more
2103 * data is coming for it.
2105 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2106 packet_put_int(c->remote_id);
2107 packet_send();
2110 * If the channel is in closed state, we have sent a close request,
2111 * and the other side will eventually respond with a confirmation.
2112 * Thus, we cannot free the channel here, because then there would be
2113 * no-one to receive the confirmation. The channel gets freed when
2114 * the confirmation arrives.
2116 if (c->type != SSH_CHANNEL_CLOSED) {
2118 * Not a closed channel - mark it as draining, which will
2119 * cause it to be freed later.
2121 buffer_clear(&c->input);
2122 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2126 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2127 /* ARGSUSED */
2128 void
2129 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2131 int id = packet_get_int();
2132 Channel *c = channel_lookup(id);
2134 packet_check_eom();
2135 if (c == NULL)
2136 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2137 chan_rcvd_oclose(c);
2140 /* ARGSUSED */
2141 void
2142 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2144 int id = packet_get_int();
2145 Channel *c = channel_lookup(id);
2147 packet_check_eom();
2148 if (c == NULL)
2149 packet_disconnect("Received close confirmation for "
2150 "out-of-range channel %d.", id);
2151 if (c->type != SSH_CHANNEL_CLOSED)
2152 packet_disconnect("Received close confirmation for "
2153 "non-closed channel %d (type %d).", id, c->type);
2154 channel_free(c);
2157 /* ARGSUSED */
2158 void
2159 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2161 int id, remote_id;
2162 Channel *c;
2164 id = packet_get_int();
2165 c = channel_lookup(id);
2167 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2168 packet_disconnect("Received open confirmation for "
2169 "non-opening channel %d.", id);
2170 remote_id = packet_get_int();
2171 /* Record the remote channel number and mark that the channel is now open. */
2172 c->remote_id = remote_id;
2173 c->type = SSH_CHANNEL_OPEN;
2175 if (compat20) {
2176 c->remote_window = packet_get_int();
2177 c->remote_maxpacket = packet_get_int();
2178 if (c->confirm) {
2179 debug2("callback start");
2180 c->confirm(c->self, c->confirm_ctx);
2181 debug2("callback done");
2183 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2184 c->remote_window, c->remote_maxpacket);
2186 packet_check_eom();
2189 static char *
2190 reason2txt(int reason)
2192 switch (reason) {
2193 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2194 return "administratively prohibited";
2195 case SSH2_OPEN_CONNECT_FAILED:
2196 return "connect failed";
2197 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2198 return "unknown channel type";
2199 case SSH2_OPEN_RESOURCE_SHORTAGE:
2200 return "resource shortage";
2202 return "unknown reason";
2205 /* ARGSUSED */
2206 void
2207 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2209 int id, reason;
2210 char *msg = NULL, *lang = NULL;
2211 Channel *c;
2213 id = packet_get_int();
2214 c = channel_lookup(id);
2216 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2217 packet_disconnect("Received open failure for "
2218 "non-opening channel %d.", id);
2219 if (compat20) {
2220 reason = packet_get_int();
2221 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2222 msg = packet_get_string(NULL);
2223 lang = packet_get_string(NULL);
2225 logit("channel %d: open failed: %s%s%s", id,
2226 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2227 if (msg != NULL)
2228 xfree(msg);
2229 if (lang != NULL)
2230 xfree(lang);
2232 packet_check_eom();
2233 /* Free the channel. This will also close the socket. */
2234 channel_free(c);
2237 /* ARGSUSED */
2238 void
2239 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2241 Channel *c;
2242 int id;
2243 u_int adjust;
2245 if (!compat20)
2246 return;
2248 /* Get the channel number and verify it. */
2249 id = packet_get_int();
2250 c = channel_lookup(id);
2252 if (c == NULL) {
2253 logit("Received window adjust for non-open channel %d.", id);
2254 return;
2256 adjust = packet_get_int();
2257 packet_check_eom();
2258 debug2("channel %d: rcvd adjust %u", id, adjust);
2259 c->remote_window += adjust;
2262 /* ARGSUSED */
2263 void
2264 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2266 Channel *c = NULL;
2267 u_short host_port;
2268 char *host, *originator_string;
2269 int remote_id, sock = -1;
2271 remote_id = packet_get_int();
2272 host = packet_get_string(NULL);
2273 host_port = packet_get_int();
2275 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2276 originator_string = packet_get_string(NULL);
2277 } else {
2278 originator_string = xstrdup("unknown (remote did not supply name)");
2280 packet_check_eom();
2281 sock = channel_connect_to(host, host_port);
2282 if (sock != -1) {
2283 c = channel_new("connected socket",
2284 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2285 originator_string, 1);
2286 c->remote_id = remote_id;
2288 xfree(originator_string);
2289 if (c == NULL) {
2290 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2291 packet_put_int(remote_id);
2292 packet_send();
2294 xfree(host);
2298 /* -- tcp forwarding */
2300 void
2301 channel_set_af(int af)
2303 IPv4or6 = af;
2306 static int
2307 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2308 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2310 Channel *c;
2311 int sock, r, success = 0, wildcard = 0, is_client;
2312 struct addrinfo hints, *ai, *aitop;
2313 const char *host, *addr;
2314 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2316 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2317 listen_addr : host_to_connect;
2318 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2320 if (host == NULL) {
2321 error("No forward host name.");
2322 return 0;
2324 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2325 error("Forward host name too long.");
2326 return 0;
2330 * Determine whether or not a port forward listens to loopback,
2331 * specified address or wildcard. On the client, a specified bind
2332 * address will always override gateway_ports. On the server, a
2333 * gateway_ports of 1 (``yes'') will override the client's
2334 * specification and force a wildcard bind, whereas a value of 2
2335 * (``clientspecified'') will bind to whatever address the client
2336 * asked for.
2338 * Special-case listen_addrs are:
2340 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2341 * "" (empty string), "*" -> wildcard v4/v6
2342 * "localhost" -> loopback v4/v6
2344 addr = NULL;
2345 if (listen_addr == NULL) {
2346 /* No address specified: default to gateway_ports setting */
2347 if (gateway_ports)
2348 wildcard = 1;
2349 } else if (gateway_ports || is_client) {
2350 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2351 strcmp(listen_addr, "0.0.0.0") == 0) ||
2352 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2353 (!is_client && gateway_ports == 1))
2354 wildcard = 1;
2355 else if (strcmp(listen_addr, "localhost") != 0)
2356 addr = listen_addr;
2359 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2360 type, wildcard, (addr == NULL) ? "NULL" : addr);
2363 * getaddrinfo returns a loopback address if the hostname is
2364 * set to NULL and hints.ai_flags is not AI_PASSIVE
2366 memset(&hints, 0, sizeof(hints));
2367 hints.ai_family = IPv4or6;
2368 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2369 hints.ai_socktype = SOCK_STREAM;
2370 snprintf(strport, sizeof strport, "%d", listen_port);
2371 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2372 if (addr == NULL) {
2373 /* This really shouldn't happen */
2374 packet_disconnect("getaddrinfo: fatal error: %s",
2375 gai_strerror(r));
2376 } else {
2377 error("channel_setup_fwd_listener: "
2378 "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
2380 return 0;
2383 for (ai = aitop; ai; ai = ai->ai_next) {
2384 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2385 continue;
2386 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2387 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2388 error("channel_setup_fwd_listener: getnameinfo failed");
2389 continue;
2391 /* Create a port to listen for the host. */
2392 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2393 if (sock < 0) {
2394 /* this is no error since kernel may not support ipv6 */
2395 verbose("socket: %.100s", strerror(errno));
2396 continue;
2399 channel_set_reuseaddr(sock);
2401 debug("Local forwarding listening on %s port %s.", ntop, strport);
2403 /* Bind the socket to the address. */
2404 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2405 /* address can be in use ipv6 address is already bound */
2406 if (!ai->ai_next)
2407 error("bind: %.100s", strerror(errno));
2408 else
2409 verbose("bind: %.100s", strerror(errno));
2411 close(sock);
2412 continue;
2414 /* Start listening for connections on the socket. */
2415 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2416 error("listen: %.100s", strerror(errno));
2417 close(sock);
2418 continue;
2420 /* Allocate a channel number for the socket. */
2421 c = channel_new("port listener", type, sock, sock, -1,
2422 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2423 0, "port listener", 1);
2424 strlcpy(c->path, host, sizeof(c->path));
2425 c->host_port = port_to_connect;
2426 c->listening_port = listen_port;
2427 success = 1;
2429 if (success == 0)
2430 error("channel_setup_fwd_listener: cannot listen to port: %d",
2431 listen_port);
2432 freeaddrinfo(aitop);
2433 return success;
2437 channel_cancel_rport_listener(const char *host, u_short port)
2439 u_int i;
2440 int found = 0;
2442 for (i = 0; i < channels_alloc; i++) {
2443 Channel *c = channels[i];
2445 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2446 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2447 c->listening_port == port) {
2448 debug2("%s: close channel %d", __func__, i);
2449 channel_free(c);
2450 found = 1;
2454 return (found);
2457 /* protocol local port fwd, used by ssh (and sshd in v1) */
2459 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2460 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2462 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2463 listen_host, listen_port, host_to_connect, port_to_connect,
2464 gateway_ports);
2467 /* protocol v2 remote port fwd, used by sshd */
2469 channel_setup_remote_fwd_listener(const char *listen_address,
2470 u_short listen_port, int gateway_ports)
2472 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2473 listen_address, listen_port, NULL, 0, gateway_ports);
2477 * Initiate forwarding of connections to port "port" on remote host through
2478 * the secure channel to host:port from local side.
2481 void
2482 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2483 const char *host_to_connect, u_short port_to_connect)
2485 int type, success = 0;
2487 /* Record locally that connection to this host/port is permitted. */
2488 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2489 fatal("channel_request_remote_forwarding: too many forwards");
2491 /* Send the forward request to the remote side. */
2492 if (compat20) {
2493 const char *address_to_bind;
2494 if (listen_host == NULL)
2495 address_to_bind = "localhost";
2496 else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
2497 address_to_bind = "";
2498 else
2499 address_to_bind = listen_host;
2501 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2502 packet_put_cstring("tcpip-forward");
2503 packet_put_char(1); /* boolean: want reply */
2504 packet_put_cstring(address_to_bind);
2505 packet_put_int(listen_port);
2506 packet_send();
2507 packet_write_wait();
2508 /* Assume that server accepts the request */
2509 success = 1;
2510 } else {
2511 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2512 packet_put_int(listen_port);
2513 packet_put_cstring(host_to_connect);
2514 packet_put_int(port_to_connect);
2515 packet_send();
2516 packet_write_wait();
2518 /* Wait for response from the remote side. */
2519 type = packet_read();
2520 switch (type) {
2521 case SSH_SMSG_SUCCESS:
2522 success = 1;
2523 break;
2524 case SSH_SMSG_FAILURE:
2525 logit("Warning: Server denied remote port forwarding.");
2526 break;
2527 default:
2528 /* Unknown packet */
2529 packet_disconnect("Protocol error for port forward request:"
2530 "received packet type %d.", type);
2533 if (success) {
2534 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2535 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2536 permitted_opens[num_permitted_opens].listen_port = listen_port;
2537 num_permitted_opens++;
2542 * Request cancellation of remote forwarding of connection host:port from
2543 * local side.
2545 void
2546 channel_request_rforward_cancel(const char *host, u_short port)
2548 int i;
2550 if (!compat20)
2551 return;
2553 for (i = 0; i < num_permitted_opens; i++) {
2554 if (permitted_opens[i].host_to_connect != NULL &&
2555 permitted_opens[i].listen_port == port)
2556 break;
2558 if (i >= num_permitted_opens) {
2559 debug("%s: requested forward not found", __func__);
2560 return;
2562 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2563 packet_put_cstring("cancel-tcpip-forward");
2564 packet_put_char(0);
2565 packet_put_cstring(host == NULL ? "" : host);
2566 packet_put_int(port);
2567 packet_send();
2569 permitted_opens[i].listen_port = 0;
2570 permitted_opens[i].port_to_connect = 0;
2571 xfree(permitted_opens[i].host_to_connect);
2572 permitted_opens[i].host_to_connect = NULL;
2576 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2577 * listening for the port, and sends back a success reply (or disconnect
2578 * message if there was an error). This never returns if there was an error.
2580 void
2581 channel_input_port_forward_request(int is_root, int gateway_ports)
2583 u_short port, host_port;
2584 char *hostname;
2586 /* Get arguments from the packet. */
2587 port = packet_get_int();
2588 hostname = packet_get_string(NULL);
2589 host_port = packet_get_int();
2591 #ifndef HAVE_CYGWIN
2593 * Check that an unprivileged user is not trying to forward a
2594 * privileged port.
2596 if (port < IPPORT_RESERVED && !is_root)
2597 packet_disconnect(
2598 "Requested forwarding of port %d but user is not root.",
2599 port);
2600 if (host_port == 0)
2601 packet_disconnect("Dynamic forwarding denied.");
2602 #endif
2604 /* Initiate forwarding */
2605 channel_setup_local_fwd_listener(NULL, port, hostname,
2606 host_port, gateway_ports);
2608 /* Free the argument string. */
2609 xfree(hostname);
2613 * Permits opening to any host/port if permitted_opens[] is empty. This is
2614 * usually called by the server, because the user could connect to any port
2615 * anyway, and the server has no way to know but to trust the client anyway.
2617 void
2618 channel_permit_all_opens(void)
2620 if (num_permitted_opens == 0)
2621 all_opens_permitted = 1;
2624 void
2625 channel_add_permitted_opens(char *host, int port)
2627 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2628 fatal("channel_request_remote_forwarding: too many forwards");
2629 debug("allow port forwarding to host %s port %d", host, port);
2631 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2632 permitted_opens[num_permitted_opens].port_to_connect = port;
2633 num_permitted_opens++;
2635 all_opens_permitted = 0;
2638 void
2639 channel_clear_permitted_opens(void)
2641 int i;
2643 for (i = 0; i < num_permitted_opens; i++)
2644 if (permitted_opens[i].host_to_connect != NULL)
2645 xfree(permitted_opens[i].host_to_connect);
2646 num_permitted_opens = 0;
2650 /* return socket to remote host, port */
2651 static int
2652 connect_to(const char *host, u_short port)
2654 struct addrinfo hints, *ai, *aitop;
2655 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2656 int gaierr;
2657 int sock = -1;
2659 memset(&hints, 0, sizeof(hints));
2660 hints.ai_family = IPv4or6;
2661 hints.ai_socktype = SOCK_STREAM;
2662 snprintf(strport, sizeof strport, "%d", port);
2663 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2664 error("connect_to %.100s: unknown host (%s)", host,
2665 gai_strerror(gaierr));
2666 return -1;
2668 for (ai = aitop; ai; ai = ai->ai_next) {
2669 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2670 continue;
2671 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2672 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2673 error("connect_to: getnameinfo failed");
2674 continue;
2676 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2677 if (sock < 0) {
2678 if (ai->ai_next == NULL)
2679 error("socket: %.100s", strerror(errno));
2680 else
2681 verbose("socket: %.100s", strerror(errno));
2682 continue;
2684 if (set_nonblock(sock) == -1)
2685 fatal("%s: set_nonblock(%d)", __func__, sock);
2686 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2687 errno != EINPROGRESS) {
2688 error("connect_to %.100s port %s: %.100s", ntop, strport,
2689 strerror(errno));
2690 close(sock);
2691 continue; /* fail -- try next */
2693 break; /* success */
2696 freeaddrinfo(aitop);
2697 if (!ai) {
2698 error("connect_to %.100s port %d: failed.", host, port);
2699 return -1;
2701 /* success */
2702 set_nodelay(sock);
2703 return sock;
2707 channel_connect_by_listen_address(u_short listen_port)
2709 int i;
2711 for (i = 0; i < num_permitted_opens; i++)
2712 if (permitted_opens[i].host_to_connect != NULL &&
2713 permitted_opens[i].listen_port == listen_port)
2714 return connect_to(
2715 permitted_opens[i].host_to_connect,
2716 permitted_opens[i].port_to_connect);
2717 error("WARNING: Server requests forwarding for unknown listen_port %d",
2718 listen_port);
2719 return -1;
2722 /* Check if connecting to that port is permitted and connect. */
2724 channel_connect_to(const char *host, u_short port)
2726 int i, permit;
2728 permit = all_opens_permitted;
2729 if (!permit) {
2730 for (i = 0; i < num_permitted_opens; i++)
2731 if (permitted_opens[i].host_to_connect != NULL &&
2732 permitted_opens[i].port_to_connect == port &&
2733 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2734 permit = 1;
2737 if (!permit) {
2738 logit("Received request to connect to host %.100s port %d, "
2739 "but the request was denied.", host, port);
2740 return -1;
2742 return connect_to(host, port);
2745 void
2746 channel_send_window_changes(void)
2748 u_int i;
2749 struct winsize ws;
2751 for (i = 0; i < channels_alloc; i++) {
2752 if (channels[i] == NULL || !channels[i]->client_tty ||
2753 channels[i]->type != SSH_CHANNEL_OPEN)
2754 continue;
2755 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2756 continue;
2757 channel_request_start(i, "window-change", 0);
2758 packet_put_int((u_int)ws.ws_col);
2759 packet_put_int((u_int)ws.ws_row);
2760 packet_put_int((u_int)ws.ws_xpixel);
2761 packet_put_int((u_int)ws.ws_ypixel);
2762 packet_send();
2766 /* -- X11 forwarding */
2769 * Creates an internet domain socket for listening for X11 connections.
2770 * Returns 0 and a suitable display number for the DISPLAY variable
2771 * stored in display_numberp , or -1 if an error occurs.
2774 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2775 int single_connection, u_int *display_numberp, int **chanids)
2777 Channel *nc = NULL;
2778 int display_number, sock;
2779 u_short port;
2780 struct addrinfo hints, *ai, *aitop;
2781 char strport[NI_MAXSERV];
2782 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2784 if (chanids == NULL)
2785 return -1;
2787 for (display_number = x11_display_offset;
2788 display_number < MAX_DISPLAYS;
2789 display_number++) {
2790 port = 6000 + display_number;
2791 memset(&hints, 0, sizeof(hints));
2792 hints.ai_family = IPv4or6;
2793 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2794 hints.ai_socktype = SOCK_STREAM;
2795 snprintf(strport, sizeof strport, "%d", port);
2796 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2797 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2798 return -1;
2800 for (ai = aitop; ai; ai = ai->ai_next) {
2801 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2802 continue;
2803 sock = socket(ai->ai_family, ai->ai_socktype,
2804 ai->ai_protocol);
2805 if (sock < 0) {
2806 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2807 error("socket: %.100s", strerror(errno));
2808 freeaddrinfo(aitop);
2809 return -1;
2810 } else {
2811 debug("x11_create_display_inet: Socket family %d not supported",
2812 ai->ai_family);
2813 continue;
2816 #ifdef IPV6_V6ONLY
2817 if (ai->ai_family == AF_INET6) {
2818 int on = 1;
2819 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2820 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2822 #endif
2823 channel_set_reuseaddr(sock);
2824 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2825 debug2("bind port %d: %.100s", port, strerror(errno));
2826 close(sock);
2828 if (ai->ai_next)
2829 continue;
2831 for (n = 0; n < num_socks; n++) {
2832 close(socks[n]);
2834 num_socks = 0;
2835 break;
2837 socks[num_socks++] = sock;
2838 #ifndef DONT_TRY_OTHER_AF
2839 if (num_socks == NUM_SOCKS)
2840 break;
2841 #else
2842 if (x11_use_localhost) {
2843 if (num_socks == NUM_SOCKS)
2844 break;
2845 } else {
2846 break;
2848 #endif
2850 freeaddrinfo(aitop);
2851 if (num_socks > 0)
2852 break;
2854 if (display_number >= MAX_DISPLAYS) {
2855 error("Failed to allocate internet-domain X11 display socket.");
2856 return -1;
2858 /* Start listening for connections on the socket. */
2859 for (n = 0; n < num_socks; n++) {
2860 sock = socks[n];
2861 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2862 error("listen: %.100s", strerror(errno));
2863 close(sock);
2864 return -1;
2868 /* Allocate a channel for each socket. */
2869 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
2870 for (n = 0; n < num_socks; n++) {
2871 sock = socks[n];
2872 nc = channel_new("x11 listener",
2873 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2874 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2875 0, "X11 inet listener", 1);
2876 nc->single_connection = single_connection;
2877 (*chanids)[n] = nc->self;
2879 (*chanids)[n] = -1;
2881 /* Return the display number for the DISPLAY environment variable. */
2882 *display_numberp = display_number;
2883 return (0);
2886 static int
2887 connect_local_xsocket(u_int dnr)
2889 int sock;
2890 struct sockaddr_un addr;
2892 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2893 if (sock < 0)
2894 error("socket: %.100s", strerror(errno));
2895 memset(&addr, 0, sizeof(addr));
2896 addr.sun_family = AF_UNIX;
2897 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2898 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
2899 return sock;
2900 close(sock);
2901 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2902 return -1;
2906 x11_connect_display(void)
2908 u_int display_number;
2909 const char *display;
2910 char buf[1024], *cp;
2911 struct addrinfo hints, *ai, *aitop;
2912 char strport[NI_MAXSERV];
2913 int gaierr, sock = 0;
2915 /* Try to open a socket for the local X server. */
2916 display = getenv("DISPLAY");
2917 if (!display) {
2918 error("DISPLAY not set.");
2919 return -1;
2922 * Now we decode the value of the DISPLAY variable and make a
2923 * connection to the real X server.
2927 * Check if it is a unix domain socket. Unix domain displays are in
2928 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2930 if (strncmp(display, "unix:", 5) == 0 ||
2931 display[0] == ':') {
2932 /* Connect to the unix domain socket. */
2933 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
2934 error("Could not parse display number from DISPLAY: %.100s",
2935 display);
2936 return -1;
2938 /* Create a socket. */
2939 sock = connect_local_xsocket(display_number);
2940 if (sock < 0)
2941 return -1;
2943 /* OK, we now have a connection to the display. */
2944 return sock;
2947 * Connect to an inet socket. The DISPLAY value is supposedly
2948 * hostname:d[.s], where hostname may also be numeric IP address.
2950 strlcpy(buf, display, sizeof(buf));
2951 cp = strchr(buf, ':');
2952 if (!cp) {
2953 error("Could not find ':' in DISPLAY: %.100s", display);
2954 return -1;
2956 *cp = 0;
2957 /* buf now contains the host name. But first we parse the display number. */
2958 if (sscanf(cp + 1, "%u", &display_number) != 1) {
2959 error("Could not parse display number from DISPLAY: %.100s",
2960 display);
2961 return -1;
2964 /* Look up the host address */
2965 memset(&hints, 0, sizeof(hints));
2966 hints.ai_family = IPv4or6;
2967 hints.ai_socktype = SOCK_STREAM;
2968 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
2969 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2970 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2971 return -1;
2973 for (ai = aitop; ai; ai = ai->ai_next) {
2974 /* Create a socket. */
2975 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2976 if (sock < 0) {
2977 debug2("socket: %.100s", strerror(errno));
2978 continue;
2980 /* Connect it to the display. */
2981 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2982 debug2("connect %.100s port %u: %.100s", buf,
2983 6000 + display_number, strerror(errno));
2984 close(sock);
2985 continue;
2987 /* Success */
2988 break;
2990 freeaddrinfo(aitop);
2991 if (!ai) {
2992 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
2993 strerror(errno));
2994 return -1;
2996 set_nodelay(sock);
2997 return sock;
3001 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3002 * the remote channel number. We should do whatever we want, and respond
3003 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3006 void
3007 x11_input_open(int type, u_int32_t seq, void *ctxt)
3009 Channel *c = NULL;
3010 int remote_id, sock = 0;
3011 char *remote_host;
3013 debug("Received X11 open request.");
3015 remote_id = packet_get_int();
3017 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3018 remote_host = packet_get_string(NULL);
3019 } else {
3020 remote_host = xstrdup("unknown (remote did not supply name)");
3022 packet_check_eom();
3024 /* Obtain a connection to the real X display. */
3025 sock = x11_connect_display();
3026 if (sock != -1) {
3027 /* Allocate a channel for this connection. */
3028 c = channel_new("connected x11 socket",
3029 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3030 remote_host, 1);
3031 c->remote_id = remote_id;
3032 c->force_drain = 1;
3034 xfree(remote_host);
3035 if (c == NULL) {
3036 /* Send refusal to the remote host. */
3037 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3038 packet_put_int(remote_id);
3039 } else {
3040 /* Send a confirmation to the remote host. */
3041 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3042 packet_put_int(remote_id);
3043 packet_put_int(c->self);
3045 packet_send();
3048 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3049 void
3050 deny_input_open(int type, u_int32_t seq, void *ctxt)
3052 int rchan = packet_get_int();
3054 switch (type) {
3055 case SSH_SMSG_AGENT_OPEN:
3056 error("Warning: ssh server tried agent forwarding.");
3057 break;
3058 case SSH_SMSG_X11_OPEN:
3059 error("Warning: ssh server tried X11 forwarding.");
3060 break;
3061 default:
3062 error("deny_input_open: type %d", type);
3063 break;
3065 error("Warning: this is probably a break-in attempt by a malicious server.");
3066 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3067 packet_put_int(rchan);
3068 packet_send();
3072 * Requests forwarding of X11 connections, generates fake authentication
3073 * data, and enables authentication spoofing.
3074 * This should be called in the client only.
3076 void
3077 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3078 const char *proto, const char *data)
3080 u_int data_len = (u_int) strlen(data) / 2;
3081 u_int i, value;
3082 char *new_data;
3083 int screen_number;
3084 const char *cp;
3085 u_int32_t rnd = 0;
3087 if (x11_saved_display == NULL)
3088 x11_saved_display = xstrdup(disp);
3089 else if (strcmp(disp, x11_saved_display) != 0) {
3090 error("x11_request_forwarding_with_spoofing: different "
3091 "$DISPLAY already forwarded");
3092 return;
3095 cp = disp;
3096 if (disp)
3097 cp = strchr(disp, ':');
3098 if (cp)
3099 cp = strchr(cp, '.');
3100 if (cp)
3101 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3102 else
3103 screen_number = 0;
3105 if (x11_saved_proto == NULL) {
3106 /* Save protocol name. */
3107 x11_saved_proto = xstrdup(proto);
3109 * Extract real authentication data and generate fake data
3110 * of the same length.
3112 x11_saved_data = xmalloc(data_len);
3113 x11_fake_data = xmalloc(data_len);
3114 for (i = 0; i < data_len; i++) {
3115 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3116 fatal("x11_request_forwarding: bad "
3117 "authentication data: %.100s", data);
3118 if (i % 4 == 0)
3119 rnd = arc4random();
3120 x11_saved_data[i] = value;
3121 x11_fake_data[i] = rnd & 0xff;
3122 rnd >>= 8;
3124 x11_saved_data_len = data_len;
3125 x11_fake_data_len = data_len;
3128 /* Convert the fake data into hex. */
3129 new_data = tohex(x11_fake_data, data_len);
3131 /* Send the request packet. */
3132 if (compat20) {
3133 channel_request_start(client_session_id, "x11-req", 0);
3134 packet_put_char(0); /* XXX bool single connection */
3135 } else {
3136 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3138 packet_put_cstring(proto);
3139 packet_put_cstring(new_data);
3140 packet_put_int(screen_number);
3141 packet_send();
3142 packet_write_wait();
3143 xfree(new_data);
3147 /* -- agent forwarding */
3149 /* Sends a message to the server to request authentication fd forwarding. */
3151 void
3152 auth_request_forwarding(void)
3154 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3155 packet_send();
3156 packet_write_wait();