2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * This file contains functions for generic socket connection forwarding.
6 * There is also code for initiating connection forwarding for X11 connections,
7 * arbitrary tcp/ip connections, and the authentication agent connection.
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
15 * SSH2 support added by Markus Friedl.
16 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
17 * Copyright (c) 1999 Dug Song. All rights reserved.
18 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42 RCSID("$OpenBSD: channels.c,v 1.232 2006/01/30 12:22:22 reyk Exp $");
56 #include "pathnames.h"
63 * Pointer to an array containing all allocated channels. The array is
64 * dynamically extended as needed.
66 static Channel **channels = NULL;
69 * Size of the channel array. All slots of the array must always be
70 * initialized (at least the type field); unused slots set to NULL
72 static u_int channels_alloc = 0;
75 * Maximum file descriptor value used in any of the channels. This is
76 * updated in channel_new.
78 static int channel_max_fd = 0;
81 /* -- tcp forwarding */
84 * Data structure for storing which hosts are permitted for forward requests.
85 * The local sides of any remote forwards are stored in this array to prevent
86 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
87 * network (which might be behind a firewall).
90 char *host_to_connect; /* Connect to 'host'. */
91 u_short port_to_connect; /* Connect to 'port'. */
92 u_short listen_port; /* Remote side should listen port number. */
95 /* List of all permitted host/port pairs to connect. */
96 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
98 /* Number of permitted host/port pairs in the array. */
99 static int num_permitted_opens = 0;
101 * If this is true, all opens are permitted. This is the case on the server
102 * on which we have to trust the client anyway, and the user could do
103 * anything after logging in anyway.
105 static int all_opens_permitted = 0;
108 /* -- X11 forwarding */
110 /* Maximum number of fake X11 displays to try. */
111 #define MAX_DISPLAYS 1000
113 /* Saved X11 local (client) display. */
114 static char *x11_saved_display = NULL;
116 /* Saved X11 authentication protocol name. */
117 static char *x11_saved_proto = NULL;
119 /* Saved X11 authentication data. This is the real data. */
120 static char *x11_saved_data = NULL;
121 static u_int x11_saved_data_len = 0;
124 * Fake X11 authentication data. This is what the server will be sending us;
125 * we should replace any occurrences of this by the real data.
127 static char *x11_fake_data = NULL;
128 static u_int x11_fake_data_len;
131 /* -- agent forwarding */
135 /* AF_UNSPEC or AF_INET or AF_INET6 */
136 static int IPv4or6 = AF_UNSPEC;
139 static void port_open_helper(Channel *c, char *rtype);
141 /* -- channel core */
144 channel_by_id(int id)
148 if (id < 0 || (u_int)id >= channels_alloc) {
149 logit("channel_by_id: %d: bad id", id);
154 logit("channel_by_id: %d: bad id: channel free", id);
161 * Returns the channel if it is allowed to receive protocol messages.
162 * Private channels, like listening sockets, may not receive messages.
165 channel_lookup(int id)
169 if ((c = channel_by_id(id)) == NULL)
173 case SSH_CHANNEL_X11_OPEN:
174 case SSH_CHANNEL_LARVAL:
175 case SSH_CHANNEL_CONNECTING:
176 case SSH_CHANNEL_DYNAMIC:
177 case SSH_CHANNEL_OPENING:
178 case SSH_CHANNEL_OPEN:
179 case SSH_CHANNEL_INPUT_DRAINING:
180 case SSH_CHANNEL_OUTPUT_DRAINING:
184 logit("Non-public channel %d, type %d.", id, c->type);
189 * Register filedescriptors for a channel, used when allocating a channel or
190 * when the channel consumer/producer is ready, e.g. shell exec'd
194 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
195 int extusage, int nonblock)
197 /* Update the maximum file descriptor value. */
198 channel_max_fd = MAX(channel_max_fd, rfd);
199 channel_max_fd = MAX(channel_max_fd, wfd);
200 channel_max_fd = MAX(channel_max_fd, efd);
202 /* XXX set close-on-exec -markus */
206 c->sock = (rfd == wfd) ? rfd : -1;
207 c->ctl_fd = -1; /* XXX: set elsewhere */
209 c->extended_usage = extusage;
211 /* XXX ugly hack: nonblock is only set by the server */
212 if (nonblock && isatty(c->rfd)) {
213 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
215 if (!isatty(c->wfd)) {
216 error("channel %d: wfd %d is not a tty?",
222 c->wfd_isatty = isatty(c->wfd);
224 /* enable nonblocking mode */
236 * Allocate a new channel object and set its type and socket. This will cause
237 * remote_name to be freed.
241 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
242 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
248 /* Do initial allocation if this is the first call. */
249 if (channels_alloc == 0) {
251 channels = xmalloc(channels_alloc * sizeof(Channel *));
252 for (i = 0; i < channels_alloc; i++)
255 /* Try to find a free slot where to put the new channel. */
256 for (found = -1, i = 0; i < channels_alloc; i++)
257 if (channels[i] == NULL) {
258 /* Found a free slot. */
263 /* There are no free slots. Take last+1 slot and expand the array. */
264 found = channels_alloc;
265 if (channels_alloc > 10000)
266 fatal("channel_new: internal error: channels_alloc %d "
267 "too big.", channels_alloc);
268 channels = xrealloc(channels,
269 (channels_alloc + 10) * sizeof(Channel *));
270 channels_alloc += 10;
271 debug2("channel: expanding %d", channels_alloc);
272 for (i = found; i < channels_alloc; i++)
275 /* Initialize and return new channel. */
276 c = channels[found] = xmalloc(sizeof(Channel));
277 memset(c, 0, sizeof(Channel));
278 buffer_init(&c->input);
279 buffer_init(&c->output);
280 buffer_init(&c->extended);
281 c->ostate = CHAN_OUTPUT_OPEN;
282 c->istate = CHAN_INPUT_OPEN;
284 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
288 c->local_window = window;
289 c->local_window_max = window;
290 c->local_consumed = 0;
291 c->local_maxpacket = maxpack;
292 c->dynamic_window = 0;
294 c->remote_name = xstrdup(remote_name);
295 c->remote_window = 0;
296 c->remote_maxpacket = 0;
298 c->single_connection = 0;
299 c->detach_user = NULL;
302 c->confirm_ctx = NULL;
303 c->input_filter = NULL;
304 c->output_filter = NULL;
305 debug("channel %d: new [%s]", found, remote_name);
310 channel_find_maxfd(void)
316 for (i = 0; i < channels_alloc; i++) {
319 max = MAX(max, c->rfd);
320 max = MAX(max, c->wfd);
321 max = MAX(max, c->efd);
328 channel_close_fd(int *fdp)
330 int ret = 0, fd = *fdp;
335 if (fd == channel_max_fd)
336 channel_max_fd = channel_find_maxfd();
341 /* Close all channel fd/socket. */
344 channel_close_fds(Channel *c)
346 debug3("channel %d: close_fds r %d w %d e %d c %d",
347 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
349 channel_close_fd(&c->sock);
350 channel_close_fd(&c->ctl_fd);
351 channel_close_fd(&c->rfd);
352 channel_close_fd(&c->wfd);
353 channel_close_fd(&c->efd);
356 /* Free the channel and close its fd/socket. */
359 channel_free(Channel *c)
364 for (n = 0, i = 0; i < channels_alloc; i++)
367 debug("channel %d: free: %s, nchannels %u", c->self,
368 c->remote_name ? c->remote_name : "???", n);
370 s = channel_open_message();
371 debug3("channel %d: status: %s", c->self, s);
375 shutdown(c->sock, SHUT_RDWR);
377 shutdown(c->ctl_fd, SHUT_RDWR);
378 channel_close_fds(c);
379 buffer_free(&c->input);
380 buffer_free(&c->output);
381 buffer_free(&c->extended);
382 if (c->remote_name) {
383 xfree(c->remote_name);
384 c->remote_name = NULL;
386 channels[c->self] = NULL;
391 channel_free_all(void)
395 for (i = 0; i < channels_alloc; i++)
396 if (channels[i] != NULL)
397 channel_free(channels[i]);
401 * Closes the sockets/fds of all channels. This is used to close extra file
402 * descriptors after a fork.
406 channel_close_all(void)
410 for (i = 0; i < channels_alloc; i++)
411 if (channels[i] != NULL)
412 channel_close_fds(channels[i]);
416 * Stop listening to channels.
420 channel_stop_listening(void)
425 for (i = 0; i < channels_alloc; i++) {
429 case SSH_CHANNEL_AUTH_SOCKET:
430 case SSH_CHANNEL_PORT_LISTENER:
431 case SSH_CHANNEL_RPORT_LISTENER:
432 case SSH_CHANNEL_X11_LISTENER:
433 channel_close_fd(&c->sock);
442 * Returns true if no channel has too much buffered data, and false if one or
443 * more channel is overfull.
447 channel_not_very_much_buffered_data(void)
452 for (i = 0; i < channels_alloc; i++) {
454 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
457 buffer_len(&c->input) > packet_get_maxsize()) {
458 debug2("channel %d: big input buffer %d",
459 c->self, buffer_len(&c->input));
463 if (buffer_len(&c->output) > packet_get_maxsize()) {
464 debug2("channel %d: big output buffer %u > %u",
465 c->self, buffer_len(&c->output),
466 packet_get_maxsize());
474 /* Returns true if any channel is still open. */
477 channel_still_open(void)
482 for (i = 0; i < channels_alloc; i++) {
487 case SSH_CHANNEL_X11_LISTENER:
488 case SSH_CHANNEL_PORT_LISTENER:
489 case SSH_CHANNEL_RPORT_LISTENER:
490 case SSH_CHANNEL_CLOSED:
491 case SSH_CHANNEL_AUTH_SOCKET:
492 case SSH_CHANNEL_DYNAMIC:
493 case SSH_CHANNEL_CONNECTING:
494 case SSH_CHANNEL_ZOMBIE:
496 case SSH_CHANNEL_LARVAL:
498 fatal("cannot happen: SSH_CHANNEL_LARVAL");
500 case SSH_CHANNEL_OPENING:
501 case SSH_CHANNEL_OPEN:
502 case SSH_CHANNEL_X11_OPEN:
504 case SSH_CHANNEL_INPUT_DRAINING:
505 case SSH_CHANNEL_OUTPUT_DRAINING:
507 fatal("cannot happen: OUT_DRAIN");
510 fatal("channel_still_open: bad channel type %d", c->type);
517 /* Returns the id of an open channel suitable for keepaliving */
520 channel_find_open(void)
525 for (i = 0; i < channels_alloc; i++) {
527 if (c == NULL || c->remote_id < 0)
530 case SSH_CHANNEL_CLOSED:
531 case SSH_CHANNEL_DYNAMIC:
532 case SSH_CHANNEL_X11_LISTENER:
533 case SSH_CHANNEL_PORT_LISTENER:
534 case SSH_CHANNEL_RPORT_LISTENER:
535 case SSH_CHANNEL_OPENING:
536 case SSH_CHANNEL_CONNECTING:
537 case SSH_CHANNEL_ZOMBIE:
539 case SSH_CHANNEL_LARVAL:
540 case SSH_CHANNEL_AUTH_SOCKET:
541 case SSH_CHANNEL_OPEN:
542 case SSH_CHANNEL_X11_OPEN:
544 case SSH_CHANNEL_INPUT_DRAINING:
545 case SSH_CHANNEL_OUTPUT_DRAINING:
547 fatal("cannot happen: OUT_DRAIN");
550 fatal("channel_find_open: bad channel type %d", c->type);
559 * Returns a message describing the currently open forwarded connections,
560 * suitable for sending to the client. The message contains crlf pairs for
565 channel_open_message(void)
572 buffer_init(&buffer);
573 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
574 buffer_append(&buffer, buf, strlen(buf));
575 for (i = 0; i < channels_alloc; i++) {
580 case SSH_CHANNEL_X11_LISTENER:
581 case SSH_CHANNEL_PORT_LISTENER:
582 case SSH_CHANNEL_RPORT_LISTENER:
583 case SSH_CHANNEL_CLOSED:
584 case SSH_CHANNEL_AUTH_SOCKET:
585 case SSH_CHANNEL_ZOMBIE:
587 case SSH_CHANNEL_LARVAL:
588 case SSH_CHANNEL_OPENING:
589 case SSH_CHANNEL_CONNECTING:
590 case SSH_CHANNEL_DYNAMIC:
591 case SSH_CHANNEL_OPEN:
592 case SSH_CHANNEL_X11_OPEN:
593 case SSH_CHANNEL_INPUT_DRAINING:
594 case SSH_CHANNEL_OUTPUT_DRAINING:
595 snprintf(buf, sizeof buf,
596 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
597 c->self, c->remote_name,
598 c->type, c->remote_id,
599 c->istate, buffer_len(&c->input),
600 c->ostate, buffer_len(&c->output),
601 c->rfd, c->wfd, c->ctl_fd);
602 buffer_append(&buffer, buf, strlen(buf));
605 fatal("channel_open_message: bad channel type %d", c->type);
609 buffer_append(&buffer, "\0", 1);
610 cp = xstrdup(buffer_ptr(&buffer));
611 buffer_free(&buffer);
616 channel_send_open(int id)
618 Channel *c = channel_lookup(id);
621 logit("channel_send_open: %d: bad id", id);
624 debug2("channel %d: send open", id);
625 packet_start(SSH2_MSG_CHANNEL_OPEN);
626 packet_put_cstring(c->ctype);
627 packet_put_int(c->self);
628 packet_put_int(c->local_window);
629 packet_put_int(c->local_maxpacket);
634 channel_request_start(int id, char *service, int wantconfirm)
636 Channel *c = channel_lookup(id);
639 logit("channel_request_start: %d: unknown channel id", id);
642 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
643 packet_start(SSH2_MSG_CHANNEL_REQUEST);
644 packet_put_int(c->remote_id);
645 packet_put_cstring(service);
646 packet_put_char(wantconfirm);
649 channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
651 Channel *c = channel_lookup(id);
654 logit("channel_register_comfirm: %d: bad id", id);
658 c->confirm_ctx = ctx;
661 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
663 Channel *c = channel_by_id(id);
666 logit("channel_register_cleanup: %d: bad id", id);
670 c->detach_close = do_close;
673 channel_cancel_cleanup(int id)
675 Channel *c = channel_by_id(id);
678 logit("channel_cancel_cleanup: %d: bad id", id);
681 c->detach_user = NULL;
685 channel_register_filter(int id, channel_infilter_fn *ifn,
686 channel_outfilter_fn *ofn)
688 Channel *c = channel_lookup(id);
691 logit("channel_register_filter: %d: bad id", id);
694 c->input_filter = ifn;
695 c->output_filter = ofn;
699 channel_set_fds(int id, int rfd, int wfd, int efd,
700 int extusage, int nonblock, u_int window_max)
702 Channel *c = channel_lookup(id);
704 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
705 fatal("channel_activate for non-larval channel %d.", id);
706 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
707 c->type = SSH_CHANNEL_OPEN;
708 c->local_window = c->local_window_max = window_max;
709 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
710 packet_put_int(c->remote_id);
711 packet_put_int(c->local_window);
716 * 'channel_pre*' are called just before select() to add any bits relevant to
717 * channels in the select bitmasks.
720 * 'channel_post*': perform any appropriate operations for channels which
721 * have events pending.
723 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
724 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
725 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
728 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
730 FD_SET(c->sock, readset);
734 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
736 debug3("channel %d: waiting for connection", c->self);
737 FD_SET(c->sock, writeset);
741 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
743 if (buffer_len(&c->input) < packet_get_maxsize())
744 FD_SET(c->sock, readset);
745 if (buffer_len(&c->output) > 0)
746 FD_SET(c->sock, writeset);
749 int channel_tcpwinsz () {
750 u_int32_t tcpwinsz = 0;
751 socklen_t optsz = sizeof(tcpwinsz);
753 if(!packet_connection_is_on_socket())
755 ret = getsockopt(packet_get_connection_in(),
756 SOL_SOCKET, SO_RCVBUF, &tcpwinsz, &optsz);
757 if ((ret == 0) && tcpwinsz > BUFFER_MAX_HPN_LEN)
758 tcpwinsz = BUFFER_MAX_HPN_LEN;
759 debug2("tcpwinsz: %d for connection: %d", tcpwinsz, packet_get_connection_in());
764 channel_pre_open(Channel *c, fd_set * readset, fd_set * writeset)
766 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
768 /* check buffer limits */
770 c->tcpwinsz = channel_tcpwinsz();
771 if (c->dynamic_window > 0)
772 c->tcpwinsz = channel_tcpwinsz();
774 limit = MIN(limit, 2 * c->tcpwinsz);
776 if (c->istate == CHAN_INPUT_OPEN &&
778 buffer_len(&c->input) < limit)
779 FD_SET(c->rfd, readset);
780 if (c->ostate == CHAN_OUTPUT_OPEN ||
781 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
782 if (buffer_len(&c->output) > 0) {
783 FD_SET(c->wfd, writeset);
784 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
785 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
786 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
787 c->self, c->efd, buffer_len(&c->extended));
792 /** XXX check close conditions, too */
793 if (compat20 && c->efd != -1) {
794 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
795 buffer_len(&c->extended) > 0)
796 FD_SET(c->efd, writeset);
797 else if (!(c->flags & CHAN_EOF_SENT) &&
798 c->extended_usage == CHAN_EXTENDED_READ &&
799 buffer_len(&c->extended) < c->remote_window)
800 FD_SET(c->efd, readset);
802 /* XXX: What about efd? races? */
803 if (compat20 && c->ctl_fd != -1 &&
804 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
805 FD_SET(c->ctl_fd, readset);
809 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
811 if (buffer_len(&c->input) == 0) {
812 packet_start(SSH_MSG_CHANNEL_CLOSE);
813 packet_put_int(c->remote_id);
815 c->type = SSH_CHANNEL_CLOSED;
816 debug2("channel %d: closing after input drain.", c->self);
821 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
823 if (buffer_len(&c->output) == 0)
826 FD_SET(c->sock, writeset);
830 * This is a special state for X11 authentication spoofing. An opened X11
831 * connection (when authentication spoofing is being done) remains in this
832 * state until the first packet has been completely read. The authentication
833 * data in that packet is then substituted by the real data if it matches the
834 * fake data, and the channel is put into normal mode.
835 * XXX All this happens at the client side.
836 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
839 x11_open_helper(Buffer *b)
842 u_int proto_len, data_len;
844 /* Check if the fixed size part of the packet is in buffer. */
845 if (buffer_len(b) < 12)
848 /* Parse the lengths of variable-length fields. */
850 if (ucp[0] == 0x42) { /* Byte order MSB first. */
851 proto_len = 256 * ucp[6] + ucp[7];
852 data_len = 256 * ucp[8] + ucp[9];
853 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
854 proto_len = ucp[6] + 256 * ucp[7];
855 data_len = ucp[8] + 256 * ucp[9];
857 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
862 /* Check if the whole packet is in buffer. */
864 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
867 /* Check if authentication protocol matches. */
868 if (proto_len != strlen(x11_saved_proto) ||
869 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
870 debug2("X11 connection uses different authentication protocol.");
873 /* Check if authentication data matches our fake data. */
874 if (data_len != x11_fake_data_len ||
875 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
876 x11_fake_data, x11_fake_data_len) != 0) {
877 debug2("X11 auth data does not match fake data.");
880 /* Check fake data length */
881 if (x11_fake_data_len != x11_saved_data_len) {
882 error("X11 fake_data_len %d != saved_data_len %d",
883 x11_fake_data_len, x11_saved_data_len);
887 * Received authentication protocol and data match
888 * our fake data. Substitute the fake data with real
891 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
892 x11_saved_data, x11_saved_data_len);
897 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
899 int ret = x11_open_helper(&c->output);
902 /* Start normal processing for the channel. */
903 c->type = SSH_CHANNEL_OPEN;
904 channel_pre_open_13(c, readset, writeset);
905 } else if (ret == -1) {
907 * We have received an X11 connection that has bad
908 * authentication information.
910 logit("X11 connection rejected because of wrong authentication.");
911 buffer_clear(&c->input);
912 buffer_clear(&c->output);
913 channel_close_fd(&c->sock);
915 c->type = SSH_CHANNEL_CLOSED;
916 packet_start(SSH_MSG_CHANNEL_CLOSE);
917 packet_put_int(c->remote_id);
923 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
925 int ret = x11_open_helper(&c->output);
927 /* c->force_drain = 1; */
930 c->type = SSH_CHANNEL_OPEN;
931 channel_pre_open(c, readset, writeset);
932 } else if (ret == -1) {
933 logit("X11 connection rejected because of wrong authentication.");
934 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
936 buffer_clear(&c->input);
938 buffer_clear(&c->output);
939 /* for proto v1, the peer will send an IEOF */
941 chan_write_failed(c);
943 c->type = SSH_CHANNEL_OPEN;
944 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
948 /* try to decode a socks4 header */
950 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
953 u_int len, have, i, found;
959 struct in_addr dest_addr;
962 debug2("channel %d: decode socks4", c->self);
964 have = buffer_len(&c->input);
965 len = sizeof(s4_req);
968 p = buffer_ptr(&c->input);
969 for (found = 0, i = len; i < have; i++) {
975 /* the peer is probably sending garbage */
976 debug("channel %d: decode socks4: too long",
983 buffer_get(&c->input, (char *)&s4_req.version, 1);
984 buffer_get(&c->input, (char *)&s4_req.command, 1);
985 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
986 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
987 have = buffer_len(&c->input);
988 p = buffer_ptr(&c->input);
990 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
992 fatal("channel %d: decode socks4: len %d > have %d",
994 strlcpy(username, p, sizeof(username));
995 buffer_consume(&c->input, len);
996 buffer_consume(&c->input, 1); /* trailing '\0' */
998 host = inet_ntoa(s4_req.dest_addr);
999 strlcpy(c->path, host, sizeof(c->path));
1000 c->host_port = ntohs(s4_req.dest_port);
1002 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1003 c->self, host, c->host_port, s4_req.command);
1005 if (s4_req.command != 1) {
1006 debug("channel %d: cannot handle: socks4 cn %d",
1007 c->self, s4_req.command);
1010 s4_rsp.version = 0; /* vn: 0 for reply */
1011 s4_rsp.command = 90; /* cd: req granted */
1012 s4_rsp.dest_port = 0; /* ignored */
1013 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1014 buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
1018 /* try to decode a socks5 header */
1019 #define SSH_SOCKS5_AUTHDONE 0x1000
1020 #define SSH_SOCKS5_NOAUTH 0x00
1021 #define SSH_SOCKS5_IPV4 0x01
1022 #define SSH_SOCKS5_DOMAIN 0x03
1023 #define SSH_SOCKS5_IPV6 0x04
1024 #define SSH_SOCKS5_CONNECT 0x01
1025 #define SSH_SOCKS5_SUCCESS 0x00
1028 channel_decode_socks5(Channel *c, fd_set * readset, fd_set * writeset)
1036 u_int16_t dest_port;
1037 u_char *p, dest_addr[255+1];
1038 u_int have, i, found, nmethods, addrlen, af;
1040 debug2("channel %d: decode socks5", c->self);
1041 p = buffer_ptr(&c->input);
1044 have = buffer_len(&c->input);
1045 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1046 /* format: ver | nmethods | methods */
1050 if (have < nmethods + 2)
1052 /* look for method: "NO AUTHENTICATION REQUIRED" */
1053 for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1054 if (p[i] == SSH_SOCKS5_NOAUTH ) {
1060 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1064 buffer_consume(&c->input, nmethods + 2);
1065 buffer_put_char(&c->output, 0x05); /* version */
1066 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1067 FD_SET(c->sock, writeset);
1068 c->flags |= SSH_SOCKS5_AUTHDONE;
1069 debug2("channel %d: socks5 auth done", c->self);
1070 return 0; /* need more */
1072 debug2("channel %d: socks5 post auth", c->self);
1073 if (have < sizeof(s5_req)+1)
1074 return 0; /* need more */
1075 memcpy((char *)&s5_req, p, sizeof(s5_req));
1076 if (s5_req.version != 0x05 ||
1077 s5_req.command != SSH_SOCKS5_CONNECT ||
1078 s5_req.reserved != 0x00) {
1079 debug2("channel %d: only socks5 connect supported", c->self);
1082 switch (s5_req.atyp){
1083 case SSH_SOCKS5_IPV4:
1087 case SSH_SOCKS5_DOMAIN:
1088 addrlen = p[sizeof(s5_req)];
1091 case SSH_SOCKS5_IPV6:
1096 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1099 if (have < 4 + addrlen + 2)
1101 buffer_consume(&c->input, sizeof(s5_req));
1102 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1103 buffer_consume(&c->input, 1); /* host string length */
1104 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1105 buffer_get(&c->input, (char *)&dest_port, 2);
1106 dest_addr[addrlen] = '\0';
1107 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1108 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1109 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1111 c->host_port = ntohs(dest_port);
1113 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1114 c->self, c->path, c->host_port, s5_req.command);
1116 s5_rsp.version = 0x05;
1117 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1118 s5_rsp.reserved = 0; /* ignored */
1119 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1120 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1121 dest_port = 0; /* ignored */
1123 buffer_append(&c->output, (char *)&s5_rsp, sizeof(s5_rsp));
1124 buffer_append(&c->output, (char *)&dest_addr, sizeof(struct in_addr));
1125 buffer_append(&c->output, (char *)&dest_port, sizeof(dest_port));
1129 /* dynamic port forwarding */
1131 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
1137 have = buffer_len(&c->input);
1139 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1140 /* buffer_dump(&c->input); */
1141 /* check if the fixed size part of the packet is in buffer. */
1144 FD_SET(c->sock, readset);
1147 /* try to guess the protocol */
1148 p = buffer_ptr(&c->input);
1151 ret = channel_decode_socks4(c, readset, writeset);
1154 ret = channel_decode_socks5(c, readset, writeset);
1162 } else if (ret == 0) {
1163 debug2("channel %d: pre_dynamic: need more", c->self);
1165 FD_SET(c->sock, readset);
1167 /* switch to the next state */
1168 c->type = SSH_CHANNEL_OPENING;
1169 port_open_helper(c, "direct-tcpip");
1173 /* This is our fake X11 server socket. */
1175 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
1178 struct sockaddr addr;
1181 char buf[16384], *remote_ipaddr;
1184 if (FD_ISSET(c->sock, readset)) {
1185 debug("X11 connection requested.");
1186 addrlen = sizeof(addr);
1187 newsock = accept(c->sock, &addr, &addrlen);
1188 if (c->single_connection) {
1189 debug2("single_connection: closing X11 listener.");
1190 channel_close_fd(&c->sock);
1194 error("accept: %.100s", strerror(errno));
1197 set_nodelay(newsock);
1198 remote_ipaddr = get_peer_ipaddr(newsock);
1199 remote_port = get_peer_port(newsock);
1200 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1201 remote_ipaddr, remote_port);
1203 nc = channel_new("accepted x11 socket",
1204 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1205 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1207 packet_start(SSH2_MSG_CHANNEL_OPEN);
1208 packet_put_cstring("x11");
1209 packet_put_int(nc->self);
1210 packet_put_int(nc->local_window_max);
1211 packet_put_int(nc->local_maxpacket);
1212 /* originator ipaddr and port */
1213 packet_put_cstring(remote_ipaddr);
1214 if (datafellows & SSH_BUG_X11FWD) {
1215 debug2("ssh2 x11 bug compat mode");
1217 packet_put_int(remote_port);
1221 packet_start(SSH_SMSG_X11_OPEN);
1222 packet_put_int(nc->self);
1223 if (packet_get_protocol_flags() &
1224 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1225 packet_put_cstring(buf);
1228 xfree(remote_ipaddr);
1233 port_open_helper(Channel *c, char *rtype)
1237 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1238 int remote_port = get_peer_port(c->sock);
1240 direct = (strcmp(rtype, "direct-tcpip") == 0);
1242 snprintf(buf, sizeof buf,
1243 "%s: listening port %d for %.100s port %d, "
1244 "connect from %.200s port %d",
1245 rtype, c->listening_port, c->path, c->host_port,
1246 remote_ipaddr, remote_port);
1248 xfree(c->remote_name);
1249 c->remote_name = xstrdup(buf);
1252 packet_start(SSH2_MSG_CHANNEL_OPEN);
1253 packet_put_cstring(rtype);
1254 packet_put_int(c->self);
1255 packet_put_int(c->local_window_max);
1256 packet_put_int(c->local_maxpacket);
1258 /* target host, port */
1259 packet_put_cstring(c->path);
1260 packet_put_int(c->host_port);
1262 /* listen address, port */
1263 packet_put_cstring(c->path);
1264 packet_put_int(c->listening_port);
1266 /* originator host and port */
1267 packet_put_cstring(remote_ipaddr);
1268 packet_put_int((u_int)remote_port);
1271 packet_start(SSH_MSG_PORT_OPEN);
1272 packet_put_int(c->self);
1273 packet_put_cstring(c->path);
1274 packet_put_int(c->host_port);
1275 if (packet_get_protocol_flags() &
1276 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1277 packet_put_cstring(c->remote_name);
1280 xfree(remote_ipaddr);
1284 channel_set_reuseaddr(int fd)
1289 * Set socket options.
1290 * Allow local port reuse in TIME_WAIT.
1292 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1293 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1297 * This socket is listening for connections to a forwarded TCP/IP port.
1300 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
1303 struct sockaddr addr;
1304 int newsock, nextstate;
1308 if (FD_ISSET(c->sock, readset)) {
1309 debug("Connection to port %d forwarding "
1310 "to %.100s port %d requested.",
1311 c->listening_port, c->path, c->host_port);
1313 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1314 nextstate = SSH_CHANNEL_OPENING;
1315 rtype = "forwarded-tcpip";
1317 if (c->host_port == 0) {
1318 nextstate = SSH_CHANNEL_DYNAMIC;
1319 rtype = "dynamic-tcpip";
1321 nextstate = SSH_CHANNEL_OPENING;
1322 rtype = "direct-tcpip";
1326 addrlen = sizeof(addr);
1327 newsock = accept(c->sock, &addr, &addrlen);
1329 error("accept: %.100s", strerror(errno));
1332 set_nodelay(newsock);
1333 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1334 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1335 nc->listening_port = c->listening_port;
1336 nc->host_port = c->host_port;
1337 strlcpy(nc->path, c->path, sizeof(nc->path));
1339 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1341 * do not call the channel_post handler until
1342 * this flag has been reset by a pre-handler.
1343 * otherwise the FD_ISSET calls might overflow
1347 port_open_helper(nc, rtype);
1353 * This is the authentication agent socket listening for connections from
1357 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
1361 struct sockaddr addr;
1364 if (FD_ISSET(c->sock, readset)) {
1365 addrlen = sizeof(addr);
1366 newsock = accept(c->sock, &addr, &addrlen);
1368 error("accept from auth socket: %.100s", strerror(errno));
1371 nc = channel_new("accepted auth socket",
1372 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1373 c->local_window_max, c->local_maxpacket,
1374 0, "accepted auth socket", 1);
1376 packet_start(SSH2_MSG_CHANNEL_OPEN);
1377 packet_put_cstring("auth-agent@openssh.com");
1378 packet_put_int(nc->self);
1379 packet_put_int(c->local_window_max);
1380 packet_put_int(c->local_maxpacket);
1382 packet_start(SSH_SMSG_AGENT_OPEN);
1383 packet_put_int(nc->self);
1390 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
1393 socklen_t sz = sizeof(err);
1395 if (FD_ISSET(c->sock, writeset)) {
1396 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1398 error("getsockopt SO_ERROR failed");
1401 debug("channel %d: connected", c->self);
1402 c->type = SSH_CHANNEL_OPEN;
1404 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1405 packet_put_int(c->remote_id);
1406 packet_put_int(c->self);
1407 packet_put_int(c->local_window);
1408 packet_put_int(c->local_maxpacket);
1410 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1411 packet_put_int(c->remote_id);
1412 packet_put_int(c->self);
1415 debug("channel %d: not connected: %s",
1416 c->self, strerror(err));
1418 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1419 packet_put_int(c->remote_id);
1420 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1421 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1422 packet_put_cstring(strerror(err));
1423 packet_put_cstring("");
1426 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1427 packet_put_int(c->remote_id);
1436 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
1438 char buf[CHAN_RBUF];
1442 FD_ISSET(c->rfd, readset)) {
1443 len = read(c->rfd, buf, sizeof(buf));
1444 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1447 debug2("channel %d: read<=0 rfd %d len %d",
1448 c->self, c->rfd, len);
1449 if (c->type != SSH_CHANNEL_OPEN) {
1450 debug2("channel %d: not open", c->self);
1453 } else if (compat13) {
1454 buffer_clear(&c->output);
1455 c->type = SSH_CHANNEL_INPUT_DRAINING;
1456 debug2("channel %d: input draining.", c->self);
1458 chan_read_failed(c);
1462 if (c->input_filter != NULL) {
1463 if (c->input_filter(c, buf, len) == -1) {
1464 debug2("channel %d: filter stops", c->self);
1465 chan_read_failed(c);
1467 } else if (c->datagram) {
1468 buffer_put_string(&c->input, buf, len);
1470 buffer_append(&c->input, buf, len);
1476 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
1479 u_char *data = NULL, *buf;
1483 /* Send buffered output data to the socket. */
1485 FD_ISSET(c->wfd, writeset) &&
1486 buffer_len(&c->output) > 0) {
1487 if (c->output_filter != NULL) {
1488 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1489 debug2("channel %d: filter stops", c->self);
1490 if (c->type != SSH_CHANNEL_OPEN)
1493 chan_write_failed(c);
1496 } else if (c->datagram) {
1497 buf = data = buffer_get_string(&c->output, &dlen);
1499 buf = data = buffer_ptr(&c->output);
1500 dlen = buffer_len(&c->output);
1504 /* ignore truncated writes, datagrams might get lost */
1505 c->local_consumed += dlen + 4;
1506 len = write(c->wfd, buf, dlen);
1508 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1511 if (c->type != SSH_CHANNEL_OPEN)
1514 chan_write_failed(c);
1520 /* XXX: Later AIX versions can't push as much data to tty */
1521 if (compat20 && c->wfd_isatty)
1522 dlen = MIN(dlen, 8*1024);
1525 len = write(c->wfd, buf, dlen);
1526 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1529 if (c->type != SSH_CHANNEL_OPEN) {
1530 debug2("channel %d: not open", c->self);
1533 } else if (compat13) {
1534 buffer_clear(&c->output);
1535 debug2("channel %d: input draining.", c->self);
1536 c->type = SSH_CHANNEL_INPUT_DRAINING;
1538 chan_write_failed(c);
1542 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1543 if (tcgetattr(c->wfd, &tio) == 0 &&
1544 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1546 * Simulate echo to reduce the impact of
1547 * traffic analysis. We need to match the
1548 * size of a SSH2_MSG_CHANNEL_DATA message
1549 * (4 byte channel id + buf)
1551 packet_send_ignore(4 + len);
1555 buffer_consume(&c->output, len);
1556 if (compat20 && len > 0) {
1557 c->local_consumed += len;
1563 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
1565 char buf[CHAN_RBUF];
1568 /** XXX handle drain efd, too */
1570 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1571 FD_ISSET(c->efd, writeset) &&
1572 buffer_len(&c->extended) > 0) {
1573 len = write(c->efd, buffer_ptr(&c->extended),
1574 buffer_len(&c->extended));
1575 debug2("channel %d: written %d to efd %d",
1576 c->self, len, c->efd);
1577 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1580 debug2("channel %d: closing write-efd %d",
1582 channel_close_fd(&c->efd);
1584 buffer_consume(&c->extended, len);
1585 c->local_consumed += len;
1587 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1588 FD_ISSET(c->efd, readset)) {
1589 len = read(c->efd, buf, sizeof(buf));
1590 debug2("channel %d: read %d from efd %d",
1591 c->self, len, c->efd);
1592 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1595 debug2("channel %d: closing read-efd %d",
1597 channel_close_fd(&c->efd);
1599 buffer_append(&c->extended, buf, len);
1606 channel_handle_ctl(Channel *c, fd_set * readset, fd_set * writeset)
1611 /* Monitor control fd to detect if the slave client exits */
1612 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1613 len = read(c->ctl_fd, buf, sizeof(buf));
1614 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1617 debug2("channel %d: ctl read<=0", c->self);
1618 if (c->type != SSH_CHANNEL_OPEN) {
1619 debug2("channel %d: not open", c->self);
1623 chan_read_failed(c);
1624 chan_write_failed(c);
1628 fatal("%s: unexpected data on ctl fd", __func__);
1633 channel_check_window(Channel *c)
1635 if (c->type == SSH_CHANNEL_OPEN &&
1636 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1637 c->local_window < c->local_window_max/2 &&
1638 c->local_consumed > 0) {
1640 /* adjust max window size if we are in a dynamic environment */
1641 if (c->dynamic_window && (c->tcpwinsz > c->local_window_max)) {
1642 addition = c->tcpwinsz - c->local_window_max;
1643 c->local_window_max += addition;
1645 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1646 packet_put_int(c->remote_id);
1647 packet_put_int(c->local_consumed + addition);
1649 debug2("channel %d: window %d sent adjust %d",
1650 c->self, c->local_window,
1652 c->local_window += c->local_consumed + addition;
1653 c->local_consumed = 0;
1659 channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1663 channel_handle_rfd(c, readset, writeset);
1664 channel_handle_wfd(c, readset, writeset);
1667 channel_handle_efd(c, readset, writeset);
1668 channel_handle_ctl(c, readset, writeset);
1669 channel_check_window(c);
1673 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1677 /* Send buffered output data to the socket. */
1678 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1679 len = write(c->sock, buffer_ptr(&c->output),
1680 buffer_len(&c->output));
1682 buffer_clear(&c->output);
1684 buffer_consume(&c->output, len);
1689 channel_handler_init_20(void)
1691 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1692 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1693 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1694 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1695 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1696 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1697 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1698 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1700 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1701 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1702 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1703 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1704 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1705 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1706 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1710 channel_handler_init_13(void)
1712 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1713 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1714 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1715 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1716 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1717 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1718 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1719 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1720 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1722 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1723 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1724 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1725 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1726 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1727 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1728 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1732 channel_handler_init_15(void)
1734 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1735 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1736 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1737 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1738 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1739 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1740 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1742 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1743 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1744 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1745 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1746 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1747 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1751 channel_handler_init(void)
1755 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1756 channel_pre[i] = NULL;
1757 channel_post[i] = NULL;
1760 channel_handler_init_20();
1762 channel_handler_init_13();
1764 channel_handler_init_15();
1767 /* gc dead channels */
1769 channel_garbage_collect(Channel *c)
1773 if (c->detach_user != NULL) {
1774 if (!chan_is_dead(c, c->detach_close))
1776 debug2("channel %d: gc: notify user", c->self);
1777 c->detach_user(c->self, NULL);
1778 /* if we still have a callback */
1779 if (c->detach_user != NULL)
1781 debug2("channel %d: gc: user detached", c->self);
1783 if (!chan_is_dead(c, 1))
1785 debug2("channel %d: garbage collecting", c->self);
1790 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1792 static int did_init = 0;
1797 channel_handler_init();
1800 for (i = 0; i < channels_alloc; i++) {
1804 if (ftab[c->type] != NULL)
1805 (*ftab[c->type])(c, readset, writeset);
1806 channel_garbage_collect(c);
1811 * Allocate/update select bitmasks and add any bits relevant to channels in
1815 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1816 u_int *nallocp, int rekeying)
1820 n = MAX(*maxfdp, channel_max_fd);
1822 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1823 /* perhaps check sz < nalloc/2 and shrink? */
1824 if (*readsetp == NULL || sz > *nallocp) {
1825 *readsetp = xrealloc(*readsetp, sz);
1826 *writesetp = xrealloc(*writesetp, sz);
1830 memset(*readsetp, 0, sz);
1831 memset(*writesetp, 0, sz);
1834 channel_handler(channel_pre, *readsetp, *writesetp);
1838 * After select, perform any appropriate operations for channels which have
1842 channel_after_select(fd_set * readset, fd_set * writeset)
1844 channel_handler(channel_post, readset, writeset);
1848 /* If there is data to send to the connection, enqueue some of it now. */
1851 channel_output_poll(void)
1856 for (i = 0; i < channels_alloc; i++) {
1862 * We are only interested in channels that can have buffered
1866 if (c->type != SSH_CHANNEL_OPEN &&
1867 c->type != SSH_CHANNEL_INPUT_DRAINING)
1870 if (c->type != SSH_CHANNEL_OPEN)
1874 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1875 /* XXX is this true? */
1876 debug3("channel %d: will not send data after close", c->self);
1880 /* Get the amount of buffered data for this channel. */
1881 if ((c->istate == CHAN_INPUT_OPEN ||
1882 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1883 (len = buffer_len(&c->input)) > 0) {
1889 data = buffer_get_string(&c->input,
1891 packet_start(SSH2_MSG_CHANNEL_DATA);
1892 packet_put_int(c->remote_id);
1893 packet_put_string(data, dlen);
1895 c->remote_window -= dlen + 4;
1901 * Send some data for the other side over the secure
1905 if (len > c->remote_window)
1906 len = c->remote_window;
1907 if (len > c->remote_maxpacket)
1908 len = c->remote_maxpacket;
1910 if (packet_is_interactive()) {
1914 /* Keep the packets at reasonable size. */
1915 if (len > packet_get_maxsize()/2)
1916 len = packet_get_maxsize()/2;
1920 packet_start(compat20 ?
1921 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1922 packet_put_int(c->remote_id);
1923 packet_put_string(buffer_ptr(&c->input), len);
1925 buffer_consume(&c->input, len);
1926 c->remote_window -= len;
1928 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1930 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1932 * input-buffer is empty and read-socket shutdown:
1933 * tell peer, that we will not send more data: send IEOF.
1934 * hack for extended data: delay EOF if EFD still in use.
1936 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1937 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1938 c->self, c->efd, buffer_len(&c->extended));
1942 /* Send extended data, i.e. stderr */
1944 !(c->flags & CHAN_EOF_SENT) &&
1945 c->remote_window > 0 &&
1946 (len = buffer_len(&c->extended)) > 0 &&
1947 c->extended_usage == CHAN_EXTENDED_READ) {
1948 debug2("channel %d: rwin %u elen %u euse %d",
1949 c->self, c->remote_window, buffer_len(&c->extended),
1951 if (len > c->remote_window)
1952 len = c->remote_window;
1953 if (len > c->remote_maxpacket)
1954 len = c->remote_maxpacket;
1955 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1956 packet_put_int(c->remote_id);
1957 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1958 packet_put_string(buffer_ptr(&c->extended), len);
1960 buffer_consume(&c->extended, len);
1961 c->remote_window -= len;
1962 debug2("channel %d: sent ext data %d", c->self, len);
1968 /* -- protocol input */
1971 channel_input_data(int type, u_int32_t seq, void *ctxt)
1978 /* Get the channel number and verify it. */
1979 id = packet_get_int();
1980 c = channel_lookup(id);
1982 packet_disconnect("Received data for nonexistent channel %d.", id);
1984 /* Ignore any data for non-open channels (might happen on close) */
1985 if (c->type != SSH_CHANNEL_OPEN &&
1986 c->type != SSH_CHANNEL_X11_OPEN)
1990 data = packet_get_string(&data_len);
1993 * Ignore data for protocol > 1.3 if output end is no longer open.
1994 * For protocol 2 the sending side is reducing its window as it sends
1995 * data, so we must 'fake' consumption of the data in order to ensure
1996 * that window updates are sent back. Otherwise the connection might
1999 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2001 c->local_window -= data_len;
2002 c->local_consumed += data_len;
2009 if (data_len > c->local_maxpacket) {
2010 logit("channel %d: rcvd big packet %d, maxpack %d",
2011 c->self, data_len, c->local_maxpacket);
2013 if (data_len > c->local_window) {
2014 logit("channel %d: rcvd too much data %d, win %d",
2015 c->self, data_len, c->local_window);
2019 c->local_window -= data_len;
2023 buffer_put_string(&c->output, data, data_len);
2025 buffer_append(&c->output, data, data_len);
2030 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2034 u_int data_len, tcode;
2037 /* Get the channel number and verify it. */
2038 id = packet_get_int();
2039 c = channel_lookup(id);
2042 packet_disconnect("Received extended_data for bad channel %d.", id);
2043 if (c->type != SSH_CHANNEL_OPEN) {
2044 logit("channel %d: ext data for non open", id);
2047 if (c->flags & CHAN_EOF_RCVD) {
2048 if (datafellows & SSH_BUG_EXTEOF)
2049 debug("channel %d: accepting ext data after eof", id);
2051 packet_disconnect("Received extended_data after EOF "
2052 "on channel %d.", id);
2054 tcode = packet_get_int();
2056 c->extended_usage != CHAN_EXTENDED_WRITE ||
2057 tcode != SSH2_EXTENDED_DATA_STDERR) {
2058 logit("channel %d: bad ext data", c->self);
2061 data = packet_get_string(&data_len);
2063 if (data_len > c->local_window) {
2064 logit("channel %d: rcvd too much extended_data %d, win %d",
2065 c->self, data_len, c->local_window);
2069 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2070 c->local_window -= data_len;
2071 buffer_append(&c->extended, data, data_len);
2076 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2081 id = packet_get_int();
2083 c = channel_lookup(id);
2085 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2088 /* XXX force input close */
2089 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2090 debug("channel %d: FORCE input drain", c->self);
2091 c->istate = CHAN_INPUT_WAIT_DRAIN;
2092 if (buffer_len(&c->input) == 0)
2099 channel_input_close(int type, u_int32_t seq, void *ctxt)
2104 id = packet_get_int();
2106 c = channel_lookup(id);
2108 packet_disconnect("Received close for nonexistent channel %d.", id);
2111 * Send a confirmation that we have closed the channel and no more
2112 * data is coming for it.
2114 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2115 packet_put_int(c->remote_id);
2119 * If the channel is in closed state, we have sent a close request,
2120 * and the other side will eventually respond with a confirmation.
2121 * Thus, we cannot free the channel here, because then there would be
2122 * no-one to receive the confirmation. The channel gets freed when
2123 * the confirmation arrives.
2125 if (c->type != SSH_CHANNEL_CLOSED) {
2127 * Not a closed channel - mark it as draining, which will
2128 * cause it to be freed later.
2130 buffer_clear(&c->input);
2131 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2135 /* 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);
2149 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2151 int id = packet_get_int();
2152 Channel *c = channel_lookup(id);
2156 packet_disconnect("Received close confirmation for "
2157 "out-of-range channel %d.", id);
2158 if (c->type != SSH_CHANNEL_CLOSED)
2159 packet_disconnect("Received close confirmation for "
2160 "non-closed channel %d (type %d).", id, c->type);
2165 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2170 id = packet_get_int();
2171 c = channel_lookup(id);
2173 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2174 packet_disconnect("Received open confirmation for "
2175 "non-opening channel %d.", id);
2176 remote_id = packet_get_int();
2177 /* Record the remote channel number and mark that the channel is now open. */
2178 c->remote_id = remote_id;
2179 c->type = SSH_CHANNEL_OPEN;
2182 c->remote_window = packet_get_int();
2183 c->remote_maxpacket = packet_get_int();
2185 debug2("callback start");
2186 c->confirm(c->self, c->confirm_ctx);
2187 debug2("callback done");
2189 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2190 c->remote_window, c->remote_maxpacket);
2196 reason2txt(int reason)
2199 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2200 return "administratively prohibited";
2201 case SSH2_OPEN_CONNECT_FAILED:
2202 return "connect failed";
2203 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2204 return "unknown channel type";
2205 case SSH2_OPEN_RESOURCE_SHORTAGE:
2206 return "resource shortage";
2208 return "unknown reason";
2212 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2215 char *msg = NULL, *lang = NULL;
2218 id = packet_get_int();
2219 c = channel_lookup(id);
2221 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2222 packet_disconnect("Received open failure for "
2223 "non-opening channel %d.", id);
2225 reason = packet_get_int();
2226 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2227 msg = packet_get_string(NULL);
2228 lang = packet_get_string(NULL);
2230 logit("channel %d: open failed: %s%s%s", id,
2231 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2238 /* Free the channel. This will also close the socket. */
2243 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2252 /* Get the channel number and verify it. */
2253 id = packet_get_int();
2254 c = channel_lookup(id);
2257 logit("Received window adjust for non-open channel %d.", id);
2260 adjust = packet_get_int();
2262 debug2("channel %d: rcvd adjust %u", id, adjust);
2263 c->remote_window += adjust;
2267 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2271 char *host, *originator_string;
2272 int remote_id, sock = -1;
2274 remote_id = packet_get_int();
2275 host = packet_get_string(NULL);
2276 host_port = packet_get_int();
2278 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2279 originator_string = packet_get_string(NULL);
2281 originator_string = xstrdup("unknown (remote did not supply name)");
2284 sock = channel_connect_to(host, host_port);
2286 c = channel_new("connected socket",
2287 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2288 originator_string, 1);
2289 c->remote_id = remote_id;
2291 xfree(originator_string);
2293 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2294 packet_put_int(remote_id);
2301 /* -- tcp forwarding */
2304 channel_set_af(int af)
2310 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2311 const char *host_to_connect, u_short port_to_connect, int gateway_ports,
2312 int hpn_disabled, int hpn_buffer_size)
2315 int sock, r, success = 0, wildcard = 0, is_client;
2316 struct addrinfo hints, *ai, *aitop;
2317 const char *host, *addr;
2318 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2320 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2321 listen_addr : host_to_connect;
2322 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2325 error("No forward host name.");
2328 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2329 error("Forward host name too long.");
2334 * Determine whether or not a port forward listens to loopback,
2335 * specified address or wildcard. On the client, a specified bind
2336 * address will always override gateway_ports. On the server, a
2337 * gateway_ports of 1 (``yes'') will override the client's
2338 * specification and force a wildcard bind, whereas a value of 2
2339 * (``clientspecified'') will bind to whatever address the client
2342 * Special-case listen_addrs are:
2344 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2345 * "" (empty string), "*" -> wildcard v4/v6
2346 * "localhost" -> loopback v4/v6
2349 if (listen_addr == NULL) {
2350 /* No address specified: default to gateway_ports setting */
2353 } else if (gateway_ports || is_client) {
2354 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2355 strcmp(listen_addr, "0.0.0.0") == 0) ||
2356 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2357 (!is_client && gateway_ports == 1))
2359 else if (strcmp(listen_addr, "localhost") != 0)
2363 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2364 type, wildcard, (addr == NULL) ? "NULL" : addr);
2367 * getaddrinfo returns a loopback address if the hostname is
2368 * set to NULL and hints.ai_flags is not AI_PASSIVE
2370 memset(&hints, 0, sizeof(hints));
2371 hints.ai_family = IPv4or6;
2372 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2373 hints.ai_socktype = SOCK_STREAM;
2374 snprintf(strport, sizeof strport, "%d", listen_port);
2375 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2377 /* This really shouldn't happen */
2378 packet_disconnect("getaddrinfo: fatal error: %s",
2381 error("channel_setup_fwd_listener: "
2382 "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
2387 for (ai = aitop; ai; ai = ai->ai_next) {
2388 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2390 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2391 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2392 error("channel_setup_fwd_listener: getnameinfo failed");
2395 /* Create a port to listen for the host. */
2396 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2398 /* this is no error since kernel may not support ipv6 */
2399 verbose("socket: %.100s", strerror(errno));
2403 channel_set_reuseaddr(sock);
2405 debug("Local forwarding listening on %s port %s.", ntop, strport);
2407 /* Bind the socket to the address. */
2408 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2409 /* address can be in use ipv6 address is already bound */
2411 error("bind: %.100s", strerror(errno));
2413 verbose("bind: %.100s", strerror(errno));
2418 /* Start listening for connections on the socket. */
2419 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2420 error("listen: %.100s", strerror(errno));
2424 /* Allocate a channel number for the socket. */
2425 /* explicitly test for hpn disabled option. if true use smaller window size */
2427 c = channel_new("port listener", type, sock, sock, -1,
2428 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2429 0, "port listener", 1);
2431 c = channel_new("port listener", type, sock, sock, -1,
2432 hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
2433 0, "port listener", 1);
2434 strlcpy(c->path, host, sizeof(c->path));
2435 c->host_port = port_to_connect;
2436 c->listening_port = listen_port;
2440 error("channel_setup_fwd_listener: cannot listen to port: %d",
2442 freeaddrinfo(aitop);
2447 channel_cancel_rport_listener(const char *host, u_short port)
2452 for (i = 0; i < channels_alloc; i++) {
2453 Channel *c = channels[i];
2455 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2456 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2457 c->listening_port == port) {
2458 debug2("%s: close channel %d", __func__, i);
2467 /* protocol local port fwd, used by ssh (and sshd in v1) */
2469 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2470 const char *host_to_connect, u_short port_to_connect, int gateway_ports,
2471 int hpn_disabled, int hpn_buffer_size)
2473 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2474 listen_host, listen_port, host_to_connect, port_to_connect,
2475 gateway_ports, hpn_disabled, hpn_buffer_size);
2478 /* protocol v2 remote port fwd, used by sshd */
2480 channel_setup_remote_fwd_listener(const char *listen_address,
2481 u_short listen_port, int gateway_ports, int hpn_disabled, int hpn_buffer_size)
2483 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2484 listen_address, listen_port, NULL, 0, gateway_ports,
2485 hpn_disabled, hpn_buffer_size);
2489 * Initiate forwarding of connections to port "port" on remote host through
2490 * the secure channel to host:port from local side.
2494 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2495 const char *host_to_connect, u_short port_to_connect)
2497 int type, success = 0;
2499 /* Record locally that connection to this host/port is permitted. */
2500 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2501 fatal("channel_request_remote_forwarding: too many forwards");
2503 /* Send the forward request to the remote side. */
2505 const char *address_to_bind;
2506 if (listen_host == NULL)
2507 address_to_bind = "localhost";
2508 else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
2509 address_to_bind = "";
2511 address_to_bind = listen_host;
2513 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2514 packet_put_cstring("tcpip-forward");
2515 packet_put_char(1); /* boolean: want reply */
2516 packet_put_cstring(address_to_bind);
2517 packet_put_int(listen_port);
2519 packet_write_wait();
2520 /* Assume that server accepts the request */
2523 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2524 packet_put_int(listen_port);
2525 packet_put_cstring(host_to_connect);
2526 packet_put_int(port_to_connect);
2528 packet_write_wait();
2530 /* Wait for response from the remote side. */
2531 type = packet_read();
2533 case SSH_SMSG_SUCCESS:
2536 case SSH_SMSG_FAILURE:
2537 logit("Warning: Server denied remote port forwarding.");
2540 /* Unknown packet */
2541 packet_disconnect("Protocol error for port forward request:"
2542 "received packet type %d.", type);
2546 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2547 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2548 permitted_opens[num_permitted_opens].listen_port = listen_port;
2549 num_permitted_opens++;
2554 * Request cancellation of remote forwarding of connection host:port from
2558 channel_request_rforward_cancel(const char *host, u_short port)
2565 for (i = 0; i < num_permitted_opens; i++) {
2566 if (permitted_opens[i].host_to_connect != NULL &&
2567 permitted_opens[i].listen_port == port)
2570 if (i >= num_permitted_opens) {
2571 debug("%s: requested forward not found", __func__);
2574 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2575 packet_put_cstring("cancel-tcpip-forward");
2577 packet_put_cstring(host == NULL ? "" : host);
2578 packet_put_int(port);
2581 permitted_opens[i].listen_port = 0;
2582 permitted_opens[i].port_to_connect = 0;
2583 xfree(permitted_opens[i].host_to_connect);
2584 permitted_opens[i].host_to_connect = NULL;
2588 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2589 * listening for the port, and sends back a success reply (or disconnect
2590 * message if there was an error). This never returns if there was an error.
2594 channel_input_port_forward_request(int is_root, int gateway_ports,
2595 int hpn_disabled, int hpn_buffer_size)
2597 u_short port, host_port;
2600 /* Get arguments from the packet. */
2601 port = packet_get_int();
2602 hostname = packet_get_string(NULL);
2603 host_port = packet_get_int();
2607 * Check that an unprivileged user is not trying to forward a
2610 if (port < IPPORT_RESERVED && !is_root)
2612 "Requested forwarding of port %d but user is not root.",
2615 packet_disconnect("Dynamic forwarding denied.");
2618 /* Initiate forwarding */
2619 channel_setup_local_fwd_listener(NULL, port, hostname,
2620 host_port, gateway_ports, hpn_disabled, hpn_buffer_size);
2622 /* Free the argument string. */
2627 * Permits opening to any host/port if permitted_opens[] is empty. This is
2628 * usually called by the server, because the user could connect to any port
2629 * anyway, and the server has no way to know but to trust the client anyway.
2632 channel_permit_all_opens(void)
2634 if (num_permitted_opens == 0)
2635 all_opens_permitted = 1;
2639 channel_add_permitted_opens(char *host, int port)
2641 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2642 fatal("channel_request_remote_forwarding: too many forwards");
2643 debug("allow port forwarding to host %s port %d", host, port);
2645 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2646 permitted_opens[num_permitted_opens].port_to_connect = port;
2647 num_permitted_opens++;
2649 all_opens_permitted = 0;
2653 channel_clear_permitted_opens(void)
2657 for (i = 0; i < num_permitted_opens; i++)
2658 if (permitted_opens[i].host_to_connect != NULL)
2659 xfree(permitted_opens[i].host_to_connect);
2660 num_permitted_opens = 0;
2665 /* return socket to remote host, port */
2667 connect_to(const char *host, u_short port)
2669 struct addrinfo hints, *ai, *aitop;
2670 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2674 memset(&hints, 0, sizeof(hints));
2675 hints.ai_family = IPv4or6;
2676 hints.ai_socktype = SOCK_STREAM;
2677 snprintf(strport, sizeof strport, "%d", port);
2678 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2679 error("connect_to %.100s: unknown host (%s)", host,
2680 gai_strerror(gaierr));
2683 for (ai = aitop; ai; ai = ai->ai_next) {
2684 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2686 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2687 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2688 error("connect_to: getnameinfo failed");
2691 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2693 if (ai->ai_next == NULL)
2694 error("socket: %.100s", strerror(errno));
2696 verbose("socket: %.100s", strerror(errno));
2699 if (set_nonblock(sock) == -1)
2700 fatal("%s: set_nonblock(%d)", __func__, sock);
2701 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2702 errno != EINPROGRESS) {
2703 error("connect_to %.100s port %s: %.100s", ntop, strport,
2706 continue; /* fail -- try next */
2708 break; /* success */
2711 freeaddrinfo(aitop);
2713 error("connect_to %.100s port %d: failed.", host, port);
2722 channel_connect_by_listen_address(u_short listen_port)
2726 for (i = 0; i < num_permitted_opens; i++)
2727 if (permitted_opens[i].host_to_connect != NULL &&
2728 permitted_opens[i].listen_port == listen_port)
2730 permitted_opens[i].host_to_connect,
2731 permitted_opens[i].port_to_connect);
2732 error("WARNING: Server requests forwarding for unknown listen_port %d",
2737 /* Check if connecting to that port is permitted and connect. */
2739 channel_connect_to(const char *host, u_short port)
2743 permit = all_opens_permitted;
2745 for (i = 0; i < num_permitted_opens; i++)
2746 if (permitted_opens[i].host_to_connect != NULL &&
2747 permitted_opens[i].port_to_connect == port &&
2748 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2753 logit("Received request to connect to host %.100s port %d, "
2754 "but the request was denied.", host, port);
2757 return connect_to(host, port);
2761 channel_send_window_changes(void)
2766 for (i = 0; i < channels_alloc; i++) {
2767 if (channels[i] == NULL || !channels[i]->client_tty ||
2768 channels[i]->type != SSH_CHANNEL_OPEN)
2770 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2772 channel_request_start(i, "window-change", 0);
2773 packet_put_int(ws.ws_col);
2774 packet_put_int(ws.ws_row);
2775 packet_put_int(ws.ws_xpixel);
2776 packet_put_int(ws.ws_ypixel);
2781 /* -- X11 forwarding */
2784 * Creates an internet domain socket for listening for X11 connections.
2785 * Returns 0 and a suitable display number for the DISPLAY variable
2786 * stored in display_numberp , or -1 if an error occurs.
2789 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2790 int single_connection, u_int *display_numberp, int **chanids,
2791 int hpn_disabled, int hpn_buffer_size)
2794 int display_number, sock;
2796 struct addrinfo hints, *ai, *aitop;
2797 char strport[NI_MAXSERV];
2798 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2800 if (chanids == NULL)
2803 for (display_number = x11_display_offset;
2804 display_number < MAX_DISPLAYS;
2806 port = 6000 + display_number;
2807 memset(&hints, 0, sizeof(hints));
2808 hints.ai_family = IPv4or6;
2809 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2810 hints.ai_socktype = SOCK_STREAM;
2811 snprintf(strport, sizeof strport, "%d", port);
2812 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2813 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2816 for (ai = aitop; ai; ai = ai->ai_next) {
2817 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2819 sock = socket(ai->ai_family, ai->ai_socktype,
2822 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2823 error("socket: %.100s", strerror(errno));
2824 freeaddrinfo(aitop);
2827 debug("x11_create_display_inet: Socket family %d not supported",
2833 if (ai->ai_family == AF_INET6) {
2835 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2836 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2839 channel_set_reuseaddr(sock);
2840 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2841 debug2("bind port %d: %.100s", port, strerror(errno));
2847 for (n = 0; n < num_socks; n++) {
2853 socks[num_socks++] = sock;
2854 #ifndef DONT_TRY_OTHER_AF
2855 if (num_socks == NUM_SOCKS)
2858 if (x11_use_localhost) {
2859 if (num_socks == NUM_SOCKS)
2866 freeaddrinfo(aitop);
2870 if (display_number >= MAX_DISPLAYS) {
2871 error("Failed to allocate internet-domain X11 display socket.");
2874 /* Start listening for connections on the socket. */
2875 for (n = 0; n < num_socks; n++) {
2877 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2878 error("listen: %.100s", strerror(errno));
2884 /* Allocate a channel for each socket. */
2885 *chanids = xmalloc(sizeof(**chanids) * (num_socks + 1));
2886 for (n = 0; n < num_socks; n++) {
2889 nc = channel_new("x11 listener",
2890 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2891 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2892 0, "X11 inet listener", 1);
2894 nc = channel_new("x11 listener",
2895 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2896 hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
2897 0, "X11 inet listener", 1);
2898 nc->single_connection = single_connection;
2899 (*chanids)[n] = nc->self;
2903 /* Return the display number for the DISPLAY environment variable. */
2904 *display_numberp = display_number;
2909 connect_local_xsocket(u_int dnr)
2912 struct sockaddr_un addr;
2914 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2916 error("socket: %.100s", strerror(errno));
2917 memset(&addr, 0, sizeof(addr));
2918 addr.sun_family = AF_UNIX;
2919 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2920 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2923 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2928 x11_connect_display(void)
2930 int display_number, sock = 0;
2931 const char *display;
2932 char buf[1024], *cp;
2933 struct addrinfo hints, *ai, *aitop;
2934 char strport[NI_MAXSERV];
2937 /* Try to open a socket for the local X server. */
2938 display = getenv("DISPLAY");
2940 error("DISPLAY not set.");
2944 * Now we decode the value of the DISPLAY variable and make a
2945 * connection to the real X server.
2949 * Check if it is a unix domain socket. Unix domain displays are in
2950 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2952 if (strncmp(display, "unix:", 5) == 0 ||
2953 display[0] == ':') {
2954 /* Connect to the unix domain socket. */
2955 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2956 error("Could not parse display number from DISPLAY: %.100s",
2960 /* Create a socket. */
2961 sock = connect_local_xsocket(display_number);
2965 /* OK, we now have a connection to the display. */
2969 * Connect to an inet socket. The DISPLAY value is supposedly
2970 * hostname:d[.s], where hostname may also be numeric IP address.
2972 strlcpy(buf, display, sizeof(buf));
2973 cp = strchr(buf, ':');
2975 error("Could not find ':' in DISPLAY: %.100s", display);
2979 /* buf now contains the host name. But first we parse the display number. */
2980 if (sscanf(cp + 1, "%d", &display_number) != 1) {
2981 error("Could not parse display number from DISPLAY: %.100s",
2986 /* Look up the host address */
2987 memset(&hints, 0, sizeof(hints));
2988 hints.ai_family = IPv4or6;
2989 hints.ai_socktype = SOCK_STREAM;
2990 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2991 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2992 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2995 for (ai = aitop; ai; ai = ai->ai_next) {
2996 /* Create a socket. */
2997 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2999 debug2("socket: %.100s", strerror(errno));
3002 /* Connect it to the display. */
3003 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3004 debug2("connect %.100s port %d: %.100s", buf,
3005 6000 + display_number, strerror(errno));
3012 freeaddrinfo(aitop);
3014 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
3023 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3024 * the remote channel number. We should do whatever we want, and respond
3025 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3029 x11_input_open(int type, u_int32_t seq, void *ctxt)
3032 int remote_id, sock = 0;
3035 debug("Received X11 open request.");
3037 remote_id = packet_get_int();
3039 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3040 remote_host = packet_get_string(NULL);
3042 remote_host = xstrdup("unknown (remote did not supply name)");
3046 /* Obtain a connection to the real X display. */
3047 sock = x11_connect_display();
3049 /* Allocate a channel for this connection. */
3050 c = channel_new("connected x11 socket",
3051 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3053 c->remote_id = remote_id;
3058 /* Send refusal to the remote host. */
3059 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3060 packet_put_int(remote_id);
3062 /* Send a confirmation to the remote host. */
3063 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3064 packet_put_int(remote_id);
3065 packet_put_int(c->self);
3070 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3072 deny_input_open(int type, u_int32_t seq, void *ctxt)
3074 int rchan = packet_get_int();
3077 case SSH_SMSG_AGENT_OPEN:
3078 error("Warning: ssh server tried agent forwarding.");
3080 case SSH_SMSG_X11_OPEN:
3081 error("Warning: ssh server tried X11 forwarding.");
3084 error("deny_input_open: type %d", type);
3087 error("Warning: this is probably a break-in attempt by a malicious server.");
3088 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3089 packet_put_int(rchan);
3094 * Requests forwarding of X11 connections, generates fake authentication
3095 * data, and enables authentication spoofing.
3096 * This should be called in the client only.
3099 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3100 const char *proto, const char *data)
3102 u_int data_len = (u_int) strlen(data) / 2;
3109 if (x11_saved_display == NULL)
3110 x11_saved_display = xstrdup(disp);
3111 else if (strcmp(disp, x11_saved_display) != 0) {
3112 error("x11_request_forwarding_with_spoofing: different "
3113 "$DISPLAY already forwarded");
3119 cp = strchr(disp, ':');
3121 cp = strchr(cp, '.');
3123 screen_number = atoi(cp + 1);
3127 if (x11_saved_proto == NULL) {
3128 /* Save protocol name. */
3129 x11_saved_proto = xstrdup(proto);
3131 * Extract real authentication data and generate fake data
3132 * of the same length.
3134 x11_saved_data = xmalloc(data_len);
3135 x11_fake_data = xmalloc(data_len);
3136 for (i = 0; i < data_len; i++) {
3137 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3138 fatal("x11_request_forwarding: bad "
3139 "authentication data: %.100s", data);
3142 x11_saved_data[i] = value;
3143 x11_fake_data[i] = rnd & 0xff;
3146 x11_saved_data_len = data_len;
3147 x11_fake_data_len = data_len;
3150 /* Convert the fake data into hex. */
3151 new_data = tohex(x11_fake_data, data_len);
3153 /* Send the request packet. */
3155 channel_request_start(client_session_id, "x11-req", 0);
3156 packet_put_char(0); /* XXX bool single connection */
3158 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3160 packet_put_cstring(proto);
3161 packet_put_cstring(new_data);
3162 packet_put_int(screen_number);
3164 packet_write_wait();
3169 /* -- agent forwarding */
3171 /* Sends a message to the server to request authentication fd forwarding. */
3174 auth_request_forwarding(void)
3176 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3178 packet_write_wait();