1 /* $OpenBSD: channels.c,v 1.256 2006/07/17 01:31:09 stevesk Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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
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.
44 #include <sys/ioctl.h>
45 #include <sys/types.h>
47 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
53 #if defined(HAVE_NETDB_H)
71 #include "pathnames.h"
77 * Pointer to an array containing all allocated channels. The array is
78 * dynamically extended as needed.
80 static Channel **channels = NULL;
83 * Size of the channel array. All slots of the array must always be
84 * initialized (at least the type field); unused slots set to NULL
86 static u_int channels_alloc = 0;
89 * Maximum file descriptor value used in any of the channels. This is
90 * updated in channel_new.
92 static int channel_max_fd = 0;
95 /* -- tcp forwarding */
98 * Data structure for storing which hosts are permitted for forward requests.
99 * The local sides of any remote forwards are stored in this array to prevent
100 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
101 * network (which might be behind a firewall).
104 char *host_to_connect; /* Connect to 'host'. */
105 u_short port_to_connect; /* Connect to 'port'. */
106 u_short listen_port; /* Remote side should listen port number. */
109 /* List of all permitted host/port pairs to connect. */
110 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
112 /* Number of permitted host/port pairs in the array. */
113 static int num_permitted_opens = 0;
115 * If this is true, all opens are permitted. This is the case on the server
116 * on which we have to trust the client anyway, and the user could do
117 * anything after logging in anyway.
119 static int all_opens_permitted = 0;
122 /* -- X11 forwarding */
124 /* Maximum number of fake X11 displays to try. */
125 #define MAX_DISPLAYS 1000
127 /* Saved X11 local (client) display. */
128 static char *x11_saved_display = NULL;
130 /* Saved X11 authentication protocol name. */
131 static char *x11_saved_proto = NULL;
133 /* Saved X11 authentication data. This is the real data. */
134 static char *x11_saved_data = NULL;
135 static u_int x11_saved_data_len = 0;
138 * Fake X11 authentication data. This is what the server will be sending us;
139 * we should replace any occurrences of this by the real data.
141 static u_char *x11_fake_data = NULL;
142 static u_int x11_fake_data_len;
145 /* -- agent forwarding */
149 /* AF_UNSPEC or AF_INET or AF_INET6 */
150 static int IPv4or6 = AF_UNSPEC;
153 static void port_open_helper(Channel *c, char *rtype);
155 /* -- channel core */
158 channel_by_id(int id)
162 if (id < 0 || (u_int)id >= channels_alloc) {
163 logit("channel_by_id: %d: bad id", id);
168 logit("channel_by_id: %d: bad id: channel free", id);
175 * Returns the channel if it is allowed to receive protocol messages.
176 * Private channels, like listening sockets, may not receive messages.
179 channel_lookup(int id)
183 if ((c = channel_by_id(id)) == NULL)
187 case SSH_CHANNEL_X11_OPEN:
188 case SSH_CHANNEL_LARVAL:
189 case SSH_CHANNEL_CONNECTING:
190 case SSH_CHANNEL_DYNAMIC:
191 case SSH_CHANNEL_OPENING:
192 case SSH_CHANNEL_OPEN:
193 case SSH_CHANNEL_INPUT_DRAINING:
194 case SSH_CHANNEL_OUTPUT_DRAINING:
197 logit("Non-public channel %d, type %d.", id, c->type);
202 * Register filedescriptors for a channel, used when allocating a channel or
203 * when the channel consumer/producer is ready, e.g. shell exec'd
206 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
207 int extusage, int nonblock)
209 /* Update the maximum file descriptor value. */
210 channel_max_fd = MAX(channel_max_fd, rfd);
211 channel_max_fd = MAX(channel_max_fd, wfd);
212 channel_max_fd = MAX(channel_max_fd, efd);
214 /* XXX set close-on-exec -markus */
218 c->sock = (rfd == wfd) ? rfd : -1;
219 c->ctl_fd = -1; /* XXX: set elsewhere */
221 c->extended_usage = extusage;
223 /* XXX ugly hack: nonblock is only set by the server */
224 if (nonblock && isatty(c->rfd)) {
225 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
227 if (!isatty(c->wfd)) {
228 error("channel %d: wfd %d is not a tty?",
234 c->wfd_isatty = isatty(c->wfd);
236 /* enable nonblocking mode */
248 * Allocate a new channel object and set its type and socket. This will cause
249 * remote_name to be freed.
252 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
253 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
259 /* Do initial allocation if this is the first call. */
260 if (channels_alloc == 0) {
262 channels = xcalloc(channels_alloc, sizeof(Channel *));
263 for (i = 0; i < channels_alloc; i++)
266 /* Try to find a free slot where to put the new channel. */
267 for (found = -1, i = 0; i < channels_alloc; i++)
268 if (channels[i] == NULL) {
269 /* Found a free slot. */
274 /* There are no free slots. Take last+1 slot and expand the array. */
275 found = channels_alloc;
276 if (channels_alloc > 10000)
277 fatal("channel_new: internal error: channels_alloc %d "
278 "too big.", channels_alloc);
279 channels = xrealloc(channels, channels_alloc + 10,
281 channels_alloc += 10;
282 debug2("channel: expanding %d", channels_alloc);
283 for (i = found; i < channels_alloc; i++)
286 /* Initialize and return new channel. */
287 c = channels[found] = xcalloc(1, sizeof(Channel));
288 buffer_init(&c->input);
289 buffer_init(&c->output);
290 buffer_init(&c->extended);
291 c->ostate = CHAN_OUTPUT_OPEN;
292 c->istate = CHAN_INPUT_OPEN;
294 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
298 c->local_window = window;
299 c->local_window_max = window;
300 c->local_consumed = 0;
301 c->local_maxpacket = maxpack;
303 c->remote_name = xstrdup(remote_name);
304 c->remote_window = 0;
305 c->remote_maxpacket = 0;
307 c->single_connection = 0;
308 c->detach_user = NULL;
311 c->confirm_ctx = NULL;
312 c->input_filter = NULL;
313 c->output_filter = NULL;
314 debug("channel %d: new [%s]", found, remote_name);
319 channel_find_maxfd(void)
325 for (i = 0; i < channels_alloc; i++) {
328 max = MAX(max, c->rfd);
329 max = MAX(max, c->wfd);
330 max = MAX(max, c->efd);
337 channel_close_fd(int *fdp)
339 int ret = 0, fd = *fdp;
344 if (fd == channel_max_fd)
345 channel_max_fd = channel_find_maxfd();
350 /* Close all channel fd/socket. */
352 channel_close_fds(Channel *c)
354 debug3("channel %d: close_fds r %d w %d e %d c %d",
355 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
357 channel_close_fd(&c->sock);
358 channel_close_fd(&c->ctl_fd);
359 channel_close_fd(&c->rfd);
360 channel_close_fd(&c->wfd);
361 channel_close_fd(&c->efd);
364 /* Free the channel and close its fd/socket. */
366 channel_free(Channel *c)
371 for (n = 0, i = 0; i < channels_alloc; i++)
374 debug("channel %d: free: %s, nchannels %u", c->self,
375 c->remote_name ? c->remote_name : "???", n);
377 s = channel_open_message();
378 debug3("channel %d: status: %s", c->self, s);
382 shutdown(c->sock, SHUT_RDWR);
384 shutdown(c->ctl_fd, SHUT_RDWR);
385 channel_close_fds(c);
386 buffer_free(&c->input);
387 buffer_free(&c->output);
388 buffer_free(&c->extended);
389 if (c->remote_name) {
390 xfree(c->remote_name);
391 c->remote_name = NULL;
393 channels[c->self] = NULL;
398 channel_free_all(void)
402 for (i = 0; i < channels_alloc; i++)
403 if (channels[i] != NULL)
404 channel_free(channels[i]);
408 * Closes the sockets/fds of all channels. This is used to close extra file
409 * descriptors after a fork.
412 channel_close_all(void)
416 for (i = 0; i < channels_alloc; i++)
417 if (channels[i] != NULL)
418 channel_close_fds(channels[i]);
422 * Stop listening to channels.
425 channel_stop_listening(void)
430 for (i = 0; i < channels_alloc; i++) {
434 case SSH_CHANNEL_AUTH_SOCKET:
435 case SSH_CHANNEL_PORT_LISTENER:
436 case SSH_CHANNEL_RPORT_LISTENER:
437 case SSH_CHANNEL_X11_LISTENER:
438 channel_close_fd(&c->sock);
447 * Returns true if no channel has too much buffered data, and false if one or
448 * more channel is overfull.
451 channel_not_very_much_buffered_data(void)
456 for (i = 0; i < channels_alloc; i++) {
458 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
461 buffer_len(&c->input) > packet_get_maxsize()) {
462 debug2("channel %d: big input buffer %d",
463 c->self, buffer_len(&c->input));
467 if (buffer_len(&c->output) > packet_get_maxsize()) {
468 debug2("channel %d: big output buffer %u > %u",
469 c->self, buffer_len(&c->output),
470 packet_get_maxsize());
478 /* Returns true if any channel is still open. */
480 channel_still_open(void)
485 for (i = 0; i < channels_alloc; i++) {
490 case SSH_CHANNEL_X11_LISTENER:
491 case SSH_CHANNEL_PORT_LISTENER:
492 case SSH_CHANNEL_RPORT_LISTENER:
493 case SSH_CHANNEL_CLOSED:
494 case SSH_CHANNEL_AUTH_SOCKET:
495 case SSH_CHANNEL_DYNAMIC:
496 case SSH_CHANNEL_CONNECTING:
497 case SSH_CHANNEL_ZOMBIE:
499 case SSH_CHANNEL_LARVAL:
501 fatal("cannot happen: SSH_CHANNEL_LARVAL");
503 case SSH_CHANNEL_OPENING:
504 case SSH_CHANNEL_OPEN:
505 case SSH_CHANNEL_X11_OPEN:
507 case SSH_CHANNEL_INPUT_DRAINING:
508 case SSH_CHANNEL_OUTPUT_DRAINING:
510 fatal("cannot happen: OUT_DRAIN");
513 fatal("channel_still_open: bad channel type %d", c->type);
520 /* Returns the id of an open channel suitable for keepaliving */
522 channel_find_open(void)
527 for (i = 0; i < channels_alloc; i++) {
529 if (c == NULL || c->remote_id < 0)
532 case SSH_CHANNEL_CLOSED:
533 case SSH_CHANNEL_DYNAMIC:
534 case SSH_CHANNEL_X11_LISTENER:
535 case SSH_CHANNEL_PORT_LISTENER:
536 case SSH_CHANNEL_RPORT_LISTENER:
537 case SSH_CHANNEL_OPENING:
538 case SSH_CHANNEL_CONNECTING:
539 case SSH_CHANNEL_ZOMBIE:
541 case SSH_CHANNEL_LARVAL:
542 case SSH_CHANNEL_AUTH_SOCKET:
543 case SSH_CHANNEL_OPEN:
544 case SSH_CHANNEL_X11_OPEN:
546 case SSH_CHANNEL_INPUT_DRAINING:
547 case SSH_CHANNEL_OUTPUT_DRAINING:
549 fatal("cannot happen: OUT_DRAIN");
552 fatal("channel_find_open: bad channel type %d", c->type);
561 * Returns a message describing the currently open forwarded connections,
562 * suitable for sending to the client. The message contains crlf pairs for
566 channel_open_message(void)
573 buffer_init(&buffer);
574 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
575 buffer_append(&buffer, buf, strlen(buf));
576 for (i = 0; i < channels_alloc; i++) {
581 case SSH_CHANNEL_X11_LISTENER:
582 case SSH_CHANNEL_PORT_LISTENER:
583 case SSH_CHANNEL_RPORT_LISTENER:
584 case SSH_CHANNEL_CLOSED:
585 case SSH_CHANNEL_AUTH_SOCKET:
586 case SSH_CHANNEL_ZOMBIE:
588 case SSH_CHANNEL_LARVAL:
589 case SSH_CHANNEL_OPENING:
590 case SSH_CHANNEL_CONNECTING:
591 case SSH_CHANNEL_DYNAMIC:
592 case SSH_CHANNEL_OPEN:
593 case SSH_CHANNEL_X11_OPEN:
594 case SSH_CHANNEL_INPUT_DRAINING:
595 case SSH_CHANNEL_OUTPUT_DRAINING:
596 snprintf(buf, sizeof buf,
597 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
598 c->self, c->remote_name,
599 c->type, c->remote_id,
600 c->istate, buffer_len(&c->input),
601 c->ostate, buffer_len(&c->output),
602 c->rfd, c->wfd, c->ctl_fd);
603 buffer_append(&buffer, buf, strlen(buf));
606 fatal("channel_open_message: bad channel type %d", c->type);
610 buffer_append(&buffer, "\0", 1);
611 cp = xstrdup(buffer_ptr(&buffer));
612 buffer_free(&buffer);
617 channel_send_open(int id)
619 Channel *c = channel_lookup(id);
622 logit("channel_send_open: %d: bad id", id);
625 debug2("channel %d: send open", id);
626 packet_start(SSH2_MSG_CHANNEL_OPEN);
627 packet_put_cstring(c->ctype);
628 packet_put_int(c->self);
629 packet_put_int(c->local_window);
630 packet_put_int(c->local_maxpacket);
635 channel_request_start(int id, char *service, int wantconfirm)
637 Channel *c = channel_lookup(id);
640 logit("channel_request_start: %d: unknown channel id", id);
643 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
644 packet_start(SSH2_MSG_CHANNEL_REQUEST);
645 packet_put_int(c->remote_id);
646 packet_put_cstring(service);
647 packet_put_char(wantconfirm);
651 channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
653 Channel *c = channel_lookup(id);
656 logit("channel_register_comfirm: %d: bad id", id);
660 c->confirm_ctx = ctx;
664 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
666 Channel *c = channel_by_id(id);
669 logit("channel_register_cleanup: %d: bad id", id);
673 c->detach_close = do_close;
677 channel_cancel_cleanup(int id)
679 Channel *c = channel_by_id(id);
682 logit("channel_cancel_cleanup: %d: bad id", id);
685 c->detach_user = NULL;
690 channel_register_filter(int id, channel_infilter_fn *ifn,
691 channel_outfilter_fn *ofn)
693 Channel *c = channel_lookup(id);
696 logit("channel_register_filter: %d: bad id", id);
699 c->input_filter = ifn;
700 c->output_filter = ofn;
704 channel_set_fds(int id, int rfd, int wfd, int efd,
705 int extusage, int nonblock, u_int window_max)
707 Channel *c = channel_lookup(id);
709 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
710 fatal("channel_activate for non-larval channel %d.", id);
711 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
712 c->type = SSH_CHANNEL_OPEN;
713 c->local_window = c->local_window_max = window_max;
714 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
715 packet_put_int(c->remote_id);
716 packet_put_int(c->local_window);
721 * 'channel_pre*' are called just before select() to add any bits relevant to
722 * channels in the select bitmasks.
725 * 'channel_post*': perform any appropriate operations for channels which
726 * have events pending.
728 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
729 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
730 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
733 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
735 FD_SET(c->sock, readset);
739 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
741 debug3("channel %d: waiting for connection", c->self);
742 FD_SET(c->sock, writeset);
746 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
748 if (buffer_len(&c->input) < packet_get_maxsize())
749 FD_SET(c->sock, readset);
750 if (buffer_len(&c->output) > 0)
751 FD_SET(c->sock, writeset);
755 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
757 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
759 if (c->istate == CHAN_INPUT_OPEN &&
761 buffer_len(&c->input) < limit &&
762 buffer_check_alloc(&c->input, CHAN_RBUF))
763 FD_SET(c->rfd, readset);
764 if (c->ostate == CHAN_OUTPUT_OPEN ||
765 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
766 if (buffer_len(&c->output) > 0) {
767 FD_SET(c->wfd, writeset);
768 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
769 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
770 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
771 c->self, c->efd, buffer_len(&c->extended));
776 /** XXX check close conditions, too */
777 if (compat20 && c->efd != -1) {
778 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
779 buffer_len(&c->extended) > 0)
780 FD_SET(c->efd, writeset);
781 else if (!(c->flags & CHAN_EOF_SENT) &&
782 c->extended_usage == CHAN_EXTENDED_READ &&
783 buffer_len(&c->extended) < c->remote_window)
784 FD_SET(c->efd, readset);
786 /* XXX: What about efd? races? */
787 if (compat20 && c->ctl_fd != -1 &&
788 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
789 FD_SET(c->ctl_fd, readset);
793 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
795 if (buffer_len(&c->input) == 0) {
796 packet_start(SSH_MSG_CHANNEL_CLOSE);
797 packet_put_int(c->remote_id);
799 c->type = SSH_CHANNEL_CLOSED;
800 debug2("channel %d: closing after input drain.", c->self);
805 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
807 if (buffer_len(&c->output) == 0)
810 FD_SET(c->sock, writeset);
814 * This is a special state for X11 authentication spoofing. An opened X11
815 * connection (when authentication spoofing is being done) remains in this
816 * state until the first packet has been completely read. The authentication
817 * data in that packet is then substituted by the real data if it matches the
818 * fake data, and the channel is put into normal mode.
819 * XXX All this happens at the client side.
820 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
823 x11_open_helper(Buffer *b)
826 u_int proto_len, data_len;
828 /* Check if the fixed size part of the packet is in buffer. */
829 if (buffer_len(b) < 12)
832 /* Parse the lengths of variable-length fields. */
834 if (ucp[0] == 0x42) { /* Byte order MSB first. */
835 proto_len = 256 * ucp[6] + ucp[7];
836 data_len = 256 * ucp[8] + ucp[9];
837 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
838 proto_len = ucp[6] + 256 * ucp[7];
839 data_len = ucp[8] + 256 * ucp[9];
841 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
846 /* Check if the whole packet is in buffer. */
848 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
851 /* Check if authentication protocol matches. */
852 if (proto_len != strlen(x11_saved_proto) ||
853 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
854 debug2("X11 connection uses different authentication protocol.");
857 /* Check if authentication data matches our fake data. */
858 if (data_len != x11_fake_data_len ||
859 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
860 x11_fake_data, x11_fake_data_len) != 0) {
861 debug2("X11 auth data does not match fake data.");
864 /* Check fake data length */
865 if (x11_fake_data_len != x11_saved_data_len) {
866 error("X11 fake_data_len %d != saved_data_len %d",
867 x11_fake_data_len, x11_saved_data_len);
871 * Received authentication protocol and data match
872 * our fake data. Substitute the fake data with real
875 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
876 x11_saved_data, x11_saved_data_len);
881 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
883 int ret = x11_open_helper(&c->output);
886 /* Start normal processing for the channel. */
887 c->type = SSH_CHANNEL_OPEN;
888 channel_pre_open_13(c, readset, writeset);
889 } else if (ret == -1) {
891 * We have received an X11 connection that has bad
892 * authentication information.
894 logit("X11 connection rejected because of wrong authentication.");
895 buffer_clear(&c->input);
896 buffer_clear(&c->output);
897 channel_close_fd(&c->sock);
899 c->type = SSH_CHANNEL_CLOSED;
900 packet_start(SSH_MSG_CHANNEL_CLOSE);
901 packet_put_int(c->remote_id);
907 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
909 int ret = x11_open_helper(&c->output);
911 /* c->force_drain = 1; */
914 c->type = SSH_CHANNEL_OPEN;
915 channel_pre_open(c, readset, writeset);
916 } else if (ret == -1) {
917 logit("X11 connection rejected because of wrong authentication.");
918 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
920 buffer_clear(&c->input);
922 buffer_clear(&c->output);
923 /* for proto v1, the peer will send an IEOF */
925 chan_write_failed(c);
927 c->type = SSH_CHANNEL_OPEN;
928 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
932 /* try to decode a socks4 header */
934 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
937 u_int len, have, i, found;
943 struct in_addr dest_addr;
946 debug2("channel %d: decode socks4", c->self);
948 have = buffer_len(&c->input);
949 len = sizeof(s4_req);
952 p = buffer_ptr(&c->input);
953 for (found = 0, i = len; i < have; i++) {
959 /* the peer is probably sending garbage */
960 debug("channel %d: decode socks4: too long",
967 buffer_get(&c->input, (char *)&s4_req.version, 1);
968 buffer_get(&c->input, (char *)&s4_req.command, 1);
969 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
970 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
971 have = buffer_len(&c->input);
972 p = buffer_ptr(&c->input);
974 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
976 fatal("channel %d: decode socks4: len %d > have %d",
978 strlcpy(username, p, sizeof(username));
979 buffer_consume(&c->input, len);
980 buffer_consume(&c->input, 1); /* trailing '\0' */
982 host = inet_ntoa(s4_req.dest_addr);
983 strlcpy(c->path, host, sizeof(c->path));
984 c->host_port = ntohs(s4_req.dest_port);
986 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
987 c->self, host, c->host_port, s4_req.command);
989 if (s4_req.command != 1) {
990 debug("channel %d: cannot handle: socks4 cn %d",
991 c->self, s4_req.command);
994 s4_rsp.version = 0; /* vn: 0 for reply */
995 s4_rsp.command = 90; /* cd: req granted */
996 s4_rsp.dest_port = 0; /* ignored */
997 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
998 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1002 /* try to decode a socks5 header */
1003 #define SSH_SOCKS5_AUTHDONE 0x1000
1004 #define SSH_SOCKS5_NOAUTH 0x00
1005 #define SSH_SOCKS5_IPV4 0x01
1006 #define SSH_SOCKS5_DOMAIN 0x03
1007 #define SSH_SOCKS5_IPV6 0x04
1008 #define SSH_SOCKS5_CONNECT 0x01
1009 #define SSH_SOCKS5_SUCCESS 0x00
1012 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1020 u_int16_t dest_port;
1021 u_char *p, dest_addr[255+1];
1022 u_int have, need, i, found, nmethods, addrlen, af;
1024 debug2("channel %d: decode socks5", c->self);
1025 p = buffer_ptr(&c->input);
1028 have = buffer_len(&c->input);
1029 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1030 /* format: ver | nmethods | methods */
1034 if (have < nmethods + 2)
1036 /* look for method: "NO AUTHENTICATION REQUIRED" */
1037 for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1038 if (p[i] == SSH_SOCKS5_NOAUTH ) {
1044 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1048 buffer_consume(&c->input, nmethods + 2);
1049 buffer_put_char(&c->output, 0x05); /* version */
1050 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1051 FD_SET(c->sock, writeset);
1052 c->flags |= SSH_SOCKS5_AUTHDONE;
1053 debug2("channel %d: socks5 auth done", c->self);
1054 return 0; /* need more */
1056 debug2("channel %d: socks5 post auth", c->self);
1057 if (have < sizeof(s5_req)+1)
1058 return 0; /* need more */
1059 memcpy(&s5_req, p, sizeof(s5_req));
1060 if (s5_req.version != 0x05 ||
1061 s5_req.command != SSH_SOCKS5_CONNECT ||
1062 s5_req.reserved != 0x00) {
1063 debug2("channel %d: only socks5 connect supported", c->self);
1066 switch (s5_req.atyp){
1067 case SSH_SOCKS5_IPV4:
1071 case SSH_SOCKS5_DOMAIN:
1072 addrlen = p[sizeof(s5_req)];
1075 case SSH_SOCKS5_IPV6:
1080 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1083 need = sizeof(s5_req) + addrlen + 2;
1084 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1088 buffer_consume(&c->input, sizeof(s5_req));
1089 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1090 buffer_consume(&c->input, 1); /* host string length */
1091 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1092 buffer_get(&c->input, (char *)&dest_port, 2);
1093 dest_addr[addrlen] = '\0';
1094 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1095 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1096 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1098 c->host_port = ntohs(dest_port);
1100 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1101 c->self, c->path, c->host_port, s5_req.command);
1103 s5_rsp.version = 0x05;
1104 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1105 s5_rsp.reserved = 0; /* ignored */
1106 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1107 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1108 dest_port = 0; /* ignored */
1110 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1111 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1112 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1116 /* dynamic port forwarding */
1118 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1124 have = buffer_len(&c->input);
1126 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1127 /* buffer_dump(&c->input); */
1128 /* check if the fixed size part of the packet is in buffer. */
1131 FD_SET(c->sock, readset);
1134 /* try to guess the protocol */
1135 p = buffer_ptr(&c->input);
1138 ret = channel_decode_socks4(c, readset, writeset);
1141 ret = channel_decode_socks5(c, readset, writeset);
1149 } else if (ret == 0) {
1150 debug2("channel %d: pre_dynamic: need more", c->self);
1152 FD_SET(c->sock, readset);
1154 /* switch to the next state */
1155 c->type = SSH_CHANNEL_OPENING;
1156 port_open_helper(c, "direct-tcpip");
1160 /* This is our fake X11 server socket. */
1162 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1165 struct sockaddr addr;
1168 char buf[16384], *remote_ipaddr;
1171 if (FD_ISSET(c->sock, readset)) {
1172 debug("X11 connection requested.");
1173 addrlen = sizeof(addr);
1174 newsock = accept(c->sock, &addr, &addrlen);
1175 if (c->single_connection) {
1176 debug2("single_connection: closing X11 listener.");
1177 channel_close_fd(&c->sock);
1181 error("accept: %.100s", strerror(errno));
1184 set_nodelay(newsock);
1185 remote_ipaddr = get_peer_ipaddr(newsock);
1186 remote_port = get_peer_port(newsock);
1187 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1188 remote_ipaddr, remote_port);
1190 nc = channel_new("accepted x11 socket",
1191 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1192 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1194 packet_start(SSH2_MSG_CHANNEL_OPEN);
1195 packet_put_cstring("x11");
1196 packet_put_int(nc->self);
1197 packet_put_int(nc->local_window_max);
1198 packet_put_int(nc->local_maxpacket);
1199 /* originator ipaddr and port */
1200 packet_put_cstring(remote_ipaddr);
1201 if (datafellows & SSH_BUG_X11FWD) {
1202 debug2("ssh2 x11 bug compat mode");
1204 packet_put_int(remote_port);
1208 packet_start(SSH_SMSG_X11_OPEN);
1209 packet_put_int(nc->self);
1210 if (packet_get_protocol_flags() &
1211 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1212 packet_put_cstring(buf);
1215 xfree(remote_ipaddr);
1220 port_open_helper(Channel *c, char *rtype)
1224 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1225 int remote_port = get_peer_port(c->sock);
1227 direct = (strcmp(rtype, "direct-tcpip") == 0);
1229 snprintf(buf, sizeof buf,
1230 "%s: listening port %d for %.100s port %d, "
1231 "connect from %.200s port %d",
1232 rtype, c->listening_port, c->path, c->host_port,
1233 remote_ipaddr, remote_port);
1235 xfree(c->remote_name);
1236 c->remote_name = xstrdup(buf);
1239 packet_start(SSH2_MSG_CHANNEL_OPEN);
1240 packet_put_cstring(rtype);
1241 packet_put_int(c->self);
1242 packet_put_int(c->local_window_max);
1243 packet_put_int(c->local_maxpacket);
1245 /* target host, port */
1246 packet_put_cstring(c->path);
1247 packet_put_int(c->host_port);
1249 /* listen address, port */
1250 packet_put_cstring(c->path);
1251 packet_put_int(c->listening_port);
1253 /* originator host and port */
1254 packet_put_cstring(remote_ipaddr);
1255 packet_put_int((u_int)remote_port);
1258 packet_start(SSH_MSG_PORT_OPEN);
1259 packet_put_int(c->self);
1260 packet_put_cstring(c->path);
1261 packet_put_int(c->host_port);
1262 if (packet_get_protocol_flags() &
1263 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1264 packet_put_cstring(c->remote_name);
1267 xfree(remote_ipaddr);
1271 channel_set_reuseaddr(int fd)
1276 * Set socket options.
1277 * Allow local port reuse in TIME_WAIT.
1279 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1280 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1284 * This socket is listening for connections to a forwarded TCP/IP port.
1287 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1290 struct sockaddr addr;
1291 int newsock, nextstate;
1295 if (FD_ISSET(c->sock, readset)) {
1296 debug("Connection to port %d forwarding "
1297 "to %.100s port %d requested.",
1298 c->listening_port, c->path, c->host_port);
1300 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1301 nextstate = SSH_CHANNEL_OPENING;
1302 rtype = "forwarded-tcpip";
1304 if (c->host_port == 0) {
1305 nextstate = SSH_CHANNEL_DYNAMIC;
1306 rtype = "dynamic-tcpip";
1308 nextstate = SSH_CHANNEL_OPENING;
1309 rtype = "direct-tcpip";
1313 addrlen = sizeof(addr);
1314 newsock = accept(c->sock, &addr, &addrlen);
1316 error("accept: %.100s", strerror(errno));
1319 set_nodelay(newsock);
1320 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1321 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1322 nc->listening_port = c->listening_port;
1323 nc->host_port = c->host_port;
1324 strlcpy(nc->path, c->path, sizeof(nc->path));
1326 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1328 * do not call the channel_post handler until
1329 * this flag has been reset by a pre-handler.
1330 * otherwise the FD_ISSET calls might overflow
1334 port_open_helper(nc, rtype);
1340 * This is the authentication agent socket listening for connections from
1344 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1348 struct sockaddr addr;
1351 if (FD_ISSET(c->sock, readset)) {
1352 addrlen = sizeof(addr);
1353 newsock = accept(c->sock, &addr, &addrlen);
1355 error("accept from auth socket: %.100s", strerror(errno));
1358 nc = channel_new("accepted auth socket",
1359 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1360 c->local_window_max, c->local_maxpacket,
1361 0, "accepted auth socket", 1);
1363 packet_start(SSH2_MSG_CHANNEL_OPEN);
1364 packet_put_cstring("auth-agent@openssh.com");
1365 packet_put_int(nc->self);
1366 packet_put_int(c->local_window_max);
1367 packet_put_int(c->local_maxpacket);
1369 packet_start(SSH_SMSG_AGENT_OPEN);
1370 packet_put_int(nc->self);
1377 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1380 socklen_t sz = sizeof(err);
1382 if (FD_ISSET(c->sock, writeset)) {
1383 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1385 error("getsockopt SO_ERROR failed");
1388 debug("channel %d: connected", c->self);
1389 c->type = SSH_CHANNEL_OPEN;
1391 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1392 packet_put_int(c->remote_id);
1393 packet_put_int(c->self);
1394 packet_put_int(c->local_window);
1395 packet_put_int(c->local_maxpacket);
1397 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1398 packet_put_int(c->remote_id);
1399 packet_put_int(c->self);
1402 debug("channel %d: not connected: %s",
1403 c->self, strerror(err));
1405 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1406 packet_put_int(c->remote_id);
1407 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1408 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1409 packet_put_cstring(strerror(err));
1410 packet_put_cstring("");
1413 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1414 packet_put_int(c->remote_id);
1423 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1425 char buf[CHAN_RBUF];
1429 FD_ISSET(c->rfd, readset)) {
1431 len = read(c->rfd, buf, sizeof(buf));
1432 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1434 #ifndef PTY_ZEROREAD
1437 if ((!c->isatty && len <= 0) ||
1438 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1440 debug2("channel %d: read<=0 rfd %d len %d",
1441 c->self, c->rfd, len);
1442 if (c->type != SSH_CHANNEL_OPEN) {
1443 debug2("channel %d: not open", c->self);
1446 } else if (compat13) {
1447 buffer_clear(&c->output);
1448 c->type = SSH_CHANNEL_INPUT_DRAINING;
1449 debug2("channel %d: input draining.", c->self);
1451 chan_read_failed(c);
1455 if (c->input_filter != NULL) {
1456 if (c->input_filter(c, buf, len) == -1) {
1457 debug2("channel %d: filter stops", c->self);
1458 chan_read_failed(c);
1460 } else if (c->datagram) {
1461 buffer_put_string(&c->input, buf, len);
1463 buffer_append(&c->input, buf, len);
1470 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1473 u_char *data = NULL, *buf;
1477 /* Send buffered output data to the socket. */
1479 FD_ISSET(c->wfd, writeset) &&
1480 buffer_len(&c->output) > 0) {
1481 if (c->output_filter != NULL) {
1482 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1483 debug2("channel %d: filter stops", c->self);
1484 if (c->type != SSH_CHANNEL_OPEN)
1487 chan_write_failed(c);
1490 } else if (c->datagram) {
1491 buf = data = buffer_get_string(&c->output, &dlen);
1493 buf = data = buffer_ptr(&c->output);
1494 dlen = buffer_len(&c->output);
1498 /* ignore truncated writes, datagrams might get lost */
1499 c->local_consumed += dlen + 4;
1500 len = write(c->wfd, buf, dlen);
1502 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1505 if (c->type != SSH_CHANNEL_OPEN)
1508 chan_write_failed(c);
1514 /* XXX: Later AIX versions can't push as much data to tty */
1515 if (compat20 && c->wfd_isatty)
1516 dlen = MIN(dlen, 8*1024);
1519 len = write(c->wfd, buf, dlen);
1520 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1523 if (c->type != SSH_CHANNEL_OPEN) {
1524 debug2("channel %d: not open", c->self);
1527 } else if (compat13) {
1528 buffer_clear(&c->output);
1529 debug2("channel %d: input draining.", c->self);
1530 c->type = SSH_CHANNEL_INPUT_DRAINING;
1532 chan_write_failed(c);
1536 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1537 if (tcgetattr(c->wfd, &tio) == 0 &&
1538 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1540 * Simulate echo to reduce the impact of
1541 * traffic analysis. We need to match the
1542 * size of a SSH2_MSG_CHANNEL_DATA message
1543 * (4 byte channel id + buf)
1545 packet_send_ignore(4 + len);
1549 buffer_consume(&c->output, len);
1550 if (compat20 && len > 0) {
1551 c->local_consumed += len;
1558 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1560 char buf[CHAN_RBUF];
1563 /** XXX handle drain efd, too */
1565 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1566 FD_ISSET(c->efd, writeset) &&
1567 buffer_len(&c->extended) > 0) {
1568 len = write(c->efd, buffer_ptr(&c->extended),
1569 buffer_len(&c->extended));
1570 debug2("channel %d: written %d to efd %d",
1571 c->self, len, c->efd);
1572 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1575 debug2("channel %d: closing write-efd %d",
1577 channel_close_fd(&c->efd);
1579 buffer_consume(&c->extended, len);
1580 c->local_consumed += len;
1582 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1583 FD_ISSET(c->efd, readset)) {
1584 len = read(c->efd, buf, sizeof(buf));
1585 debug2("channel %d: read %d from efd %d",
1586 c->self, len, c->efd);
1587 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1590 debug2("channel %d: closing read-efd %d",
1592 channel_close_fd(&c->efd);
1594 buffer_append(&c->extended, buf, len);
1602 channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
1607 /* Monitor control fd to detect if the slave client exits */
1608 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1609 len = read(c->ctl_fd, buf, sizeof(buf));
1610 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1613 debug2("channel %d: ctl read<=0", c->self);
1614 if (c->type != SSH_CHANNEL_OPEN) {
1615 debug2("channel %d: not open", c->self);
1619 chan_read_failed(c);
1620 chan_write_failed(c);
1624 fatal("%s: unexpected data on ctl fd", __func__);
1630 channel_check_window(Channel *c)
1632 if (c->type == SSH_CHANNEL_OPEN &&
1633 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1634 c->local_window < c->local_window_max/2 &&
1635 c->local_consumed > 0) {
1636 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1637 packet_put_int(c->remote_id);
1638 packet_put_int(c->local_consumed);
1640 debug2("channel %d: window %d sent adjust %d",
1641 c->self, c->local_window,
1643 c->local_window += c->local_consumed;
1644 c->local_consumed = 0;
1650 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1654 channel_handle_rfd(c, readset, writeset);
1655 channel_handle_wfd(c, readset, writeset);
1658 channel_handle_efd(c, readset, writeset);
1659 channel_handle_ctl(c, readset, writeset);
1660 channel_check_window(c);
1664 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1668 /* Send buffered output data to the socket. */
1669 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1670 len = write(c->sock, buffer_ptr(&c->output),
1671 buffer_len(&c->output));
1673 buffer_clear(&c->output);
1675 buffer_consume(&c->output, len);
1680 channel_handler_init_20(void)
1682 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1683 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1684 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1685 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1686 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1687 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1688 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1689 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1691 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1692 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1693 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1694 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1695 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1696 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1697 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1701 channel_handler_init_13(void)
1703 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1704 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1705 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1706 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1707 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1708 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1709 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1710 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1711 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1713 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1714 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1715 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1716 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1717 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1718 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1719 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1723 channel_handler_init_15(void)
1725 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1726 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1727 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1728 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1729 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1730 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1731 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1733 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1734 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1735 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1736 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1737 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1738 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1742 channel_handler_init(void)
1746 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1747 channel_pre[i] = NULL;
1748 channel_post[i] = NULL;
1751 channel_handler_init_20();
1753 channel_handler_init_13();
1755 channel_handler_init_15();
1758 /* gc dead channels */
1760 channel_garbage_collect(Channel *c)
1764 if (c->detach_user != NULL) {
1765 if (!chan_is_dead(c, c->detach_close))
1767 debug2("channel %d: gc: notify user", c->self);
1768 c->detach_user(c->self, NULL);
1769 /* if we still have a callback */
1770 if (c->detach_user != NULL)
1772 debug2("channel %d: gc: user detached", c->self);
1774 if (!chan_is_dead(c, 1))
1776 debug2("channel %d: garbage collecting", c->self);
1781 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1783 static int did_init = 0;
1788 channel_handler_init();
1791 for (i = 0; i < channels_alloc; i++) {
1795 if (ftab[c->type] != NULL)
1796 (*ftab[c->type])(c, readset, writeset);
1797 channel_garbage_collect(c);
1802 * Allocate/update select bitmasks and add any bits relevant to channels in
1806 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1807 u_int *nallocp, int rekeying)
1809 u_int n, sz, nfdset;
1811 n = MAX(*maxfdp, channel_max_fd);
1813 nfdset = howmany(n+1, NFDBITS);
1814 /* Explicitly test here, because xrealloc isn't always called */
1815 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
1816 fatal("channel_prepare_select: max_fd (%d) is too large", n);
1817 sz = nfdset * sizeof(fd_mask);
1819 /* perhaps check sz < nalloc/2 and shrink? */
1820 if (*readsetp == NULL || sz > *nallocp) {
1821 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
1822 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1826 memset(*readsetp, 0, sz);
1827 memset(*writesetp, 0, sz);
1830 channel_handler(channel_pre, *readsetp, *writesetp);
1834 * After select, perform any appropriate operations for channels which have
1838 channel_after_select(fd_set *readset, fd_set *writeset)
1840 channel_handler(channel_post, readset, writeset);
1844 /* If there is data to send to the connection, enqueue some of it now. */
1846 channel_output_poll(void)
1851 for (i = 0; i < channels_alloc; i++) {
1857 * We are only interested in channels that can have buffered
1861 if (c->type != SSH_CHANNEL_OPEN &&
1862 c->type != SSH_CHANNEL_INPUT_DRAINING)
1865 if (c->type != SSH_CHANNEL_OPEN)
1869 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1870 /* XXX is this true? */
1871 debug3("channel %d: will not send data after close", c->self);
1875 /* Get the amount of buffered data for this channel. */
1876 if ((c->istate == CHAN_INPUT_OPEN ||
1877 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1878 (len = buffer_len(&c->input)) > 0) {
1884 data = buffer_get_string(&c->input,
1886 packet_start(SSH2_MSG_CHANNEL_DATA);
1887 packet_put_int(c->remote_id);
1888 packet_put_string(data, dlen);
1890 c->remote_window -= dlen + 4;
1896 * Send some data for the other side over the secure
1900 if (len > c->remote_window)
1901 len = c->remote_window;
1902 if (len > c->remote_maxpacket)
1903 len = c->remote_maxpacket;
1905 if (packet_is_interactive()) {
1909 /* Keep the packets at reasonable size. */
1910 if (len > packet_get_maxsize()/2)
1911 len = packet_get_maxsize()/2;
1915 packet_start(compat20 ?
1916 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1917 packet_put_int(c->remote_id);
1918 packet_put_string(buffer_ptr(&c->input), len);
1920 buffer_consume(&c->input, len);
1921 c->remote_window -= len;
1923 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1925 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1927 * input-buffer is empty and read-socket shutdown:
1928 * tell peer, that we will not send more data: send IEOF.
1929 * hack for extended data: delay EOF if EFD still in use.
1931 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1932 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1933 c->self, c->efd, buffer_len(&c->extended));
1937 /* Send extended data, i.e. stderr */
1939 !(c->flags & CHAN_EOF_SENT) &&
1940 c->remote_window > 0 &&
1941 (len = buffer_len(&c->extended)) > 0 &&
1942 c->extended_usage == CHAN_EXTENDED_READ) {
1943 debug2("channel %d: rwin %u elen %u euse %d",
1944 c->self, c->remote_window, buffer_len(&c->extended),
1946 if (len > c->remote_window)
1947 len = c->remote_window;
1948 if (len > c->remote_maxpacket)
1949 len = c->remote_maxpacket;
1950 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1951 packet_put_int(c->remote_id);
1952 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1953 packet_put_string(buffer_ptr(&c->extended), len);
1955 buffer_consume(&c->extended, len);
1956 c->remote_window -= len;
1957 debug2("channel %d: sent ext data %d", c->self, len);
1963 /* -- protocol input */
1967 channel_input_data(int type, u_int32_t seq, void *ctxt)
1974 /* Get the channel number and verify it. */
1975 id = packet_get_int();
1976 c = channel_lookup(id);
1978 packet_disconnect("Received data for nonexistent channel %d.", id);
1980 /* Ignore any data for non-open channels (might happen on close) */
1981 if (c->type != SSH_CHANNEL_OPEN &&
1982 c->type != SSH_CHANNEL_X11_OPEN)
1986 data = packet_get_string(&data_len);
1989 * Ignore data for protocol > 1.3 if output end is no longer open.
1990 * For protocol 2 the sending side is reducing its window as it sends
1991 * data, so we must 'fake' consumption of the data in order to ensure
1992 * that window updates are sent back. Otherwise the connection might
1995 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
1997 c->local_window -= data_len;
1998 c->local_consumed += data_len;
2005 if (data_len > c->local_maxpacket) {
2006 logit("channel %d: rcvd big packet %d, maxpack %d",
2007 c->self, data_len, c->local_maxpacket);
2009 if (data_len > c->local_window) {
2010 logit("channel %d: rcvd too much data %d, win %d",
2011 c->self, data_len, c->local_window);
2015 c->local_window -= data_len;
2019 buffer_put_string(&c->output, data, data_len);
2021 buffer_append(&c->output, data, data_len);
2027 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2031 u_int data_len, tcode;
2034 /* Get the channel number and verify it. */
2035 id = packet_get_int();
2036 c = channel_lookup(id);
2039 packet_disconnect("Received extended_data for bad channel %d.", id);
2040 if (c->type != SSH_CHANNEL_OPEN) {
2041 logit("channel %d: ext data for non open", id);
2044 if (c->flags & CHAN_EOF_RCVD) {
2045 if (datafellows & SSH_BUG_EXTEOF)
2046 debug("channel %d: accepting ext data after eof", id);
2048 packet_disconnect("Received extended_data after EOF "
2049 "on channel %d.", id);
2051 tcode = packet_get_int();
2053 c->extended_usage != CHAN_EXTENDED_WRITE ||
2054 tcode != SSH2_EXTENDED_DATA_STDERR) {
2055 logit("channel %d: bad ext data", c->self);
2058 data = packet_get_string(&data_len);
2060 if (data_len > c->local_window) {
2061 logit("channel %d: rcvd too much extended_data %d, win %d",
2062 c->self, data_len, c->local_window);
2066 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2067 c->local_window -= data_len;
2068 buffer_append(&c->extended, data, data_len);
2074 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2079 id = packet_get_int();
2081 c = channel_lookup(id);
2083 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2086 /* XXX force input close */
2087 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2088 debug("channel %d: FORCE input drain", c->self);
2089 c->istate = CHAN_INPUT_WAIT_DRAIN;
2090 if (buffer_len(&c->input) == 0)
2098 channel_input_close(int type, u_int32_t seq, void *ctxt)
2103 id = packet_get_int();
2105 c = channel_lookup(id);
2107 packet_disconnect("Received close for nonexistent channel %d.", id);
2110 * Send a confirmation that we have closed the channel and no more
2111 * data is coming for it.
2113 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2114 packet_put_int(c->remote_id);
2118 * If the channel is in closed state, we have sent a close request,
2119 * and the other side will eventually respond with a confirmation.
2120 * Thus, we cannot free the channel here, because then there would be
2121 * no-one to receive the confirmation. The channel gets freed when
2122 * the confirmation arrives.
2124 if (c->type != SSH_CHANNEL_CLOSED) {
2126 * Not a closed channel - mark it as draining, which will
2127 * cause it to be freed later.
2129 buffer_clear(&c->input);
2130 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2134 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2137 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2139 int id = packet_get_int();
2140 Channel *c = channel_lookup(id);
2144 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2145 chan_rcvd_oclose(c);
2150 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2152 int id = packet_get_int();
2153 Channel *c = channel_lookup(id);
2157 packet_disconnect("Received close confirmation for "
2158 "out-of-range channel %d.", id);
2159 if (c->type != SSH_CHANNEL_CLOSED)
2160 packet_disconnect("Received close confirmation for "
2161 "non-closed channel %d (type %d).", id, c->type);
2167 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2172 id = packet_get_int();
2173 c = channel_lookup(id);
2175 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2176 packet_disconnect("Received open confirmation for "
2177 "non-opening channel %d.", id);
2178 remote_id = packet_get_int();
2179 /* Record the remote channel number and mark that the channel is now open. */
2180 c->remote_id = remote_id;
2181 c->type = SSH_CHANNEL_OPEN;
2184 c->remote_window = packet_get_int();
2185 c->remote_maxpacket = packet_get_int();
2187 debug2("callback start");
2188 c->confirm(c->self, c->confirm_ctx);
2189 debug2("callback done");
2191 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2192 c->remote_window, c->remote_maxpacket);
2198 reason2txt(int reason)
2201 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2202 return "administratively prohibited";
2203 case SSH2_OPEN_CONNECT_FAILED:
2204 return "connect failed";
2205 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2206 return "unknown channel type";
2207 case SSH2_OPEN_RESOURCE_SHORTAGE:
2208 return "resource shortage";
2210 return "unknown reason";
2215 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2218 char *msg = NULL, *lang = NULL;
2221 id = packet_get_int();
2222 c = channel_lookup(id);
2224 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2225 packet_disconnect("Received open failure for "
2226 "non-opening channel %d.", id);
2228 reason = packet_get_int();
2229 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2230 msg = packet_get_string(NULL);
2231 lang = packet_get_string(NULL);
2233 logit("channel %d: open failed: %s%s%s", id,
2234 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2241 /* Free the channel. This will also close the socket. */
2247 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2256 /* Get the channel number and verify it. */
2257 id = packet_get_int();
2258 c = channel_lookup(id);
2261 logit("Received window adjust for non-open channel %d.", id);
2264 adjust = packet_get_int();
2266 debug2("channel %d: rcvd adjust %u", id, adjust);
2267 c->remote_window += adjust;
2272 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2276 char *host, *originator_string;
2277 int remote_id, sock = -1;
2279 remote_id = packet_get_int();
2280 host = packet_get_string(NULL);
2281 host_port = packet_get_int();
2283 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2284 originator_string = packet_get_string(NULL);
2286 originator_string = xstrdup("unknown (remote did not supply name)");
2289 sock = channel_connect_to(host, host_port);
2291 c = channel_new("connected socket",
2292 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2293 originator_string, 1);
2294 c->remote_id = remote_id;
2296 xfree(originator_string);
2298 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2299 packet_put_int(remote_id);
2306 /* -- tcp forwarding */
2309 channel_set_af(int af)
2315 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2316 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2319 int sock, r, success = 0, wildcard = 0, is_client;
2320 struct addrinfo hints, *ai, *aitop;
2321 const char *host, *addr;
2322 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2324 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2325 listen_addr : host_to_connect;
2326 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2329 error("No forward host name.");
2332 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2333 error("Forward host name too long.");
2338 * Determine whether or not a port forward listens to loopback,
2339 * specified address or wildcard. On the client, a specified bind
2340 * address will always override gateway_ports. On the server, a
2341 * gateway_ports of 1 (``yes'') will override the client's
2342 * specification and force a wildcard bind, whereas a value of 2
2343 * (``clientspecified'') will bind to whatever address the client
2346 * Special-case listen_addrs are:
2348 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2349 * "" (empty string), "*" -> wildcard v4/v6
2350 * "localhost" -> loopback v4/v6
2353 if (listen_addr == NULL) {
2354 /* No address specified: default to gateway_ports setting */
2357 } else if (gateway_ports || is_client) {
2358 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2359 strcmp(listen_addr, "0.0.0.0") == 0) ||
2360 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2361 (!is_client && gateway_ports == 1))
2363 else if (strcmp(listen_addr, "localhost") != 0)
2367 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2368 type, wildcard, (addr == NULL) ? "NULL" : addr);
2371 * getaddrinfo returns a loopback address if the hostname is
2372 * set to NULL and hints.ai_flags is not AI_PASSIVE
2374 memset(&hints, 0, sizeof(hints));
2375 hints.ai_family = IPv4or6;
2376 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2377 hints.ai_socktype = SOCK_STREAM;
2378 snprintf(strport, sizeof strport, "%d", listen_port);
2379 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2381 /* This really shouldn't happen */
2382 packet_disconnect("getaddrinfo: fatal error: %s",
2385 error("channel_setup_fwd_listener: "
2386 "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
2391 for (ai = aitop; ai; ai = ai->ai_next) {
2392 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2394 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2395 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2396 error("channel_setup_fwd_listener: getnameinfo failed");
2399 /* Create a port to listen for the host. */
2400 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2402 /* this is no error since kernel may not support ipv6 */
2403 verbose("socket: %.100s", strerror(errno));
2407 channel_set_reuseaddr(sock);
2409 debug("Local forwarding listening on %s port %s.", ntop, strport);
2411 /* Bind the socket to the address. */
2412 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2413 /* address can be in use ipv6 address is already bound */
2415 error("bind: %.100s", strerror(errno));
2417 verbose("bind: %.100s", strerror(errno));
2422 /* Start listening for connections on the socket. */
2423 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2424 error("listen: %.100s", strerror(errno));
2428 /* Allocate a channel number for the socket. */
2429 c = channel_new("port listener", type, sock, sock, -1,
2430 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2431 0, "port listener", 1);
2432 strlcpy(c->path, host, sizeof(c->path));
2433 c->host_port = port_to_connect;
2434 c->listening_port = listen_port;
2438 error("channel_setup_fwd_listener: cannot listen to port: %d",
2440 freeaddrinfo(aitop);
2445 channel_cancel_rport_listener(const char *host, u_short port)
2450 for (i = 0; i < channels_alloc; i++) {
2451 Channel *c = channels[i];
2453 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2454 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2455 c->listening_port == port) {
2456 debug2("%s: close channel %d", __func__, i);
2465 /* protocol local port fwd, used by ssh (and sshd in v1) */
2467 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2468 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2470 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2471 listen_host, listen_port, host_to_connect, port_to_connect,
2475 /* protocol v2 remote port fwd, used by sshd */
2477 channel_setup_remote_fwd_listener(const char *listen_address,
2478 u_short listen_port, int gateway_ports)
2480 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2481 listen_address, listen_port, NULL, 0, gateway_ports);
2485 * Initiate forwarding of connections to port "port" on remote host through
2486 * the secure channel to host:port from local side.
2490 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2491 const char *host_to_connect, u_short port_to_connect)
2493 int type, success = 0;
2495 /* Record locally that connection to this host/port is permitted. */
2496 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2497 fatal("channel_request_remote_forwarding: too many forwards");
2499 /* Send the forward request to the remote side. */
2501 const char *address_to_bind;
2502 if (listen_host == NULL)
2503 address_to_bind = "localhost";
2504 else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
2505 address_to_bind = "";
2507 address_to_bind = listen_host;
2509 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2510 packet_put_cstring("tcpip-forward");
2511 packet_put_char(1); /* boolean: want reply */
2512 packet_put_cstring(address_to_bind);
2513 packet_put_int(listen_port);
2515 packet_write_wait();
2516 /* Assume that server accepts the request */
2519 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2520 packet_put_int(listen_port);
2521 packet_put_cstring(host_to_connect);
2522 packet_put_int(port_to_connect);
2524 packet_write_wait();
2526 /* Wait for response from the remote side. */
2527 type = packet_read();
2529 case SSH_SMSG_SUCCESS:
2532 case SSH_SMSG_FAILURE:
2535 /* Unknown packet */
2536 packet_disconnect("Protocol error for port forward request:"
2537 "received packet type %d.", type);
2541 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2542 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2543 permitted_opens[num_permitted_opens].listen_port = listen_port;
2544 num_permitted_opens++;
2546 return (success ? 0 : -1);
2550 * Request cancellation of remote forwarding of connection host:port from
2554 channel_request_rforward_cancel(const char *host, u_short port)
2561 for (i = 0; i < num_permitted_opens; i++) {
2562 if (permitted_opens[i].host_to_connect != NULL &&
2563 permitted_opens[i].listen_port == port)
2566 if (i >= num_permitted_opens) {
2567 debug("%s: requested forward not found", __func__);
2570 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2571 packet_put_cstring("cancel-tcpip-forward");
2573 packet_put_cstring(host == NULL ? "" : host);
2574 packet_put_int(port);
2577 permitted_opens[i].listen_port = 0;
2578 permitted_opens[i].port_to_connect = 0;
2579 xfree(permitted_opens[i].host_to_connect);
2580 permitted_opens[i].host_to_connect = NULL;
2584 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2585 * listening for the port, and sends back a success reply (or disconnect
2586 * message if there was an error).
2589 channel_input_port_forward_request(int is_root, int gateway_ports)
2591 u_short port, host_port;
2595 /* Get arguments from the packet. */
2596 port = packet_get_int();
2597 hostname = packet_get_string(NULL);
2598 host_port = packet_get_int();
2602 * Check that an unprivileged user is not trying to forward a
2605 if (port < IPPORT_RESERVED && !is_root)
2607 "Requested forwarding of port %d but user is not root.",
2610 packet_disconnect("Dynamic forwarding denied.");
2613 /* Initiate forwarding */
2614 success = channel_setup_local_fwd_listener(NULL, port, hostname,
2615 host_port, gateway_ports);
2617 /* Free the argument string. */
2620 return (success ? 0 : -1);
2624 * Permits opening to any host/port if permitted_opens[] is empty. This is
2625 * usually called by the server, because the user could connect to any port
2626 * anyway, and the server has no way to know but to trust the client anyway.
2629 channel_permit_all_opens(void)
2631 if (num_permitted_opens == 0)
2632 all_opens_permitted = 1;
2636 channel_add_permitted_opens(char *host, int port)
2638 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2639 fatal("channel_add_permitted_opens: too many forwards");
2640 debug("allow port forwarding to host %s port %d", host, port);
2642 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2643 permitted_opens[num_permitted_opens].port_to_connect = port;
2644 num_permitted_opens++;
2646 all_opens_permitted = 0;
2650 channel_clear_permitted_opens(void)
2654 for (i = 0; i < num_permitted_opens; i++)
2655 if (permitted_opens[i].host_to_connect != NULL)
2656 xfree(permitted_opens[i].host_to_connect);
2657 num_permitted_opens = 0;
2661 /* return socket to remote host, port */
2663 connect_to(const char *host, u_short port)
2665 struct addrinfo hints, *ai, *aitop;
2666 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2670 memset(&hints, 0, sizeof(hints));
2671 hints.ai_family = IPv4or6;
2672 hints.ai_socktype = SOCK_STREAM;
2673 snprintf(strport, sizeof strport, "%d", port);
2674 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2675 error("connect_to %.100s: unknown host (%s)", host,
2676 gai_strerror(gaierr));
2679 for (ai = aitop; ai; ai = ai->ai_next) {
2680 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2682 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2683 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2684 error("connect_to: getnameinfo failed");
2687 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2689 if (ai->ai_next == NULL)
2690 error("socket: %.100s", strerror(errno));
2692 verbose("socket: %.100s", strerror(errno));
2695 if (set_nonblock(sock) == -1)
2696 fatal("%s: set_nonblock(%d)", __func__, sock);
2697 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2698 errno != EINPROGRESS) {
2699 error("connect_to %.100s port %s: %.100s", ntop, strport,
2702 continue; /* fail -- try next */
2704 break; /* success */
2707 freeaddrinfo(aitop);
2709 error("connect_to %.100s port %d: failed.", host, port);
2718 channel_connect_by_listen_address(u_short listen_port)
2722 for (i = 0; i < num_permitted_opens; i++)
2723 if (permitted_opens[i].host_to_connect != NULL &&
2724 permitted_opens[i].listen_port == listen_port)
2726 permitted_opens[i].host_to_connect,
2727 permitted_opens[i].port_to_connect);
2728 error("WARNING: Server requests forwarding for unknown listen_port %d",
2733 /* Check if connecting to that port is permitted and connect. */
2735 channel_connect_to(const char *host, u_short port)
2739 permit = all_opens_permitted;
2741 for (i = 0; i < num_permitted_opens; i++)
2742 if (permitted_opens[i].host_to_connect != NULL &&
2743 permitted_opens[i].port_to_connect == port &&
2744 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2749 logit("Received request to connect to host %.100s port %d, "
2750 "but the request was denied.", host, port);
2753 return connect_to(host, port);
2757 channel_send_window_changes(void)
2762 for (i = 0; i < channels_alloc; i++) {
2763 if (channels[i] == NULL || !channels[i]->client_tty ||
2764 channels[i]->type != SSH_CHANNEL_OPEN)
2766 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2768 channel_request_start(i, "window-change", 0);
2769 packet_put_int((u_int)ws.ws_col);
2770 packet_put_int((u_int)ws.ws_row);
2771 packet_put_int((u_int)ws.ws_xpixel);
2772 packet_put_int((u_int)ws.ws_ypixel);
2777 /* -- X11 forwarding */
2780 * Creates an internet domain socket for listening for X11 connections.
2781 * Returns 0 and a suitable display number for the DISPLAY variable
2782 * stored in display_numberp , or -1 if an error occurs.
2785 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2786 int single_connection, u_int *display_numberp, int **chanids)
2789 int display_number, sock;
2791 struct addrinfo hints, *ai, *aitop;
2792 char strport[NI_MAXSERV];
2793 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2795 if (chanids == NULL)
2798 for (display_number = x11_display_offset;
2799 display_number < MAX_DISPLAYS;
2801 port = 6000 + display_number;
2802 memset(&hints, 0, sizeof(hints));
2803 hints.ai_family = IPv4or6;
2804 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2805 hints.ai_socktype = SOCK_STREAM;
2806 snprintf(strport, sizeof strport, "%d", port);
2807 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2808 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2811 for (ai = aitop; ai; ai = ai->ai_next) {
2812 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2814 sock = socket(ai->ai_family, ai->ai_socktype,
2817 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2818 error("socket: %.100s", strerror(errno));
2819 freeaddrinfo(aitop);
2822 debug("x11_create_display_inet: Socket family %d not supported",
2828 if (ai->ai_family == AF_INET6) {
2830 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2831 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2834 channel_set_reuseaddr(sock);
2835 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2836 debug2("bind port %d: %.100s", port, strerror(errno));
2842 for (n = 0; n < num_socks; n++) {
2848 socks[num_socks++] = sock;
2849 #ifndef DONT_TRY_OTHER_AF
2850 if (num_socks == NUM_SOCKS)
2853 if (x11_use_localhost) {
2854 if (num_socks == NUM_SOCKS)
2861 freeaddrinfo(aitop);
2865 if (display_number >= MAX_DISPLAYS) {
2866 error("Failed to allocate internet-domain X11 display socket.");
2869 /* Start listening for connections on the socket. */
2870 for (n = 0; n < num_socks; n++) {
2872 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2873 error("listen: %.100s", strerror(errno));
2879 /* Allocate a channel for each socket. */
2880 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
2881 for (n = 0; n < num_socks; n++) {
2883 nc = channel_new("x11 listener",
2884 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2885 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2886 0, "X11 inet listener", 1);
2887 nc->single_connection = single_connection;
2888 (*chanids)[n] = nc->self;
2892 /* Return the display number for the DISPLAY environment variable. */
2893 *display_numberp = display_number;
2898 connect_local_xsocket(u_int dnr)
2901 struct sockaddr_un addr;
2903 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2905 error("socket: %.100s", strerror(errno));
2906 memset(&addr, 0, sizeof(addr));
2907 addr.sun_family = AF_UNIX;
2908 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2909 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
2912 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2917 x11_connect_display(void)
2919 u_int display_number;
2920 const char *display;
2921 char buf[1024], *cp;
2922 struct addrinfo hints, *ai, *aitop;
2923 char strport[NI_MAXSERV];
2924 int gaierr, sock = 0;
2926 /* Try to open a socket for the local X server. */
2927 display = getenv("DISPLAY");
2929 error("DISPLAY not set.");
2933 * Now we decode the value of the DISPLAY variable and make a
2934 * connection to the real X server.
2938 * Check if it is a unix domain socket. Unix domain displays are in
2939 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2941 if (strncmp(display, "unix:", 5) == 0 ||
2942 display[0] == ':') {
2943 /* Connect to the unix domain socket. */
2944 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
2945 error("Could not parse display number from DISPLAY: %.100s",
2949 /* Create a socket. */
2950 sock = connect_local_xsocket(display_number);
2954 /* OK, we now have a connection to the display. */
2958 * Connect to an inet socket. The DISPLAY value is supposedly
2959 * hostname:d[.s], where hostname may also be numeric IP address.
2961 strlcpy(buf, display, sizeof(buf));
2962 cp = strchr(buf, ':');
2964 error("Could not find ':' in DISPLAY: %.100s", display);
2968 /* buf now contains the host name. But first we parse the display number. */
2969 if (sscanf(cp + 1, "%u", &display_number) != 1) {
2970 error("Could not parse display number from DISPLAY: %.100s",
2975 /* Look up the host address */
2976 memset(&hints, 0, sizeof(hints));
2977 hints.ai_family = IPv4or6;
2978 hints.ai_socktype = SOCK_STREAM;
2979 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
2980 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2981 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2984 for (ai = aitop; ai; ai = ai->ai_next) {
2985 /* Create a socket. */
2986 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2988 debug2("socket: %.100s", strerror(errno));
2991 /* Connect it to the display. */
2992 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2993 debug2("connect %.100s port %u: %.100s", buf,
2994 6000 + display_number, strerror(errno));
3001 freeaddrinfo(aitop);
3003 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3012 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3013 * the remote channel number. We should do whatever we want, and respond
3014 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3018 x11_input_open(int type, u_int32_t seq, void *ctxt)
3021 int remote_id, sock = 0;
3024 debug("Received X11 open request.");
3026 remote_id = packet_get_int();
3028 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3029 remote_host = packet_get_string(NULL);
3031 remote_host = xstrdup("unknown (remote did not supply name)");
3035 /* Obtain a connection to the real X display. */
3036 sock = x11_connect_display();
3038 /* Allocate a channel for this connection. */
3039 c = channel_new("connected x11 socket",
3040 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3042 c->remote_id = remote_id;
3047 /* Send refusal to the remote host. */
3048 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3049 packet_put_int(remote_id);
3051 /* Send a confirmation to the remote host. */
3052 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3053 packet_put_int(remote_id);
3054 packet_put_int(c->self);
3059 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3061 deny_input_open(int type, u_int32_t seq, void *ctxt)
3063 int rchan = packet_get_int();
3066 case SSH_SMSG_AGENT_OPEN:
3067 error("Warning: ssh server tried agent forwarding.");
3069 case SSH_SMSG_X11_OPEN:
3070 error("Warning: ssh server tried X11 forwarding.");
3073 error("deny_input_open: type %d", type);
3076 error("Warning: this is probably a break-in attempt by a malicious server.");
3077 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3078 packet_put_int(rchan);
3083 * Requests forwarding of X11 connections, generates fake authentication
3084 * data, and enables authentication spoofing.
3085 * This should be called in the client only.
3088 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3089 const char *proto, const char *data)
3091 u_int data_len = (u_int) strlen(data) / 2;
3098 if (x11_saved_display == NULL)
3099 x11_saved_display = xstrdup(disp);
3100 else if (strcmp(disp, x11_saved_display) != 0) {
3101 error("x11_request_forwarding_with_spoofing: different "
3102 "$DISPLAY already forwarded");
3108 cp = strchr(disp, ':');
3110 cp = strchr(cp, '.');
3112 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3116 if (x11_saved_proto == NULL) {
3117 /* Save protocol name. */
3118 x11_saved_proto = xstrdup(proto);
3120 * Extract real authentication data and generate fake data
3121 * of the same length.
3123 x11_saved_data = xmalloc(data_len);
3124 x11_fake_data = xmalloc(data_len);
3125 for (i = 0; i < data_len; i++) {
3126 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3127 fatal("x11_request_forwarding: bad "
3128 "authentication data: %.100s", data);
3131 x11_saved_data[i] = value;
3132 x11_fake_data[i] = rnd & 0xff;
3135 x11_saved_data_len = data_len;
3136 x11_fake_data_len = data_len;
3139 /* Convert the fake data into hex. */
3140 new_data = tohex(x11_fake_data, data_len);
3142 /* Send the request packet. */
3144 channel_request_start(client_session_id, "x11-req", 0);
3145 packet_put_char(0); /* XXX bool single connection */
3147 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3149 packet_put_cstring(proto);
3150 packet_put_cstring(new_data);
3151 packet_put_int(screen_number);
3153 packet_write_wait();
3158 /* -- agent forwarding */
3160 /* Sends a message to the server to request authentication fd forwarding. */
3163 auth_request_forwarding(void)
3165 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3167 packet_write_wait();