1 /* $OpenBSD: channels.c,v 1.275 2008/05/08 12:02:23 djm 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/types.h>
45 #include <sys/ioctl.h>
47 #include <sys/socket.h>
48 #ifdef HAVE_SYS_TIME_H
49 # include <sys/time.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
64 #include "openbsd-compat/sys-queue.h"
78 #include "pathnames.h"
83 * Pointer to an array containing all allocated channels. The array is
84 * dynamically extended as needed.
86 static Channel **channels = NULL;
89 * Size of the channel array. All slots of the array must always be
90 * initialized (at least the type field); unused slots set to NULL
92 static u_int channels_alloc = 0;
95 * Maximum file descriptor value used in any of the channels. This is
96 * updated in channel_new.
98 static int channel_max_fd = 0;
101 /* -- tcp forwarding */
104 * Data structure for storing which hosts are permitted for forward requests.
105 * The local sides of any remote forwards are stored in this array to prevent
106 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
107 * network (which might be behind a firewall).
110 char *host_to_connect; /* Connect to 'host'. */
111 u_short port_to_connect; /* Connect to 'port'. */
112 u_short listen_port; /* Remote side should listen port number. */
115 /* List of all permitted host/port pairs to connect by the user. */
116 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
118 /* List of all permitted host/port pairs to connect by the admin. */
119 static ForwardPermission permitted_adm_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
121 /* Number of permitted host/port pairs in the array permitted by the user. */
122 static int num_permitted_opens = 0;
124 /* Number of permitted host/port pair in the array permitted by the admin. */
125 static int num_adm_permitted_opens = 0;
128 * If this is true, all opens are permitted. This is the case on the server
129 * on which we have to trust the client anyway, and the user could do
130 * anything after logging in anyway.
132 static int all_opens_permitted = 0;
135 /* -- X11 forwarding */
137 /* Maximum number of fake X11 displays to try. */
138 #define MAX_DISPLAYS 1000
140 /* Saved X11 local (client) display. */
141 static char *x11_saved_display = NULL;
143 /* Saved X11 authentication protocol name. */
144 static char *x11_saved_proto = NULL;
146 /* Saved X11 authentication data. This is the real data. */
147 static char *x11_saved_data = NULL;
148 static u_int x11_saved_data_len = 0;
151 * Fake X11 authentication data. This is what the server will be sending us;
152 * we should replace any occurrences of this by the real data.
154 static u_char *x11_fake_data = NULL;
155 static u_int x11_fake_data_len;
158 /* -- agent forwarding */
162 /* AF_UNSPEC or AF_INET or AF_INET6 */
163 static int IPv4or6 = AF_UNSPEC;
166 static void port_open_helper(Channel *c, char *rtype);
168 /* -- channel core */
171 channel_by_id(int id)
175 if (id < 0 || (u_int)id >= channels_alloc) {
176 logit("channel_by_id: %d: bad id", id);
181 logit("channel_by_id: %d: bad id: channel free", id);
188 * Returns the channel if it is allowed to receive protocol messages.
189 * Private channels, like listening sockets, may not receive messages.
192 channel_lookup(int id)
196 if ((c = channel_by_id(id)) == NULL)
200 case SSH_CHANNEL_X11_OPEN:
201 case SSH_CHANNEL_LARVAL:
202 case SSH_CHANNEL_CONNECTING:
203 case SSH_CHANNEL_DYNAMIC:
204 case SSH_CHANNEL_OPENING:
205 case SSH_CHANNEL_OPEN:
206 case SSH_CHANNEL_INPUT_DRAINING:
207 case SSH_CHANNEL_OUTPUT_DRAINING:
210 logit("Non-public channel %d, type %d.", id, c->type);
215 * Register filedescriptors for a channel, used when allocating a channel or
216 * when the channel consumer/producer is ready, e.g. shell exec'd
219 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
220 int extusage, int nonblock)
222 /* Update the maximum file descriptor value. */
223 channel_max_fd = MAX(channel_max_fd, rfd);
224 channel_max_fd = MAX(channel_max_fd, wfd);
225 channel_max_fd = MAX(channel_max_fd, efd);
227 /* XXX set close-on-exec -markus */
231 c->sock = (rfd == wfd) ? rfd : -1;
232 c->ctl_fd = -1; /* XXX: set elsewhere */
234 c->extended_usage = extusage;
236 /* XXX ugly hack: nonblock is only set by the server */
237 if (nonblock && isatty(c->rfd)) {
238 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
240 if (!isatty(c->wfd)) {
241 error("channel %d: wfd %d is not a tty?",
247 c->wfd_isatty = isatty(c->wfd);
249 /* enable nonblocking mode */
261 * Allocate a new channel object and set its type and socket. This will cause
262 * remote_name to be freed.
265 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
266 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
272 /* Do initial allocation if this is the first call. */
273 if (channels_alloc == 0) {
275 channels = xcalloc(channels_alloc, sizeof(Channel *));
276 for (i = 0; i < channels_alloc; i++)
279 /* Try to find a free slot where to put the new channel. */
280 for (found = -1, i = 0; i < channels_alloc; i++)
281 if (channels[i] == NULL) {
282 /* Found a free slot. */
287 /* There are no free slots. Take last+1 slot and expand the array. */
288 found = channels_alloc;
289 if (channels_alloc > 10000)
290 fatal("channel_new: internal error: channels_alloc %d "
291 "too big.", channels_alloc);
292 channels = xrealloc(channels, channels_alloc + 10,
294 channels_alloc += 10;
295 debug2("channel: expanding %d", channels_alloc);
296 for (i = found; i < channels_alloc; i++)
299 /* Initialize and return new channel. */
300 c = channels[found] = xcalloc(1, sizeof(Channel));
301 buffer_init(&c->input);
302 buffer_init(&c->output);
303 buffer_init(&c->extended);
304 c->ostate = CHAN_OUTPUT_OPEN;
305 c->istate = CHAN_INPUT_OPEN;
307 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
311 c->local_window = window;
312 c->local_window_max = window;
313 c->local_consumed = 0;
314 c->local_maxpacket = maxpack;
316 c->remote_name = xstrdup(remote_name);
317 c->remote_window = 0;
318 c->remote_maxpacket = 0;
320 c->single_connection = 0;
321 c->detach_user = NULL;
323 c->open_confirm = NULL;
324 c->open_confirm_ctx = NULL;
325 c->input_filter = NULL;
326 c->output_filter = NULL;
327 TAILQ_INIT(&c->status_confirms);
328 debug("channel %d: new [%s]", found, remote_name);
333 channel_find_maxfd(void)
339 for (i = 0; i < channels_alloc; i++) {
342 max = MAX(max, c->rfd);
343 max = MAX(max, c->wfd);
344 max = MAX(max, c->efd);
351 channel_close_fd(int *fdp)
353 int ret = 0, fd = *fdp;
358 if (fd == channel_max_fd)
359 channel_max_fd = channel_find_maxfd();
364 /* Close all channel fd/socket. */
366 channel_close_fds(Channel *c)
368 debug3("channel %d: close_fds r %d w %d e %d c %d",
369 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
371 channel_close_fd(&c->sock);
372 channel_close_fd(&c->ctl_fd);
373 channel_close_fd(&c->rfd);
374 channel_close_fd(&c->wfd);
375 channel_close_fd(&c->efd);
378 /* Free the channel and close its fd/socket. */
380 channel_free(Channel *c)
384 struct channel_confirm *cc;
386 for (n = 0, i = 0; i < channels_alloc; i++)
389 debug("channel %d: free: %s, nchannels %u", c->self,
390 c->remote_name ? c->remote_name : "???", n);
392 s = channel_open_message();
393 debug3("channel %d: status: %s", c->self, s);
397 shutdown(c->sock, SHUT_RDWR);
399 shutdown(c->ctl_fd, SHUT_RDWR);
400 channel_close_fds(c);
401 buffer_free(&c->input);
402 buffer_free(&c->output);
403 buffer_free(&c->extended);
404 if (c->remote_name) {
405 xfree(c->remote_name);
406 c->remote_name = NULL;
408 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
409 if (cc->abandon_cb != NULL)
410 cc->abandon_cb(c, cc->ctx);
411 TAILQ_REMOVE(&c->status_confirms, cc, entry);
412 bzero(cc, sizeof(*cc));
415 channels[c->self] = NULL;
420 channel_free_all(void)
424 for (i = 0; i < channels_alloc; i++)
425 if (channels[i] != NULL)
426 channel_free(channels[i]);
430 * Closes the sockets/fds of all channels. This is used to close extra file
431 * descriptors after a fork.
434 channel_close_all(void)
438 for (i = 0; i < channels_alloc; i++)
439 if (channels[i] != NULL)
440 channel_close_fds(channels[i]);
444 * Stop listening to channels.
447 channel_stop_listening(void)
452 for (i = 0; i < channels_alloc; i++) {
456 case SSH_CHANNEL_AUTH_SOCKET:
457 case SSH_CHANNEL_PORT_LISTENER:
458 case SSH_CHANNEL_RPORT_LISTENER:
459 case SSH_CHANNEL_X11_LISTENER:
460 channel_close_fd(&c->sock);
469 * Returns true if no channel has too much buffered data, and false if one or
470 * more channel is overfull.
473 channel_not_very_much_buffered_data(void)
478 for (i = 0; i < channels_alloc; i++) {
480 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
483 buffer_len(&c->input) > packet_get_maxsize()) {
484 debug2("channel %d: big input buffer %d",
485 c->self, buffer_len(&c->input));
489 if (buffer_len(&c->output) > packet_get_maxsize()) {
490 debug2("channel %d: big output buffer %u > %u",
491 c->self, buffer_len(&c->output),
492 packet_get_maxsize());
500 /* Returns true if any channel is still open. */
502 channel_still_open(void)
507 for (i = 0; i < channels_alloc; i++) {
512 case SSH_CHANNEL_X11_LISTENER:
513 case SSH_CHANNEL_PORT_LISTENER:
514 case SSH_CHANNEL_RPORT_LISTENER:
515 case SSH_CHANNEL_CLOSED:
516 case SSH_CHANNEL_AUTH_SOCKET:
517 case SSH_CHANNEL_DYNAMIC:
518 case SSH_CHANNEL_CONNECTING:
519 case SSH_CHANNEL_ZOMBIE:
521 case SSH_CHANNEL_LARVAL:
523 fatal("cannot happen: SSH_CHANNEL_LARVAL");
525 case SSH_CHANNEL_OPENING:
526 case SSH_CHANNEL_OPEN:
527 case SSH_CHANNEL_X11_OPEN:
529 case SSH_CHANNEL_INPUT_DRAINING:
530 case SSH_CHANNEL_OUTPUT_DRAINING:
532 fatal("cannot happen: OUT_DRAIN");
535 fatal("channel_still_open: bad channel type %d", c->type);
542 /* Returns the id of an open channel suitable for keepaliving */
544 channel_find_open(void)
549 for (i = 0; i < channels_alloc; i++) {
551 if (c == NULL || c->remote_id < 0)
554 case SSH_CHANNEL_CLOSED:
555 case SSH_CHANNEL_DYNAMIC:
556 case SSH_CHANNEL_X11_LISTENER:
557 case SSH_CHANNEL_PORT_LISTENER:
558 case SSH_CHANNEL_RPORT_LISTENER:
559 case SSH_CHANNEL_OPENING:
560 case SSH_CHANNEL_CONNECTING:
561 case SSH_CHANNEL_ZOMBIE:
563 case SSH_CHANNEL_LARVAL:
564 case SSH_CHANNEL_AUTH_SOCKET:
565 case SSH_CHANNEL_OPEN:
566 case SSH_CHANNEL_X11_OPEN:
568 case SSH_CHANNEL_INPUT_DRAINING:
569 case SSH_CHANNEL_OUTPUT_DRAINING:
571 fatal("cannot happen: OUT_DRAIN");
574 fatal("channel_find_open: bad channel type %d", c->type);
583 * Returns a message describing the currently open forwarded connections,
584 * suitable for sending to the client. The message contains crlf pairs for
588 channel_open_message(void)
595 buffer_init(&buffer);
596 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
597 buffer_append(&buffer, buf, strlen(buf));
598 for (i = 0; i < channels_alloc; i++) {
603 case SSH_CHANNEL_X11_LISTENER:
604 case SSH_CHANNEL_PORT_LISTENER:
605 case SSH_CHANNEL_RPORT_LISTENER:
606 case SSH_CHANNEL_CLOSED:
607 case SSH_CHANNEL_AUTH_SOCKET:
608 case SSH_CHANNEL_ZOMBIE:
610 case SSH_CHANNEL_LARVAL:
611 case SSH_CHANNEL_OPENING:
612 case SSH_CHANNEL_CONNECTING:
613 case SSH_CHANNEL_DYNAMIC:
614 case SSH_CHANNEL_OPEN:
615 case SSH_CHANNEL_X11_OPEN:
616 case SSH_CHANNEL_INPUT_DRAINING:
617 case SSH_CHANNEL_OUTPUT_DRAINING:
618 snprintf(buf, sizeof buf,
619 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
620 c->self, c->remote_name,
621 c->type, c->remote_id,
622 c->istate, buffer_len(&c->input),
623 c->ostate, buffer_len(&c->output),
624 c->rfd, c->wfd, c->ctl_fd);
625 buffer_append(&buffer, buf, strlen(buf));
628 fatal("channel_open_message: bad channel type %d", c->type);
632 buffer_append(&buffer, "\0", 1);
633 cp = xstrdup(buffer_ptr(&buffer));
634 buffer_free(&buffer);
639 channel_send_open(int id)
641 Channel *c = channel_lookup(id);
644 logit("channel_send_open: %d: bad id", id);
647 debug2("channel %d: send open", id);
648 packet_start(SSH2_MSG_CHANNEL_OPEN);
649 packet_put_cstring(c->ctype);
650 packet_put_int(c->self);
651 packet_put_int(c->local_window);
652 packet_put_int(c->local_maxpacket);
657 channel_request_start(int id, char *service, int wantconfirm)
659 Channel *c = channel_lookup(id);
662 logit("channel_request_start: %d: unknown channel id", id);
665 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
666 packet_start(SSH2_MSG_CHANNEL_REQUEST);
667 packet_put_int(c->remote_id);
668 packet_put_cstring(service);
669 packet_put_char(wantconfirm);
673 channel_register_status_confirm(int id, channel_confirm_cb *cb,
674 channel_confirm_abandon_cb *abandon_cb, void *ctx)
676 struct channel_confirm *cc;
679 if ((c = channel_lookup(id)) == NULL)
680 fatal("channel_register_expect: %d: bad id", id);
682 cc = xmalloc(sizeof(*cc));
684 cc->abandon_cb = abandon_cb;
686 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
690 channel_register_open_confirm(int id, channel_callback_fn *fn, void *ctx)
692 Channel *c = channel_lookup(id);
695 logit("channel_register_open_comfirm: %d: bad id", id);
698 c->open_confirm = fn;
699 c->open_confirm_ctx = ctx;
703 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
705 Channel *c = channel_by_id(id);
708 logit("channel_register_cleanup: %d: bad id", id);
712 c->detach_close = do_close;
716 channel_cancel_cleanup(int id)
718 Channel *c = channel_by_id(id);
721 logit("channel_cancel_cleanup: %d: bad id", id);
724 c->detach_user = NULL;
729 channel_register_filter(int id, channel_infilter_fn *ifn,
730 channel_outfilter_fn *ofn)
732 Channel *c = channel_lookup(id);
735 logit("channel_register_filter: %d: bad id", id);
738 c->input_filter = ifn;
739 c->output_filter = ofn;
743 channel_set_fds(int id, int rfd, int wfd, int efd,
744 int extusage, int nonblock, u_int window_max)
746 Channel *c = channel_lookup(id);
748 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
749 fatal("channel_activate for non-larval channel %d.", id);
750 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
751 c->type = SSH_CHANNEL_OPEN;
752 c->local_window = c->local_window_max = window_max;
753 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
754 packet_put_int(c->remote_id);
755 packet_put_int(c->local_window);
760 * 'channel_pre*' are called just before select() to add any bits relevant to
761 * channels in the select bitmasks.
764 * 'channel_post*': perform any appropriate operations for channels which
765 * have events pending.
767 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
768 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
769 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
773 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
775 FD_SET(c->sock, readset);
780 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
782 debug3("channel %d: waiting for connection", c->self);
783 FD_SET(c->sock, writeset);
787 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
789 if (buffer_len(&c->input) < packet_get_maxsize())
790 FD_SET(c->sock, readset);
791 if (buffer_len(&c->output) > 0)
792 FD_SET(c->sock, writeset);
796 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
798 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
800 if (c->istate == CHAN_INPUT_OPEN &&
802 buffer_len(&c->input) < limit &&
803 buffer_check_alloc(&c->input, CHAN_RBUF))
804 FD_SET(c->rfd, readset);
805 if (c->ostate == CHAN_OUTPUT_OPEN ||
806 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
807 if (buffer_len(&c->output) > 0) {
808 FD_SET(c->wfd, writeset);
809 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
810 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
811 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
812 c->self, c->efd, buffer_len(&c->extended));
817 /** XXX check close conditions, too */
818 if (compat20 && c->efd != -1) {
819 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
820 buffer_len(&c->extended) > 0)
821 FD_SET(c->efd, writeset);
822 else if (!(c->flags & CHAN_EOF_SENT) &&
823 c->extended_usage == CHAN_EXTENDED_READ &&
824 buffer_len(&c->extended) < c->remote_window)
825 FD_SET(c->efd, readset);
827 /* XXX: What about efd? races? */
828 if (compat20 && c->ctl_fd != -1 &&
829 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
830 FD_SET(c->ctl_fd, readset);
835 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
837 if (buffer_len(&c->input) == 0) {
838 packet_start(SSH_MSG_CHANNEL_CLOSE);
839 packet_put_int(c->remote_id);
841 c->type = SSH_CHANNEL_CLOSED;
842 debug2("channel %d: closing after input drain.", c->self);
848 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
850 if (buffer_len(&c->output) == 0)
853 FD_SET(c->sock, writeset);
857 * This is a special state for X11 authentication spoofing. An opened X11
858 * connection (when authentication spoofing is being done) remains in this
859 * state until the first packet has been completely read. The authentication
860 * data in that packet is then substituted by the real data if it matches the
861 * fake data, and the channel is put into normal mode.
862 * XXX All this happens at the client side.
863 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
866 x11_open_helper(Buffer *b)
869 u_int proto_len, data_len;
871 /* Check if the fixed size part of the packet is in buffer. */
872 if (buffer_len(b) < 12)
875 /* Parse the lengths of variable-length fields. */
877 if (ucp[0] == 0x42) { /* Byte order MSB first. */
878 proto_len = 256 * ucp[6] + ucp[7];
879 data_len = 256 * ucp[8] + ucp[9];
880 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
881 proto_len = ucp[6] + 256 * ucp[7];
882 data_len = ucp[8] + 256 * ucp[9];
884 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
889 /* Check if the whole packet is in buffer. */
891 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
894 /* Check if authentication protocol matches. */
895 if (proto_len != strlen(x11_saved_proto) ||
896 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
897 debug2("X11 connection uses different authentication protocol.");
900 /* Check if authentication data matches our fake data. */
901 if (data_len != x11_fake_data_len ||
902 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
903 x11_fake_data, x11_fake_data_len) != 0) {
904 debug2("X11 auth data does not match fake data.");
907 /* Check fake data length */
908 if (x11_fake_data_len != x11_saved_data_len) {
909 error("X11 fake_data_len %d != saved_data_len %d",
910 x11_fake_data_len, x11_saved_data_len);
914 * Received authentication protocol and data match
915 * our fake data. Substitute the fake data with real
918 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
919 x11_saved_data, x11_saved_data_len);
924 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
926 int ret = x11_open_helper(&c->output);
929 /* Start normal processing for the channel. */
930 c->type = SSH_CHANNEL_OPEN;
931 channel_pre_open_13(c, readset, writeset);
932 } else if (ret == -1) {
934 * We have received an X11 connection that has bad
935 * authentication information.
937 logit("X11 connection rejected because of wrong authentication.");
938 buffer_clear(&c->input);
939 buffer_clear(&c->output);
940 channel_close_fd(&c->sock);
942 c->type = SSH_CHANNEL_CLOSED;
943 packet_start(SSH_MSG_CHANNEL_CLOSE);
944 packet_put_int(c->remote_id);
950 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
952 int ret = x11_open_helper(&c->output);
954 /* c->force_drain = 1; */
957 c->type = SSH_CHANNEL_OPEN;
958 channel_pre_open(c, readset, writeset);
959 } else if (ret == -1) {
960 logit("X11 connection rejected because of wrong authentication.");
961 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
963 buffer_clear(&c->input);
965 buffer_clear(&c->output);
966 /* for proto v1, the peer will send an IEOF */
968 chan_write_failed(c);
970 c->type = SSH_CHANNEL_OPEN;
971 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
975 /* try to decode a socks4 header */
978 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
981 u_int len, have, i, found;
987 struct in_addr dest_addr;
990 debug2("channel %d: decode socks4", c->self);
992 have = buffer_len(&c->input);
993 len = sizeof(s4_req);
996 p = buffer_ptr(&c->input);
997 for (found = 0, i = len; i < have; i++) {
1003 /* the peer is probably sending garbage */
1004 debug("channel %d: decode socks4: too long",
1011 buffer_get(&c->input, (char *)&s4_req.version, 1);
1012 buffer_get(&c->input, (char *)&s4_req.command, 1);
1013 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1014 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1015 have = buffer_len(&c->input);
1016 p = buffer_ptr(&c->input);
1018 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1020 fatal("channel %d: decode socks4: len %d > have %d",
1021 c->self, len, have);
1022 strlcpy(username, p, sizeof(username));
1023 buffer_consume(&c->input, len);
1024 buffer_consume(&c->input, 1); /* trailing '\0' */
1026 host = inet_ntoa(s4_req.dest_addr);
1027 strlcpy(c->path, host, sizeof(c->path));
1028 c->host_port = ntohs(s4_req.dest_port);
1030 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1031 c->self, host, c->host_port, s4_req.command);
1033 if (s4_req.command != 1) {
1034 debug("channel %d: cannot handle: socks4 cn %d",
1035 c->self, s4_req.command);
1038 s4_rsp.version = 0; /* vn: 0 for reply */
1039 s4_rsp.command = 90; /* cd: req granted */
1040 s4_rsp.dest_port = 0; /* ignored */
1041 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1042 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1046 /* try to decode a socks5 header */
1047 #define SSH_SOCKS5_AUTHDONE 0x1000
1048 #define SSH_SOCKS5_NOAUTH 0x00
1049 #define SSH_SOCKS5_IPV4 0x01
1050 #define SSH_SOCKS5_DOMAIN 0x03
1051 #define SSH_SOCKS5_IPV6 0x04
1052 #define SSH_SOCKS5_CONNECT 0x01
1053 #define SSH_SOCKS5_SUCCESS 0x00
1057 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1065 u_int16_t dest_port;
1066 u_char *p, dest_addr[255+1];
1067 u_int have, need, i, found, nmethods, addrlen, af;
1069 debug2("channel %d: decode socks5", c->self);
1070 p = buffer_ptr(&c->input);
1073 have = buffer_len(&c->input);
1074 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1075 /* format: ver | nmethods | methods */
1079 if (have < nmethods + 2)
1081 /* look for method: "NO AUTHENTICATION REQUIRED" */
1082 for (found = 0, i = 2; i < nmethods + 2; i++) {
1083 if (p[i] == SSH_SOCKS5_NOAUTH) {
1089 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1093 buffer_consume(&c->input, nmethods + 2);
1094 buffer_put_char(&c->output, 0x05); /* version */
1095 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1096 FD_SET(c->sock, writeset);
1097 c->flags |= SSH_SOCKS5_AUTHDONE;
1098 debug2("channel %d: socks5 auth done", c->self);
1099 return 0; /* need more */
1101 debug2("channel %d: socks5 post auth", c->self);
1102 if (have < sizeof(s5_req)+1)
1103 return 0; /* need more */
1104 memcpy(&s5_req, p, sizeof(s5_req));
1105 if (s5_req.version != 0x05 ||
1106 s5_req.command != SSH_SOCKS5_CONNECT ||
1107 s5_req.reserved != 0x00) {
1108 debug2("channel %d: only socks5 connect supported", c->self);
1111 switch (s5_req.atyp){
1112 case SSH_SOCKS5_IPV4:
1116 case SSH_SOCKS5_DOMAIN:
1117 addrlen = p[sizeof(s5_req)];
1120 case SSH_SOCKS5_IPV6:
1125 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1128 need = sizeof(s5_req) + addrlen + 2;
1129 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1133 buffer_consume(&c->input, sizeof(s5_req));
1134 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1135 buffer_consume(&c->input, 1); /* host string length */
1136 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1137 buffer_get(&c->input, (char *)&dest_port, 2);
1138 dest_addr[addrlen] = '\0';
1139 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1140 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1141 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1143 c->host_port = ntohs(dest_port);
1145 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1146 c->self, c->path, c->host_port, s5_req.command);
1148 s5_rsp.version = 0x05;
1149 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1150 s5_rsp.reserved = 0; /* ignored */
1151 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1152 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1153 dest_port = 0; /* ignored */
1155 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1156 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1157 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1161 /* dynamic port forwarding */
1163 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1169 have = buffer_len(&c->input);
1171 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1172 /* buffer_dump(&c->input); */
1173 /* check if the fixed size part of the packet is in buffer. */
1176 FD_SET(c->sock, readset);
1179 /* try to guess the protocol */
1180 p = buffer_ptr(&c->input);
1183 ret = channel_decode_socks4(c, readset, writeset);
1186 ret = channel_decode_socks5(c, readset, writeset);
1194 } else if (ret == 0) {
1195 debug2("channel %d: pre_dynamic: need more", c->self);
1197 FD_SET(c->sock, readset);
1199 /* switch to the next state */
1200 c->type = SSH_CHANNEL_OPENING;
1201 port_open_helper(c, "direct-tcpip");
1205 /* This is our fake X11 server socket. */
1208 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1211 struct sockaddr addr;
1214 char buf[16384], *remote_ipaddr;
1217 if (FD_ISSET(c->sock, readset)) {
1218 debug("X11 connection requested.");
1219 addrlen = sizeof(addr);
1220 newsock = accept(c->sock, &addr, &addrlen);
1221 if (c->single_connection) {
1222 debug2("single_connection: closing X11 listener.");
1223 channel_close_fd(&c->sock);
1227 error("accept: %.100s", strerror(errno));
1230 set_nodelay(newsock);
1231 remote_ipaddr = get_peer_ipaddr(newsock);
1232 remote_port = get_peer_port(newsock);
1233 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1234 remote_ipaddr, remote_port);
1236 nc = channel_new("accepted x11 socket",
1237 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1238 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1240 packet_start(SSH2_MSG_CHANNEL_OPEN);
1241 packet_put_cstring("x11");
1242 packet_put_int(nc->self);
1243 packet_put_int(nc->local_window_max);
1244 packet_put_int(nc->local_maxpacket);
1245 /* originator ipaddr and port */
1246 packet_put_cstring(remote_ipaddr);
1247 if (datafellows & SSH_BUG_X11FWD) {
1248 debug2("ssh2 x11 bug compat mode");
1250 packet_put_int(remote_port);
1254 packet_start(SSH_SMSG_X11_OPEN);
1255 packet_put_int(nc->self);
1256 if (packet_get_protocol_flags() &
1257 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1258 packet_put_cstring(buf);
1261 xfree(remote_ipaddr);
1266 port_open_helper(Channel *c, char *rtype)
1270 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1271 int remote_port = get_peer_port(c->sock);
1273 direct = (strcmp(rtype, "direct-tcpip") == 0);
1275 snprintf(buf, sizeof buf,
1276 "%s: listening port %d for %.100s port %d, "
1277 "connect from %.200s port %d",
1278 rtype, c->listening_port, c->path, c->host_port,
1279 remote_ipaddr, remote_port);
1281 xfree(c->remote_name);
1282 c->remote_name = xstrdup(buf);
1285 packet_start(SSH2_MSG_CHANNEL_OPEN);
1286 packet_put_cstring(rtype);
1287 packet_put_int(c->self);
1288 packet_put_int(c->local_window_max);
1289 packet_put_int(c->local_maxpacket);
1291 /* target host, port */
1292 packet_put_cstring(c->path);
1293 packet_put_int(c->host_port);
1295 /* listen address, port */
1296 packet_put_cstring(c->path);
1297 packet_put_int(c->listening_port);
1299 /* originator host and port */
1300 packet_put_cstring(remote_ipaddr);
1301 packet_put_int((u_int)remote_port);
1304 packet_start(SSH_MSG_PORT_OPEN);
1305 packet_put_int(c->self);
1306 packet_put_cstring(c->path);
1307 packet_put_int(c->host_port);
1308 if (packet_get_protocol_flags() &
1309 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1310 packet_put_cstring(c->remote_name);
1313 xfree(remote_ipaddr);
1317 channel_set_reuseaddr(int fd)
1322 * Set socket options.
1323 * Allow local port reuse in TIME_WAIT.
1325 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1326 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1330 * This socket is listening for connections to a forwarded TCP/IP port.
1334 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1337 struct sockaddr addr;
1338 int newsock, nextstate;
1342 if (FD_ISSET(c->sock, readset)) {
1343 debug("Connection to port %d forwarding "
1344 "to %.100s port %d requested.",
1345 c->listening_port, c->path, c->host_port);
1347 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1348 nextstate = SSH_CHANNEL_OPENING;
1349 rtype = "forwarded-tcpip";
1351 if (c->host_port == 0) {
1352 nextstate = SSH_CHANNEL_DYNAMIC;
1353 rtype = "dynamic-tcpip";
1355 nextstate = SSH_CHANNEL_OPENING;
1356 rtype = "direct-tcpip";
1360 addrlen = sizeof(addr);
1361 newsock = accept(c->sock, &addr, &addrlen);
1363 error("accept: %.100s", strerror(errno));
1366 set_nodelay(newsock);
1367 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1368 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1369 nc->listening_port = c->listening_port;
1370 nc->host_port = c->host_port;
1371 strlcpy(nc->path, c->path, sizeof(nc->path));
1373 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1375 * do not call the channel_post handler until
1376 * this flag has been reset by a pre-handler.
1377 * otherwise the FD_ISSET calls might overflow
1381 port_open_helper(nc, rtype);
1387 * This is the authentication agent socket listening for connections from
1392 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1396 struct sockaddr addr;
1399 if (FD_ISSET(c->sock, readset)) {
1400 addrlen = sizeof(addr);
1401 newsock = accept(c->sock, &addr, &addrlen);
1403 error("accept from auth socket: %.100s", strerror(errno));
1406 nc = channel_new("accepted auth socket",
1407 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1408 c->local_window_max, c->local_maxpacket,
1409 0, "accepted auth socket", 1);
1411 packet_start(SSH2_MSG_CHANNEL_OPEN);
1412 packet_put_cstring("auth-agent@openssh.com");
1413 packet_put_int(nc->self);
1414 packet_put_int(c->local_window_max);
1415 packet_put_int(c->local_maxpacket);
1417 packet_start(SSH_SMSG_AGENT_OPEN);
1418 packet_put_int(nc->self);
1426 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1429 socklen_t sz = sizeof(err);
1431 if (FD_ISSET(c->sock, writeset)) {
1432 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1434 error("getsockopt SO_ERROR failed");
1437 debug("channel %d: connected", c->self);
1438 c->type = SSH_CHANNEL_OPEN;
1440 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1441 packet_put_int(c->remote_id);
1442 packet_put_int(c->self);
1443 packet_put_int(c->local_window);
1444 packet_put_int(c->local_maxpacket);
1446 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1447 packet_put_int(c->remote_id);
1448 packet_put_int(c->self);
1451 debug("channel %d: not connected: %s",
1452 c->self, strerror(err));
1454 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1455 packet_put_int(c->remote_id);
1456 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1457 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1458 packet_put_cstring(strerror(err));
1459 packet_put_cstring("");
1462 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1463 packet_put_int(c->remote_id);
1473 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1475 char buf[CHAN_RBUF];
1478 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1479 if (c->rfd != -1 && (force || FD_ISSET(c->rfd, readset))) {
1481 len = read(c->rfd, buf, sizeof(buf));
1482 if (len < 0 && (errno == EINTR || (errno == EAGAIN && !force)))
1484 #ifndef PTY_ZEROREAD
1487 if ((!c->isatty && len <= 0) ||
1488 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1490 debug2("channel %d: read<=0 rfd %d len %d",
1491 c->self, c->rfd, len);
1492 if (c->type != SSH_CHANNEL_OPEN) {
1493 debug2("channel %d: not open", c->self);
1496 } else if (compat13) {
1497 buffer_clear(&c->output);
1498 c->type = SSH_CHANNEL_INPUT_DRAINING;
1499 debug2("channel %d: input draining.", c->self);
1501 chan_read_failed(c);
1505 if (c->input_filter != NULL) {
1506 if (c->input_filter(c, buf, len) == -1) {
1507 debug2("channel %d: filter stops", c->self);
1508 chan_read_failed(c);
1510 } else if (c->datagram) {
1511 buffer_put_string(&c->input, buf, len);
1513 buffer_append(&c->input, buf, len);
1521 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1524 u_char *data = NULL, *buf;
1528 /* Send buffered output data to the socket. */
1530 FD_ISSET(c->wfd, writeset) &&
1531 buffer_len(&c->output) > 0) {
1532 if (c->output_filter != NULL) {
1533 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1534 debug2("channel %d: filter stops", c->self);
1535 if (c->type != SSH_CHANNEL_OPEN)
1538 chan_write_failed(c);
1541 } else if (c->datagram) {
1542 buf = data = buffer_get_string(&c->output, &dlen);
1544 buf = data = buffer_ptr(&c->output);
1545 dlen = buffer_len(&c->output);
1549 /* ignore truncated writes, datagrams might get lost */
1550 c->local_consumed += dlen + 4;
1551 len = write(c->wfd, buf, dlen);
1553 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1556 if (c->type != SSH_CHANNEL_OPEN)
1559 chan_write_failed(c);
1565 /* XXX: Later AIX versions can't push as much data to tty */
1566 if (compat20 && c->wfd_isatty)
1567 dlen = MIN(dlen, 8*1024);
1570 len = write(c->wfd, buf, dlen);
1571 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1574 if (c->type != SSH_CHANNEL_OPEN) {
1575 debug2("channel %d: not open", c->self);
1578 } else if (compat13) {
1579 buffer_clear(&c->output);
1580 debug2("channel %d: input draining.", c->self);
1581 c->type = SSH_CHANNEL_INPUT_DRAINING;
1583 chan_write_failed(c);
1587 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1588 if (tcgetattr(c->wfd, &tio) == 0 &&
1589 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1591 * Simulate echo to reduce the impact of
1592 * traffic analysis. We need to match the
1593 * size of a SSH2_MSG_CHANNEL_DATA message
1594 * (4 byte channel id + buf)
1596 packet_send_ignore(4 + len);
1600 buffer_consume(&c->output, len);
1601 if (compat20 && len > 0) {
1602 c->local_consumed += len;
1609 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1611 char buf[CHAN_RBUF];
1614 /** XXX handle drain efd, too */
1616 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1617 FD_ISSET(c->efd, writeset) &&
1618 buffer_len(&c->extended) > 0) {
1619 len = write(c->efd, buffer_ptr(&c->extended),
1620 buffer_len(&c->extended));
1621 debug2("channel %d: written %d to efd %d",
1622 c->self, len, c->efd);
1623 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1626 debug2("channel %d: closing write-efd %d",
1628 channel_close_fd(&c->efd);
1630 buffer_consume(&c->extended, len);
1631 c->local_consumed += len;
1633 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1634 (c->detach_close || FD_ISSET(c->efd, readset))) {
1635 len = read(c->efd, buf, sizeof(buf));
1636 debug2("channel %d: read %d from efd %d",
1637 c->self, len, c->efd);
1638 if (len < 0 && (errno == EINTR ||
1639 (errno == EAGAIN && !c->detach_close)))
1642 debug2("channel %d: closing read-efd %d",
1644 channel_close_fd(&c->efd);
1646 buffer_append(&c->extended, buf, len);
1655 channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
1660 /* Monitor control fd to detect if the slave client exits */
1661 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1662 len = read(c->ctl_fd, buf, sizeof(buf));
1663 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1666 debug2("channel %d: ctl read<=0", c->self);
1667 if (c->type != SSH_CHANNEL_OPEN) {
1668 debug2("channel %d: not open", c->self);
1672 chan_read_failed(c);
1673 chan_write_failed(c);
1677 fatal("%s: unexpected data on ctl fd", __func__);
1683 channel_check_window(Channel *c)
1685 if (c->type == SSH_CHANNEL_OPEN &&
1686 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1687 ((c->local_window_max - c->local_window >
1688 c->local_maxpacket*3) ||
1689 c->local_window < c->local_window_max/2) &&
1690 c->local_consumed > 0) {
1691 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1692 packet_put_int(c->remote_id);
1693 packet_put_int(c->local_consumed);
1695 debug2("channel %d: window %d sent adjust %d",
1696 c->self, c->local_window,
1698 c->local_window += c->local_consumed;
1699 c->local_consumed = 0;
1705 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1709 channel_handle_rfd(c, readset, writeset);
1710 channel_handle_wfd(c, readset, writeset);
1713 channel_handle_efd(c, readset, writeset);
1714 channel_handle_ctl(c, readset, writeset);
1715 channel_check_window(c);
1720 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1724 /* Send buffered output data to the socket. */
1725 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1726 len = write(c->sock, buffer_ptr(&c->output),
1727 buffer_len(&c->output));
1729 buffer_clear(&c->output);
1731 buffer_consume(&c->output, len);
1736 channel_handler_init_20(void)
1738 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1739 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1740 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1741 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1742 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1743 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1744 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1745 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1747 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1748 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1749 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1750 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1751 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1752 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1753 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1757 channel_handler_init_13(void)
1759 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1760 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1761 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1762 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1763 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1764 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1765 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1766 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1767 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1769 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1770 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1771 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1772 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1773 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1774 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1775 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1779 channel_handler_init_15(void)
1781 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1782 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1783 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1784 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1785 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1786 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1787 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1789 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1790 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1791 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1792 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1793 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1794 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1798 channel_handler_init(void)
1802 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1803 channel_pre[i] = NULL;
1804 channel_post[i] = NULL;
1807 channel_handler_init_20();
1809 channel_handler_init_13();
1811 channel_handler_init_15();
1814 /* gc dead channels */
1816 channel_garbage_collect(Channel *c)
1820 if (c->detach_user != NULL) {
1821 if (!chan_is_dead(c, c->detach_close))
1823 debug2("channel %d: gc: notify user", c->self);
1824 c->detach_user(c->self, NULL);
1825 /* if we still have a callback */
1826 if (c->detach_user != NULL)
1828 debug2("channel %d: gc: user detached", c->self);
1830 if (!chan_is_dead(c, 1))
1832 debug2("channel %d: garbage collecting", c->self);
1837 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1839 static int did_init = 0;
1844 channel_handler_init();
1847 for (i = 0; i < channels_alloc; i++) {
1851 if (ftab[c->type] != NULL)
1852 (*ftab[c->type])(c, readset, writeset);
1853 channel_garbage_collect(c);
1858 * Allocate/update select bitmasks and add any bits relevant to channels in
1862 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1863 u_int *nallocp, int rekeying)
1865 u_int n, sz, nfdset;
1867 n = MAX(*maxfdp, channel_max_fd);
1869 nfdset = howmany(n+1, NFDBITS);
1870 /* Explicitly test here, because xrealloc isn't always called */
1871 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
1872 fatal("channel_prepare_select: max_fd (%d) is too large", n);
1873 sz = nfdset * sizeof(fd_mask);
1875 /* perhaps check sz < nalloc/2 and shrink? */
1876 if (*readsetp == NULL || sz > *nallocp) {
1877 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
1878 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1882 memset(*readsetp, 0, sz);
1883 memset(*writesetp, 0, sz);
1886 channel_handler(channel_pre, *readsetp, *writesetp);
1890 * After select, perform any appropriate operations for channels which have
1894 channel_after_select(fd_set *readset, fd_set *writeset)
1896 channel_handler(channel_post, readset, writeset);
1900 /* If there is data to send to the connection, enqueue some of it now. */
1902 channel_output_poll(void)
1907 for (i = 0; i < channels_alloc; i++) {
1913 * We are only interested in channels that can have buffered
1917 if (c->type != SSH_CHANNEL_OPEN &&
1918 c->type != SSH_CHANNEL_INPUT_DRAINING)
1921 if (c->type != SSH_CHANNEL_OPEN)
1925 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1926 /* XXX is this true? */
1927 debug3("channel %d: will not send data after close", c->self);
1931 /* Get the amount of buffered data for this channel. */
1932 if ((c->istate == CHAN_INPUT_OPEN ||
1933 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1934 (len = buffer_len(&c->input)) > 0) {
1940 data = buffer_get_string(&c->input,
1942 packet_start(SSH2_MSG_CHANNEL_DATA);
1943 packet_put_int(c->remote_id);
1944 packet_put_string(data, dlen);
1946 c->remote_window -= dlen + 4;
1952 * Send some data for the other side over the secure
1956 if (len > c->remote_window)
1957 len = c->remote_window;
1958 if (len > c->remote_maxpacket)
1959 len = c->remote_maxpacket;
1961 if (packet_is_interactive()) {
1965 /* Keep the packets at reasonable size. */
1966 if (len > packet_get_maxsize()/2)
1967 len = packet_get_maxsize()/2;
1971 packet_start(compat20 ?
1972 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1973 packet_put_int(c->remote_id);
1974 packet_put_string(buffer_ptr(&c->input), len);
1976 buffer_consume(&c->input, len);
1977 c->remote_window -= len;
1979 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1981 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1983 * input-buffer is empty and read-socket shutdown:
1984 * tell peer, that we will not send more data: send IEOF.
1985 * hack for extended data: delay EOF if EFD still in use.
1987 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1988 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1989 c->self, c->efd, buffer_len(&c->extended));
1993 /* Send extended data, i.e. stderr */
1995 !(c->flags & CHAN_EOF_SENT) &&
1996 c->remote_window > 0 &&
1997 (len = buffer_len(&c->extended)) > 0 &&
1998 c->extended_usage == CHAN_EXTENDED_READ) {
1999 debug2("channel %d: rwin %u elen %u euse %d",
2000 c->self, c->remote_window, buffer_len(&c->extended),
2002 if (len > c->remote_window)
2003 len = c->remote_window;
2004 if (len > c->remote_maxpacket)
2005 len = c->remote_maxpacket;
2006 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
2007 packet_put_int(c->remote_id);
2008 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
2009 packet_put_string(buffer_ptr(&c->extended), len);
2011 buffer_consume(&c->extended, len);
2012 c->remote_window -= len;
2013 debug2("channel %d: sent ext data %d", c->self, len);
2019 /* -- protocol input */
2023 channel_input_data(int type, u_int32_t seq, void *ctxt)
2030 /* Get the channel number and verify it. */
2031 id = packet_get_int();
2032 c = channel_lookup(id);
2034 packet_disconnect("Received data for nonexistent channel %d.", id);
2036 /* Ignore any data for non-open channels (might happen on close) */
2037 if (c->type != SSH_CHANNEL_OPEN &&
2038 c->type != SSH_CHANNEL_X11_OPEN)
2042 data = packet_get_string_ptr(&data_len);
2045 * Ignore data for protocol > 1.3 if output end is no longer open.
2046 * For protocol 2 the sending side is reducing its window as it sends
2047 * data, so we must 'fake' consumption of the data in order to ensure
2048 * that window updates are sent back. Otherwise the connection might
2051 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2053 c->local_window -= data_len;
2054 c->local_consumed += data_len;
2060 if (data_len > c->local_maxpacket) {
2061 logit("channel %d: rcvd big packet %d, maxpack %d",
2062 c->self, data_len, c->local_maxpacket);
2064 if (data_len > c->local_window) {
2065 logit("channel %d: rcvd too much data %d, win %d",
2066 c->self, data_len, c->local_window);
2069 c->local_window -= data_len;
2072 buffer_put_string(&c->output, data, data_len);
2074 buffer_append(&c->output, data, data_len);
2080 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2084 u_int data_len, tcode;
2087 /* Get the channel number and verify it. */
2088 id = packet_get_int();
2089 c = channel_lookup(id);
2092 packet_disconnect("Received extended_data for bad channel %d.", id);
2093 if (c->type != SSH_CHANNEL_OPEN) {
2094 logit("channel %d: ext data for non open", id);
2097 if (c->flags & CHAN_EOF_RCVD) {
2098 if (datafellows & SSH_BUG_EXTEOF)
2099 debug("channel %d: accepting ext data after eof", id);
2101 packet_disconnect("Received extended_data after EOF "
2102 "on channel %d.", id);
2104 tcode = packet_get_int();
2106 c->extended_usage != CHAN_EXTENDED_WRITE ||
2107 tcode != SSH2_EXTENDED_DATA_STDERR) {
2108 logit("channel %d: bad ext data", c->self);
2111 data = packet_get_string(&data_len);
2113 if (data_len > c->local_window) {
2114 logit("channel %d: rcvd too much extended_data %d, win %d",
2115 c->self, data_len, c->local_window);
2119 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2120 c->local_window -= data_len;
2121 buffer_append(&c->extended, data, data_len);
2127 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2132 id = packet_get_int();
2134 c = channel_lookup(id);
2136 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2139 /* XXX force input close */
2140 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2141 debug("channel %d: FORCE input drain", c->self);
2142 c->istate = CHAN_INPUT_WAIT_DRAIN;
2143 if (buffer_len(&c->input) == 0)
2151 channel_input_close(int type, u_int32_t seq, void *ctxt)
2156 id = packet_get_int();
2158 c = channel_lookup(id);
2160 packet_disconnect("Received close for nonexistent channel %d.", id);
2163 * Send a confirmation that we have closed the channel and no more
2164 * data is coming for it.
2166 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2167 packet_put_int(c->remote_id);
2171 * If the channel is in closed state, we have sent a close request,
2172 * and the other side will eventually respond with a confirmation.
2173 * Thus, we cannot free the channel here, because then there would be
2174 * no-one to receive the confirmation. The channel gets freed when
2175 * the confirmation arrives.
2177 if (c->type != SSH_CHANNEL_CLOSED) {
2179 * Not a closed channel - mark it as draining, which will
2180 * cause it to be freed later.
2182 buffer_clear(&c->input);
2183 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2187 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2190 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2192 int id = packet_get_int();
2193 Channel *c = channel_lookup(id);
2197 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2198 chan_rcvd_oclose(c);
2203 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2205 int id = packet_get_int();
2206 Channel *c = channel_lookup(id);
2210 packet_disconnect("Received close confirmation for "
2211 "out-of-range channel %d.", id);
2212 if (c->type != SSH_CHANNEL_CLOSED)
2213 packet_disconnect("Received close confirmation for "
2214 "non-closed channel %d (type %d).", id, c->type);
2220 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2225 id = packet_get_int();
2226 c = channel_lookup(id);
2228 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2229 packet_disconnect("Received open confirmation for "
2230 "non-opening channel %d.", id);
2231 remote_id = packet_get_int();
2232 /* Record the remote channel number and mark that the channel is now open. */
2233 c->remote_id = remote_id;
2234 c->type = SSH_CHANNEL_OPEN;
2237 c->remote_window = packet_get_int();
2238 c->remote_maxpacket = packet_get_int();
2239 if (c->open_confirm) {
2240 debug2("callback start");
2241 c->open_confirm(c->self, c->open_confirm_ctx);
2242 debug2("callback done");
2244 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2245 c->remote_window, c->remote_maxpacket);
2251 reason2txt(int reason)
2254 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2255 return "administratively prohibited";
2256 case SSH2_OPEN_CONNECT_FAILED:
2257 return "connect failed";
2258 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2259 return "unknown channel type";
2260 case SSH2_OPEN_RESOURCE_SHORTAGE:
2261 return "resource shortage";
2263 return "unknown reason";
2268 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2271 char *msg = NULL, *lang = NULL;
2274 id = packet_get_int();
2275 c = channel_lookup(id);
2277 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2278 packet_disconnect("Received open failure for "
2279 "non-opening channel %d.", id);
2281 reason = packet_get_int();
2282 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2283 msg = packet_get_string(NULL);
2284 lang = packet_get_string(NULL);
2286 logit("channel %d: open failed: %s%s%s", id,
2287 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2294 /* Free the channel. This will also close the socket. */
2300 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2309 /* Get the channel number and verify it. */
2310 id = packet_get_int();
2311 c = channel_lookup(id);
2314 logit("Received window adjust for non-open channel %d.", id);
2317 adjust = packet_get_int();
2319 debug2("channel %d: rcvd adjust %u", id, adjust);
2320 c->remote_window += adjust;
2325 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2329 char *host, *originator_string;
2330 int remote_id, sock = -1;
2332 remote_id = packet_get_int();
2333 host = packet_get_string(NULL);
2334 host_port = packet_get_int();
2336 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2337 originator_string = packet_get_string(NULL);
2339 originator_string = xstrdup("unknown (remote did not supply name)");
2342 sock = channel_connect_to(host, host_port);
2344 c = channel_new("connected socket",
2345 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2346 originator_string, 1);
2347 c->remote_id = remote_id;
2349 xfree(originator_string);
2351 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2352 packet_put_int(remote_id);
2360 channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
2363 struct channel_confirm *cc;
2366 /* Reset keepalive timeout */
2367 keep_alive_timeouts = 0;
2369 remote_id = packet_get_int();
2372 debug2("channel_input_confirm: type %d id %d", type, remote_id);
2374 if ((c = channel_lookup(remote_id)) == NULL) {
2375 logit("channel_input_success_failure: %d: unknown", remote_id);
2379 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
2381 cc->cb(type, c, cc->ctx);
2382 TAILQ_REMOVE(&c->status_confirms, cc, entry);
2383 bzero(cc, sizeof(*cc));
2387 /* -- tcp forwarding */
2390 channel_set_af(int af)
2396 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2397 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2400 int sock, r, success = 0, wildcard = 0, is_client;
2401 struct addrinfo hints, *ai, *aitop;
2402 const char *host, *addr;
2403 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2405 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2406 listen_addr : host_to_connect;
2407 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2410 error("No forward host name.");
2413 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2414 error("Forward host name too long.");
2419 * Determine whether or not a port forward listens to loopback,
2420 * specified address or wildcard. On the client, a specified bind
2421 * address will always override gateway_ports. On the server, a
2422 * gateway_ports of 1 (``yes'') will override the client's
2423 * specification and force a wildcard bind, whereas a value of 2
2424 * (``clientspecified'') will bind to whatever address the client
2427 * Special-case listen_addrs are:
2429 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2430 * "" (empty string), "*" -> wildcard v4/v6
2431 * "localhost" -> loopback v4/v6
2434 if (listen_addr == NULL) {
2435 /* No address specified: default to gateway_ports setting */
2438 } else if (gateway_ports || is_client) {
2439 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2440 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
2441 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2442 (!is_client && gateway_ports == 1))
2444 else if (strcmp(listen_addr, "localhost") != 0)
2448 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2449 type, wildcard, (addr == NULL) ? "NULL" : addr);
2452 * getaddrinfo returns a loopback address if the hostname is
2453 * set to NULL and hints.ai_flags is not AI_PASSIVE
2455 memset(&hints, 0, sizeof(hints));
2456 hints.ai_family = IPv4or6;
2457 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2458 hints.ai_socktype = SOCK_STREAM;
2459 snprintf(strport, sizeof strport, "%d", listen_port);
2460 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2462 /* This really shouldn't happen */
2463 packet_disconnect("getaddrinfo: fatal error: %s",
2464 ssh_gai_strerror(r));
2466 error("channel_setup_fwd_listener: "
2467 "getaddrinfo(%.64s): %s", addr,
2468 ssh_gai_strerror(r));
2473 for (ai = aitop; ai; ai = ai->ai_next) {
2474 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2476 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2477 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2478 error("channel_setup_fwd_listener: getnameinfo failed");
2481 /* Create a port to listen for the host. */
2482 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2484 /* this is no error since kernel may not support ipv6 */
2485 verbose("socket: %.100s", strerror(errno));
2489 channel_set_reuseaddr(sock);
2491 debug("Local forwarding listening on %s port %s.", ntop, strport);
2493 /* Bind the socket to the address. */
2494 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2495 /* address can be in use ipv6 address is already bound */
2497 error("bind: %.100s", strerror(errno));
2499 verbose("bind: %.100s", strerror(errno));
2504 /* Start listening for connections on the socket. */
2505 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2506 error("listen: %.100s", strerror(errno));
2510 /* Allocate a channel number for the socket. */
2511 c = channel_new("port listener", type, sock, sock, -1,
2512 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2513 0, "port listener", 1);
2514 strlcpy(c->path, host, sizeof(c->path));
2515 c->host_port = port_to_connect;
2516 c->listening_port = listen_port;
2520 error("channel_setup_fwd_listener: cannot listen to port: %d",
2522 freeaddrinfo(aitop);
2527 channel_cancel_rport_listener(const char *host, u_short port)
2532 for (i = 0; i < channels_alloc; i++) {
2533 Channel *c = channels[i];
2535 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2536 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2537 c->listening_port == port) {
2538 debug2("%s: close channel %d", __func__, i);
2547 /* protocol local port fwd, used by ssh (and sshd in v1) */
2549 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2550 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2552 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2553 listen_host, listen_port, host_to_connect, port_to_connect,
2557 /* protocol v2 remote port fwd, used by sshd */
2559 channel_setup_remote_fwd_listener(const char *listen_address,
2560 u_short listen_port, int gateway_ports)
2562 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2563 listen_address, listen_port, NULL, 0, gateway_ports);
2567 * Initiate forwarding of connections to port "port" on remote host through
2568 * the secure channel to host:port from local side.
2572 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2573 const char *host_to_connect, u_short port_to_connect)
2575 int type, success = 0;
2577 /* Record locally that connection to this host/port is permitted. */
2578 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2579 fatal("channel_request_remote_forwarding: too many forwards");
2581 /* Send the forward request to the remote side. */
2583 const char *address_to_bind;
2584 if (listen_host == NULL) {
2585 if (datafellows & SSH_BUG_RFWD_ADDR)
2586 address_to_bind = "127.0.0.1";
2588 address_to_bind = "localhost";
2589 } else if (*listen_host == '\0' ||
2590 strcmp(listen_host, "*") == 0) {
2591 if (datafellows & SSH_BUG_RFWD_ADDR)
2592 address_to_bind = "0.0.0.0";
2594 address_to_bind = "";
2596 address_to_bind = listen_host;
2598 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2599 packet_put_cstring("tcpip-forward");
2600 packet_put_char(1); /* boolean: want reply */
2601 packet_put_cstring(address_to_bind);
2602 packet_put_int(listen_port);
2604 packet_write_wait();
2605 /* Assume that server accepts the request */
2608 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2609 packet_put_int(listen_port);
2610 packet_put_cstring(host_to_connect);
2611 packet_put_int(port_to_connect);
2613 packet_write_wait();
2615 /* Wait for response from the remote side. */
2616 type = packet_read();
2618 case SSH_SMSG_SUCCESS:
2621 case SSH_SMSG_FAILURE:
2624 /* Unknown packet */
2625 packet_disconnect("Protocol error for port forward request:"
2626 "received packet type %d.", type);
2630 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2631 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2632 permitted_opens[num_permitted_opens].listen_port = listen_port;
2633 num_permitted_opens++;
2635 return (success ? 0 : -1);
2639 * Request cancellation of remote forwarding of connection host:port from
2643 channel_request_rforward_cancel(const char *host, u_short port)
2650 for (i = 0; i < num_permitted_opens; i++) {
2651 if (permitted_opens[i].host_to_connect != NULL &&
2652 permitted_opens[i].listen_port == port)
2655 if (i >= num_permitted_opens) {
2656 debug("%s: requested forward not found", __func__);
2659 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2660 packet_put_cstring("cancel-tcpip-forward");
2662 packet_put_cstring(host == NULL ? "" : host);
2663 packet_put_int(port);
2666 permitted_opens[i].listen_port = 0;
2667 permitted_opens[i].port_to_connect = 0;
2668 xfree(permitted_opens[i].host_to_connect);
2669 permitted_opens[i].host_to_connect = NULL;
2673 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2674 * listening for the port, and sends back a success reply (or disconnect
2675 * message if there was an error).
2678 channel_input_port_forward_request(int is_root, int gateway_ports)
2680 u_short port, host_port;
2684 /* Get arguments from the packet. */
2685 port = packet_get_int();
2686 hostname = packet_get_string(NULL);
2687 host_port = packet_get_int();
2691 * Check that an unprivileged user is not trying to forward a
2694 if (port < IPPORT_RESERVED && !is_root)
2696 "Requested forwarding of port %d but user is not root.",
2699 packet_disconnect("Dynamic forwarding denied.");
2702 /* Initiate forwarding */
2703 success = channel_setup_local_fwd_listener(NULL, port, hostname,
2704 host_port, gateway_ports);
2706 /* Free the argument string. */
2709 return (success ? 0 : -1);
2713 * Permits opening to any host/port if permitted_opens[] is empty. This is
2714 * usually called by the server, because the user could connect to any port
2715 * anyway, and the server has no way to know but to trust the client anyway.
2718 channel_permit_all_opens(void)
2720 if (num_permitted_opens == 0)
2721 all_opens_permitted = 1;
2725 channel_add_permitted_opens(char *host, int port)
2727 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2728 fatal("channel_add_permitted_opens: too many forwards");
2729 debug("allow port forwarding to host %s port %d", host, port);
2731 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2732 permitted_opens[num_permitted_opens].port_to_connect = port;
2733 num_permitted_opens++;
2735 all_opens_permitted = 0;
2739 channel_add_adm_permitted_opens(char *host, int port)
2741 if (num_adm_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2742 fatal("channel_add_adm_permitted_opens: too many forwards");
2743 debug("config allows port forwarding to host %s port %d", host, port);
2745 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
2747 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
2748 return ++num_adm_permitted_opens;
2752 channel_clear_permitted_opens(void)
2756 for (i = 0; i < num_permitted_opens; i++)
2757 if (permitted_opens[i].host_to_connect != NULL)
2758 xfree(permitted_opens[i].host_to_connect);
2759 num_permitted_opens = 0;
2763 channel_clear_adm_permitted_opens(void)
2767 for (i = 0; i < num_adm_permitted_opens; i++)
2768 if (permitted_adm_opens[i].host_to_connect != NULL)
2769 xfree(permitted_adm_opens[i].host_to_connect);
2770 num_adm_permitted_opens = 0;
2773 /* return socket to remote host, port */
2775 connect_to(const char *host, u_short port)
2777 struct addrinfo hints, *ai, *aitop;
2778 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2782 memset(&hints, 0, sizeof(hints));
2783 hints.ai_family = IPv4or6;
2784 hints.ai_socktype = SOCK_STREAM;
2785 snprintf(strport, sizeof strport, "%d", port);
2786 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2787 error("connect_to %.100s: unknown host (%s)", host,
2788 ssh_gai_strerror(gaierr));
2791 for (ai = aitop; ai; ai = ai->ai_next) {
2792 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2794 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2795 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2796 error("connect_to: getnameinfo failed");
2799 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2801 if (ai->ai_next == NULL)
2802 error("socket: %.100s", strerror(errno));
2804 verbose("socket: %.100s", strerror(errno));
2807 if (set_nonblock(sock) == -1)
2808 fatal("%s: set_nonblock(%d)", __func__, sock);
2809 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2810 errno != EINPROGRESS) {
2811 error("connect_to %.100s port %s: %.100s", ntop, strport,
2814 continue; /* fail -- try next */
2816 break; /* success */
2819 freeaddrinfo(aitop);
2821 error("connect_to %.100s port %d: failed.", host, port);
2830 channel_connect_by_listen_address(u_short listen_port)
2834 for (i = 0; i < num_permitted_opens; i++)
2835 if (permitted_opens[i].host_to_connect != NULL &&
2836 permitted_opens[i].listen_port == listen_port)
2838 permitted_opens[i].host_to_connect,
2839 permitted_opens[i].port_to_connect);
2840 error("WARNING: Server requests forwarding for unknown listen_port %d",
2845 /* Check if connecting to that port is permitted and connect. */
2847 channel_connect_to(const char *host, u_short port)
2849 int i, permit, permit_adm = 1;
2851 permit = all_opens_permitted;
2853 for (i = 0; i < num_permitted_opens; i++)
2854 if (permitted_opens[i].host_to_connect != NULL &&
2855 permitted_opens[i].port_to_connect == port &&
2856 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2860 if (num_adm_permitted_opens > 0) {
2862 for (i = 0; i < num_adm_permitted_opens; i++)
2863 if (permitted_adm_opens[i].host_to_connect != NULL &&
2864 permitted_adm_opens[i].port_to_connect == port &&
2865 strcmp(permitted_adm_opens[i].host_to_connect, host)
2870 if (!permit || !permit_adm) {
2871 logit("Received request to connect to host %.100s port %d, "
2872 "but the request was denied.", host, port);
2875 return connect_to(host, port);
2879 channel_send_window_changes(void)
2884 for (i = 0; i < channels_alloc; i++) {
2885 if (channels[i] == NULL || !channels[i]->client_tty ||
2886 channels[i]->type != SSH_CHANNEL_OPEN)
2888 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2890 channel_request_start(i, "window-change", 0);
2891 packet_put_int((u_int)ws.ws_col);
2892 packet_put_int((u_int)ws.ws_row);
2893 packet_put_int((u_int)ws.ws_xpixel);
2894 packet_put_int((u_int)ws.ws_ypixel);
2899 /* -- X11 forwarding */
2902 * Creates an internet domain socket for listening for X11 connections.
2903 * Returns 0 and a suitable display number for the DISPLAY variable
2904 * stored in display_numberp , or -1 if an error occurs.
2907 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2908 int single_connection, u_int *display_numberp, int **chanids)
2911 int display_number, sock;
2913 struct addrinfo hints, *ai, *aitop;
2914 char strport[NI_MAXSERV];
2915 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2917 if (chanids == NULL)
2920 for (display_number = x11_display_offset;
2921 display_number < MAX_DISPLAYS;
2923 port = 6000 + display_number;
2924 memset(&hints, 0, sizeof(hints));
2925 hints.ai_family = IPv4or6;
2926 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2927 hints.ai_socktype = SOCK_STREAM;
2928 snprintf(strport, sizeof strport, "%d", port);
2929 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2930 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
2933 for (ai = aitop; ai; ai = ai->ai_next) {
2934 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2936 sock = socket(ai->ai_family, ai->ai_socktype,
2939 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2940 error("socket: %.100s", strerror(errno));
2941 freeaddrinfo(aitop);
2944 debug("x11_create_display_inet: Socket family %d not supported",
2950 if (ai->ai_family == AF_INET6) {
2952 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2953 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2956 channel_set_reuseaddr(sock);
2957 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2958 debug2("bind port %d: %.100s", port, strerror(errno));
2961 for (n = 0; n < num_socks; n++) {
2967 socks[num_socks++] = sock;
2968 #ifndef DONT_TRY_OTHER_AF
2969 if (num_socks == NUM_SOCKS)
2972 if (x11_use_localhost) {
2973 if (num_socks == NUM_SOCKS)
2980 freeaddrinfo(aitop);
2984 if (display_number >= MAX_DISPLAYS) {
2985 error("Failed to allocate internet-domain X11 display socket.");
2988 /* Start listening for connections on the socket. */
2989 for (n = 0; n < num_socks; n++) {
2991 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2992 error("listen: %.100s", strerror(errno));
2998 /* Allocate a channel for each socket. */
2999 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
3000 for (n = 0; n < num_socks; n++) {
3002 nc = channel_new("x11 listener",
3003 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3004 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
3005 0, "X11 inet listener", 1);
3006 nc->single_connection = single_connection;
3007 (*chanids)[n] = nc->self;
3011 /* Return the display number for the DISPLAY environment variable. */
3012 *display_numberp = display_number;
3017 connect_local_xsocket(u_int dnr)
3020 struct sockaddr_un addr;
3022 sock = socket(AF_UNIX, SOCK_STREAM, 0);
3024 error("socket: %.100s", strerror(errno));
3025 memset(&addr, 0, sizeof(addr));
3026 addr.sun_family = AF_UNIX;
3027 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
3028 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
3031 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
3036 x11_connect_display(void)
3038 u_int display_number;
3039 const char *display;
3040 char buf[1024], *cp;
3041 struct addrinfo hints, *ai, *aitop;
3042 char strport[NI_MAXSERV];
3043 int gaierr, sock = 0;
3045 /* Try to open a socket for the local X server. */
3046 display = getenv("DISPLAY");
3048 error("DISPLAY not set.");
3052 * Now we decode the value of the DISPLAY variable and make a
3053 * connection to the real X server.
3057 * Check if it is a unix domain socket. Unix domain displays are in
3058 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
3060 if (strncmp(display, "unix:", 5) == 0 ||
3061 display[0] == ':') {
3062 /* Connect to the unix domain socket. */
3063 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
3064 error("Could not parse display number from DISPLAY: %.100s",
3068 /* Create a socket. */
3069 sock = connect_local_xsocket(display_number);
3073 /* OK, we now have a connection to the display. */
3077 * Connect to an inet socket. The DISPLAY value is supposedly
3078 * hostname:d[.s], where hostname may also be numeric IP address.
3080 strlcpy(buf, display, sizeof(buf));
3081 cp = strchr(buf, ':');
3083 error("Could not find ':' in DISPLAY: %.100s", display);
3087 /* buf now contains the host name. But first we parse the display number. */
3088 if (sscanf(cp + 1, "%u", &display_number) != 1) {
3089 error("Could not parse display number from DISPLAY: %.100s",
3094 /* Look up the host address */
3095 memset(&hints, 0, sizeof(hints));
3096 hints.ai_family = IPv4or6;
3097 hints.ai_socktype = SOCK_STREAM;
3098 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
3099 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
3100 error("%.100s: unknown host. (%s)", buf,
3101 ssh_gai_strerror(gaierr));
3104 for (ai = aitop; ai; ai = ai->ai_next) {
3105 /* Create a socket. */
3106 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3108 debug2("socket: %.100s", strerror(errno));
3111 /* Connect it to the display. */
3112 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3113 debug2("connect %.100s port %u: %.100s", buf,
3114 6000 + display_number, strerror(errno));
3121 freeaddrinfo(aitop);
3123 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3132 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3133 * the remote channel number. We should do whatever we want, and respond
3134 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3139 x11_input_open(int type, u_int32_t seq, void *ctxt)
3142 int remote_id, sock = 0;
3145 debug("Received X11 open request.");
3147 remote_id = packet_get_int();
3149 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3150 remote_host = packet_get_string(NULL);
3152 remote_host = xstrdup("unknown (remote did not supply name)");
3156 /* Obtain a connection to the real X display. */
3157 sock = x11_connect_display();
3159 /* Allocate a channel for this connection. */
3160 c = channel_new("connected x11 socket",
3161 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3163 c->remote_id = remote_id;
3168 /* Send refusal to the remote host. */
3169 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3170 packet_put_int(remote_id);
3172 /* Send a confirmation to the remote host. */
3173 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3174 packet_put_int(remote_id);
3175 packet_put_int(c->self);
3180 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3183 deny_input_open(int type, u_int32_t seq, void *ctxt)
3185 int rchan = packet_get_int();
3188 case SSH_SMSG_AGENT_OPEN:
3189 error("Warning: ssh server tried agent forwarding.");
3191 case SSH_SMSG_X11_OPEN:
3192 error("Warning: ssh server tried X11 forwarding.");
3195 error("deny_input_open: type %d", type);
3198 error("Warning: this is probably a break-in attempt by a malicious server.");
3199 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3200 packet_put_int(rchan);
3205 * Requests forwarding of X11 connections, generates fake authentication
3206 * data, and enables authentication spoofing.
3207 * This should be called in the client only.
3210 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3211 const char *proto, const char *data)
3213 u_int data_len = (u_int) strlen(data) / 2;
3220 if (x11_saved_display == NULL)
3221 x11_saved_display = xstrdup(disp);
3222 else if (strcmp(disp, x11_saved_display) != 0) {
3223 error("x11_request_forwarding_with_spoofing: different "
3224 "$DISPLAY already forwarded");
3228 cp = strchr(disp, ':');
3230 cp = strchr(cp, '.');
3232 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3236 if (x11_saved_proto == NULL) {
3237 /* Save protocol name. */
3238 x11_saved_proto = xstrdup(proto);
3240 * Extract real authentication data and generate fake data
3241 * of the same length.
3243 x11_saved_data = xmalloc(data_len);
3244 x11_fake_data = xmalloc(data_len);
3245 for (i = 0; i < data_len; i++) {
3246 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3247 fatal("x11_request_forwarding: bad "
3248 "authentication data: %.100s", data);
3251 x11_saved_data[i] = value;
3252 x11_fake_data[i] = rnd & 0xff;
3255 x11_saved_data_len = data_len;
3256 x11_fake_data_len = data_len;
3259 /* Convert the fake data into hex. */
3260 new_data = tohex(x11_fake_data, data_len);
3262 /* Send the request packet. */
3264 channel_request_start(client_session_id, "x11-req", 0);
3265 packet_put_char(0); /* XXX bool single connection */
3267 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3269 packet_put_cstring(proto);
3270 packet_put_cstring(new_data);
3271 packet_put_int(screen_number);
3273 packet_write_wait();
3278 /* -- agent forwarding */
3280 /* Sends a message to the server to request authentication fd forwarding. */
3283 auth_request_forwarding(void)
3285 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3287 packet_write_wait();