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.195 2003/09/16 21:02:40 markus Exp $");
56 #include "pathnames.h"
62 * Pointer to an array containing all allocated channels. The array is
63 * dynamically extended as needed.
65 static Channel **channels = NULL;
68 * Size of the channel array. All slots of the array must always be
69 * initialized (at least the type field); unused slots set to NULL
71 static int channels_alloc = 0;
74 * Maximum file descriptor value used in any of the channels. This is
75 * updated in channel_new.
77 static int channel_max_fd = 0;
80 /* -- tcp forwarding */
83 * Data structure for storing which hosts are permitted for forward requests.
84 * The local sides of any remote forwards are stored in this array to prevent
85 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
86 * network (which might be behind a firewall).
89 char *host_to_connect; /* Connect to 'host'. */
90 u_short port_to_connect; /* Connect to 'port'. */
91 u_short listen_port; /* Remote side should listen port number. */
94 /* List of all permitted host/port pairs to connect. */
95 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
97 /* Number of permitted host/port pairs in the array. */
98 static int num_permitted_opens = 0;
100 * If this is true, all opens are permitted. This is the case on the server
101 * on which we have to trust the client anyway, and the user could do
102 * anything after logging in anyway.
104 static int all_opens_permitted = 0;
107 /* -- X11 forwarding */
109 /* Maximum number of fake X11 displays to try. */
110 #define MAX_DISPLAYS 1000
112 /* Saved X11 authentication protocol name. */
113 static char *x11_saved_proto = NULL;
115 /* Saved X11 authentication data. This is the real data. */
116 static char *x11_saved_data = NULL;
117 static u_int x11_saved_data_len = 0;
120 * Fake X11 authentication data. This is what the server will be sending us;
121 * we should replace any occurrences of this by the real data.
123 static char *x11_fake_data = NULL;
124 static u_int x11_fake_data_len;
127 /* -- agent forwarding */
131 /* AF_UNSPEC or AF_INET or AF_INET6 */
132 static int IPv4or6 = AF_UNSPEC;
135 static void port_open_helper(Channel *c, char *rtype);
137 /* -- channel core */
140 channel_lookup(int id)
144 if (id < 0 || id >= channels_alloc) {
145 logit("channel_lookup: %d: bad id", id);
150 logit("channel_lookup: %d: bad id: channel free", id);
157 * Register filedescriptors for a channel, used when allocating a channel or
158 * when the channel consumer/producer is ready, e.g. shell exec'd
162 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
163 int extusage, int nonblock)
165 /* Update the maximum file descriptor value. */
166 channel_max_fd = MAX(channel_max_fd, rfd);
167 channel_max_fd = MAX(channel_max_fd, wfd);
168 channel_max_fd = MAX(channel_max_fd, efd);
170 /* XXX set close-on-exec -markus */
174 c->sock = (rfd == wfd) ? rfd : -1;
176 c->extended_usage = extusage;
178 /* XXX ugly hack: nonblock is only set by the server */
179 if (nonblock && isatty(c->rfd)) {
180 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
182 if (!isatty(c->wfd)) {
183 error("channel %d: wfd %d is not a tty?",
189 c->wfd_isatty = isatty(c->wfd);
191 /* enable nonblocking mode */
203 * Allocate a new channel object and set its type and socket. This will cause
204 * remote_name to be freed.
208 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
209 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
214 /* Do initial allocation if this is the first call. */
215 if (channels_alloc == 0) {
217 channels = xmalloc(channels_alloc * sizeof(Channel *));
218 for (i = 0; i < channels_alloc; i++)
220 fatal_add_cleanup((void (*) (void *)) channel_free_all, NULL);
222 /* Try to find a free slot where to put the new channel. */
223 for (found = -1, i = 0; i < channels_alloc; i++)
224 if (channels[i] == NULL) {
225 /* Found a free slot. */
230 /* There are no free slots. Take last+1 slot and expand the array. */
231 found = channels_alloc;
232 if (channels_alloc > 10000)
233 fatal("channel_new: internal error: channels_alloc %d "
234 "too big.", channels_alloc);
235 channels = xrealloc(channels,
236 (channels_alloc + 10) * sizeof(Channel *));
237 channels_alloc += 10;
238 debug2("channel: expanding %d", channels_alloc);
239 for (i = found; i < channels_alloc; i++)
242 /* Initialize and return new channel. */
243 c = channels[found] = xmalloc(sizeof(Channel));
244 memset(c, 0, sizeof(Channel));
245 buffer_init(&c->input);
246 buffer_init(&c->output);
247 buffer_init(&c->extended);
248 c->ostate = CHAN_OUTPUT_OPEN;
249 c->istate = CHAN_INPUT_OPEN;
251 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
255 c->local_window = window;
256 c->local_window_max = window;
257 c->local_consumed = 0;
258 c->local_maxpacket = maxpack;
260 c->remote_name = xstrdup(remote_name);
261 c->remote_window = 0;
262 c->remote_maxpacket = 0;
264 c->single_connection = 0;
265 c->detach_user = NULL;
267 c->input_filter = NULL;
268 debug("channel %d: new [%s]", found, remote_name);
273 channel_find_maxfd(void)
278 for (i = 0; i < channels_alloc; i++) {
281 max = MAX(max, c->rfd);
282 max = MAX(max, c->wfd);
283 max = MAX(max, c->efd);
290 channel_close_fd(int *fdp)
292 int ret = 0, fd = *fdp;
297 if (fd == channel_max_fd)
298 channel_max_fd = channel_find_maxfd();
303 /* Close all channel fd/socket. */
306 channel_close_fds(Channel *c)
308 debug3("channel %d: close_fds r %d w %d e %d",
309 c->self, c->rfd, c->wfd, c->efd);
311 channel_close_fd(&c->sock);
312 channel_close_fd(&c->rfd);
313 channel_close_fd(&c->wfd);
314 channel_close_fd(&c->efd);
317 /* Free the channel and close its fd/socket. */
320 channel_free(Channel *c)
325 for (n = 0, i = 0; i < channels_alloc; i++)
328 debug("channel %d: free: %s, nchannels %d", c->self,
329 c->remote_name ? c->remote_name : "???", n);
331 s = channel_open_message();
332 debug3("channel %d: status: %s", c->self, s);
336 shutdown(c->sock, SHUT_RDWR);
337 channel_close_fds(c);
338 buffer_free(&c->input);
339 buffer_free(&c->output);
340 buffer_free(&c->extended);
341 if (c->remote_name) {
342 xfree(c->remote_name);
343 c->remote_name = NULL;
345 channels[c->self] = NULL;
350 channel_free_all(void)
354 for (i = 0; i < channels_alloc; i++)
355 if (channels[i] != NULL)
356 channel_free(channels[i]);
360 * Closes the sockets/fds of all channels. This is used to close extra file
361 * descriptors after a fork.
365 channel_close_all(void)
369 for (i = 0; i < channels_alloc; i++)
370 if (channels[i] != NULL)
371 channel_close_fds(channels[i]);
375 * Stop listening to channels.
379 channel_stop_listening(void)
384 for (i = 0; i < channels_alloc; i++) {
388 case SSH_CHANNEL_AUTH_SOCKET:
389 case SSH_CHANNEL_PORT_LISTENER:
390 case SSH_CHANNEL_RPORT_LISTENER:
391 case SSH_CHANNEL_X11_LISTENER:
392 channel_close_fd(&c->sock);
401 * Returns true if no channel has too much buffered data, and false if one or
402 * more channel is overfull.
406 channel_not_very_much_buffered_data(void)
411 for (i = 0; i < channels_alloc; i++) {
413 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
416 buffer_len(&c->input) > packet_get_maxsize()) {
417 debug2("channel %d: big input buffer %d",
418 c->self, buffer_len(&c->input));
422 if (buffer_len(&c->output) > packet_get_maxsize()) {
423 debug2("channel %d: big output buffer %u > %u",
424 c->self, buffer_len(&c->output),
425 packet_get_maxsize());
433 /* Returns true if any channel is still open. */
436 channel_still_open(void)
441 for (i = 0; i < channels_alloc; i++) {
446 case SSH_CHANNEL_X11_LISTENER:
447 case SSH_CHANNEL_PORT_LISTENER:
448 case SSH_CHANNEL_RPORT_LISTENER:
449 case SSH_CHANNEL_CLOSED:
450 case SSH_CHANNEL_AUTH_SOCKET:
451 case SSH_CHANNEL_DYNAMIC:
452 case SSH_CHANNEL_CONNECTING:
453 case SSH_CHANNEL_ZOMBIE:
455 case SSH_CHANNEL_LARVAL:
457 fatal("cannot happen: SSH_CHANNEL_LARVAL");
459 case SSH_CHANNEL_OPENING:
460 case SSH_CHANNEL_OPEN:
461 case SSH_CHANNEL_X11_OPEN:
463 case SSH_CHANNEL_INPUT_DRAINING:
464 case SSH_CHANNEL_OUTPUT_DRAINING:
466 fatal("cannot happen: OUT_DRAIN");
469 fatal("channel_still_open: bad channel type %d", c->type);
476 /* Returns the id of an open channel suitable for keepaliving */
479 channel_find_open(void)
484 for (i = 0; i < channels_alloc; i++) {
489 case SSH_CHANNEL_CLOSED:
490 case SSH_CHANNEL_DYNAMIC:
491 case SSH_CHANNEL_X11_LISTENER:
492 case SSH_CHANNEL_PORT_LISTENER:
493 case SSH_CHANNEL_RPORT_LISTENER:
494 case SSH_CHANNEL_OPENING:
495 case SSH_CHANNEL_CONNECTING:
496 case SSH_CHANNEL_ZOMBIE:
498 case SSH_CHANNEL_LARVAL:
499 case SSH_CHANNEL_AUTH_SOCKET:
500 case SSH_CHANNEL_OPEN:
501 case SSH_CHANNEL_X11_OPEN:
503 case SSH_CHANNEL_INPUT_DRAINING:
504 case SSH_CHANNEL_OUTPUT_DRAINING:
506 fatal("cannot happen: OUT_DRAIN");
509 fatal("channel_find_open: bad channel type %d", c->type);
518 * Returns a message describing the currently open forwarded connections,
519 * suitable for sending to the client. The message contains crlf pairs for
524 channel_open_message(void)
531 buffer_init(&buffer);
532 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
533 buffer_append(&buffer, buf, strlen(buf));
534 for (i = 0; i < channels_alloc; i++) {
539 case SSH_CHANNEL_X11_LISTENER:
540 case SSH_CHANNEL_PORT_LISTENER:
541 case SSH_CHANNEL_RPORT_LISTENER:
542 case SSH_CHANNEL_CLOSED:
543 case SSH_CHANNEL_AUTH_SOCKET:
544 case SSH_CHANNEL_ZOMBIE:
546 case SSH_CHANNEL_LARVAL:
547 case SSH_CHANNEL_OPENING:
548 case SSH_CHANNEL_CONNECTING:
549 case SSH_CHANNEL_DYNAMIC:
550 case SSH_CHANNEL_OPEN:
551 case SSH_CHANNEL_X11_OPEN:
552 case SSH_CHANNEL_INPUT_DRAINING:
553 case SSH_CHANNEL_OUTPUT_DRAINING:
554 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
555 c->self, c->remote_name,
556 c->type, c->remote_id,
557 c->istate, buffer_len(&c->input),
558 c->ostate, buffer_len(&c->output),
560 buffer_append(&buffer, buf, strlen(buf));
563 fatal("channel_open_message: bad channel type %d", c->type);
567 buffer_append(&buffer, "\0", 1);
568 cp = xstrdup(buffer_ptr(&buffer));
569 buffer_free(&buffer);
574 channel_send_open(int id)
576 Channel *c = channel_lookup(id);
579 logit("channel_send_open: %d: bad id", id);
582 debug2("channel %d: send open", id);
583 packet_start(SSH2_MSG_CHANNEL_OPEN);
584 packet_put_cstring(c->ctype);
585 packet_put_int(c->self);
586 packet_put_int(c->local_window);
587 packet_put_int(c->local_maxpacket);
592 channel_request_start(int id, char *service, int wantconfirm)
594 Channel *c = channel_lookup(id);
597 logit("channel_request_start: %d: unknown channel id", id);
600 debug2("channel %d: request %s", id, service) ;
601 packet_start(SSH2_MSG_CHANNEL_REQUEST);
602 packet_put_int(c->remote_id);
603 packet_put_cstring(service);
604 packet_put_char(wantconfirm);
607 channel_register_confirm(int id, channel_callback_fn *fn)
609 Channel *c = channel_lookup(id);
612 logit("channel_register_comfirm: %d: bad id", id);
618 channel_register_cleanup(int id, channel_callback_fn *fn)
620 Channel *c = channel_lookup(id);
623 logit("channel_register_cleanup: %d: bad id", id);
629 channel_cancel_cleanup(int id)
631 Channel *c = channel_lookup(id);
634 logit("channel_cancel_cleanup: %d: bad id", id);
637 c->detach_user = NULL;
640 channel_register_filter(int id, channel_filter_fn *fn)
642 Channel *c = channel_lookup(id);
645 logit("channel_register_filter: %d: bad id", id);
648 c->input_filter = fn;
652 channel_set_fds(int id, int rfd, int wfd, int efd,
653 int extusage, int nonblock, u_int window_max)
655 Channel *c = channel_lookup(id);
657 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
658 fatal("channel_activate for non-larval channel %d.", id);
659 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
660 c->type = SSH_CHANNEL_OPEN;
661 c->local_window = c->local_window_max = window_max;
662 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
663 packet_put_int(c->remote_id);
664 packet_put_int(c->local_window);
669 * 'channel_pre*' are called just before select() to add any bits relevant to
670 * channels in the select bitmasks.
673 * 'channel_post*': perform any appropriate operations for channels which
674 * have events pending.
676 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
677 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
678 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
681 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
683 FD_SET(c->sock, readset);
687 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
689 debug3("channel %d: waiting for connection", c->self);
690 FD_SET(c->sock, writeset);
694 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
696 if (buffer_len(&c->input) < packet_get_maxsize())
697 FD_SET(c->sock, readset);
698 if (buffer_len(&c->output) > 0)
699 FD_SET(c->sock, writeset);
703 channel_pre_open(Channel *c, fd_set * readset, fd_set * writeset)
705 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
707 if (c->istate == CHAN_INPUT_OPEN &&
709 buffer_len(&c->input) < limit)
710 FD_SET(c->rfd, readset);
711 if (c->ostate == CHAN_OUTPUT_OPEN ||
712 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
713 if (buffer_len(&c->output) > 0) {
714 FD_SET(c->wfd, writeset);
715 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
716 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
717 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
718 c->self, c->efd, buffer_len(&c->extended));
723 /** XXX check close conditions, too */
724 if (compat20 && c->efd != -1) {
725 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
726 buffer_len(&c->extended) > 0)
727 FD_SET(c->efd, writeset);
728 else if (!(c->flags & CHAN_EOF_SENT) &&
729 c->extended_usage == CHAN_EXTENDED_READ &&
730 buffer_len(&c->extended) < c->remote_window)
731 FD_SET(c->efd, readset);
736 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
738 if (buffer_len(&c->input) == 0) {
739 packet_start(SSH_MSG_CHANNEL_CLOSE);
740 packet_put_int(c->remote_id);
742 c->type = SSH_CHANNEL_CLOSED;
743 debug2("channel %d: closing after input drain.", c->self);
748 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
750 if (buffer_len(&c->output) == 0)
753 FD_SET(c->sock, writeset);
757 * This is a special state for X11 authentication spoofing. An opened X11
758 * connection (when authentication spoofing is being done) remains in this
759 * state until the first packet has been completely read. The authentication
760 * data in that packet is then substituted by the real data if it matches the
761 * fake data, and the channel is put into normal mode.
762 * XXX All this happens at the client side.
763 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
766 x11_open_helper(Buffer *b)
769 u_int proto_len, data_len;
771 /* Check if the fixed size part of the packet is in buffer. */
772 if (buffer_len(b) < 12)
775 /* Parse the lengths of variable-length fields. */
777 if (ucp[0] == 0x42) { /* Byte order MSB first. */
778 proto_len = 256 * ucp[6] + ucp[7];
779 data_len = 256 * ucp[8] + ucp[9];
780 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
781 proto_len = ucp[6] + 256 * ucp[7];
782 data_len = ucp[8] + 256 * ucp[9];
784 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
789 /* Check if the whole packet is in buffer. */
791 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
794 /* Check if authentication protocol matches. */
795 if (proto_len != strlen(x11_saved_proto) ||
796 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
797 debug2("X11 connection uses different authentication protocol.");
800 /* Check if authentication data matches our fake data. */
801 if (data_len != x11_fake_data_len ||
802 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
803 x11_fake_data, x11_fake_data_len) != 0) {
804 debug2("X11 auth data does not match fake data.");
807 /* Check fake data length */
808 if (x11_fake_data_len != x11_saved_data_len) {
809 error("X11 fake_data_len %d != saved_data_len %d",
810 x11_fake_data_len, x11_saved_data_len);
814 * Received authentication protocol and data match
815 * our fake data. Substitute the fake data with real
818 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
819 x11_saved_data, x11_saved_data_len);
824 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
826 int ret = x11_open_helper(&c->output);
829 /* Start normal processing for the channel. */
830 c->type = SSH_CHANNEL_OPEN;
831 channel_pre_open_13(c, readset, writeset);
832 } else if (ret == -1) {
834 * We have received an X11 connection that has bad
835 * authentication information.
837 logit("X11 connection rejected because of wrong authentication.");
838 buffer_clear(&c->input);
839 buffer_clear(&c->output);
840 channel_close_fd(&c->sock);
842 c->type = SSH_CHANNEL_CLOSED;
843 packet_start(SSH_MSG_CHANNEL_CLOSE);
844 packet_put_int(c->remote_id);
850 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
852 int ret = x11_open_helper(&c->output);
854 /* c->force_drain = 1; */
857 c->type = SSH_CHANNEL_OPEN;
858 channel_pre_open(c, readset, writeset);
859 } else if (ret == -1) {
860 logit("X11 connection rejected because of wrong authentication.");
861 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
863 buffer_clear(&c->input);
865 buffer_clear(&c->output);
866 /* for proto v1, the peer will send an IEOF */
868 chan_write_failed(c);
870 c->type = SSH_CHANNEL_OPEN;
871 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
875 /* try to decode a socks4 header */
877 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
880 int len, have, i, found;
886 struct in_addr dest_addr;
889 debug2("channel %d: decode socks4", c->self);
891 have = buffer_len(&c->input);
892 len = sizeof(s4_req);
895 p = buffer_ptr(&c->input);
896 for (found = 0, i = len; i < have; i++) {
902 /* the peer is probably sending garbage */
903 debug("channel %d: decode socks4: too long",
910 buffer_get(&c->input, (char *)&s4_req.version, 1);
911 buffer_get(&c->input, (char *)&s4_req.command, 1);
912 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
913 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
914 have = buffer_len(&c->input);
915 p = buffer_ptr(&c->input);
917 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
919 fatal("channel %d: decode socks4: len %d > have %d",
921 strlcpy(username, p, sizeof(username));
922 buffer_consume(&c->input, len);
923 buffer_consume(&c->input, 1); /* trailing '\0' */
925 host = inet_ntoa(s4_req.dest_addr);
926 strlcpy(c->path, host, sizeof(c->path));
927 c->host_port = ntohs(s4_req.dest_port);
929 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
930 c->self, host, c->host_port, s4_req.command);
932 if (s4_req.command != 1) {
933 debug("channel %d: cannot handle: socks4 cn %d",
934 c->self, s4_req.command);
937 s4_rsp.version = 0; /* vn: 0 for reply */
938 s4_rsp.command = 90; /* cd: req granted */
939 s4_rsp.dest_port = 0; /* ignored */
940 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
941 buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
945 /* try to decode a socks5 header */
946 #define SSH_SOCKS5_AUTHDONE 0x1000
947 #define SSH_SOCKS5_NOAUTH 0x00
948 #define SSH_SOCKS5_IPV4 0x01
949 #define SSH_SOCKS5_DOMAIN 0x03
950 #define SSH_SOCKS5_IPV6 0x04
951 #define SSH_SOCKS5_CONNECT 0x01
952 #define SSH_SOCKS5_SUCCESS 0x00
955 channel_decode_socks5(Channel *c, fd_set * readset, fd_set * writeset)
964 u_char *p, dest_addr[255+1];
965 int i, have, found, nmethods, addrlen, af;
967 debug2("channel %d: decode socks5", c->self);
968 p = buffer_ptr(&c->input);
971 have = buffer_len(&c->input);
972 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
973 /* format: ver | nmethods | methods */
977 if (have < nmethods + 2)
979 /* look for method: "NO AUTHENTICATION REQUIRED" */
980 for (found = 0, i = 2 ; i < nmethods + 2; i++) {
981 if (p[i] == SSH_SOCKS5_NOAUTH ) {
987 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
991 buffer_consume(&c->input, nmethods + 2);
992 buffer_put_char(&c->output, 0x05); /* version */
993 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
994 FD_SET(c->sock, writeset);
995 c->flags |= SSH_SOCKS5_AUTHDONE;
996 debug2("channel %d: socks5 auth done", c->self);
997 return 0; /* need more */
999 debug2("channel %d: socks5 post auth", c->self);
1000 if (have < sizeof(s5_req)+1)
1001 return 0; /* need more */
1002 memcpy((char *)&s5_req, p, sizeof(s5_req));
1003 if (s5_req.version != 0x05 ||
1004 s5_req.command != SSH_SOCKS5_CONNECT ||
1005 s5_req.reserved != 0x00) {
1006 debug2("channel %d: only socks5 connect supported", c->self);
1009 switch(s5_req.atyp){
1010 case SSH_SOCKS5_IPV4:
1014 case SSH_SOCKS5_DOMAIN:
1015 addrlen = p[sizeof(s5_req)];
1018 case SSH_SOCKS5_IPV6:
1023 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1026 if (have < 4 + addrlen + 2)
1028 buffer_consume(&c->input, sizeof(s5_req));
1029 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1030 buffer_consume(&c->input, 1); /* host string length */
1031 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1032 buffer_get(&c->input, (char *)&dest_port, 2);
1033 dest_addr[addrlen] = '\0';
1034 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1035 strlcpy(c->path, dest_addr, sizeof(c->path));
1036 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1038 c->host_port = ntohs(dest_port);
1040 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1041 c->self, c->path, c->host_port, s5_req.command);
1043 s5_rsp.version = 0x05;
1044 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1045 s5_rsp.reserved = 0; /* ignored */
1046 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1047 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1048 dest_port = 0; /* ignored */
1050 buffer_append(&c->output, (char *)&s5_rsp, sizeof(s5_rsp));
1051 buffer_append(&c->output, (char *)&dest_addr, sizeof(struct in_addr));
1052 buffer_append(&c->output, (char *)&dest_port, sizeof(dest_port));
1056 /* dynamic port forwarding */
1058 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
1063 have = buffer_len(&c->input);
1065 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1066 /* buffer_dump(&c->input); */
1067 /* check if the fixed size part of the packet is in buffer. */
1070 FD_SET(c->sock, readset);
1073 /* try to guess the protocol */
1074 p = buffer_ptr(&c->input);
1077 ret = channel_decode_socks4(c, readset, writeset);
1080 ret = channel_decode_socks5(c, readset, writeset);
1088 } else if (ret == 0) {
1089 debug2("channel %d: pre_dynamic: need more", c->self);
1091 FD_SET(c->sock, readset);
1093 /* switch to the next state */
1094 c->type = SSH_CHANNEL_OPENING;
1095 port_open_helper(c, "direct-tcpip");
1099 /* This is our fake X11 server socket. */
1101 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
1104 struct sockaddr addr;
1107 char buf[16384], *remote_ipaddr;
1110 if (FD_ISSET(c->sock, readset)) {
1111 debug("X11 connection requested.");
1112 addrlen = sizeof(addr);
1113 newsock = accept(c->sock, &addr, &addrlen);
1114 if (c->single_connection) {
1115 debug2("single_connection: closing X11 listener.");
1116 channel_close_fd(&c->sock);
1120 error("accept: %.100s", strerror(errno));
1123 set_nodelay(newsock);
1124 remote_ipaddr = get_peer_ipaddr(newsock);
1125 remote_port = get_peer_port(newsock);
1126 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1127 remote_ipaddr, remote_port);
1129 nc = channel_new("accepted x11 socket",
1130 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1131 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1133 packet_start(SSH2_MSG_CHANNEL_OPEN);
1134 packet_put_cstring("x11");
1135 packet_put_int(nc->self);
1136 packet_put_int(nc->local_window_max);
1137 packet_put_int(nc->local_maxpacket);
1138 /* originator ipaddr and port */
1139 packet_put_cstring(remote_ipaddr);
1140 if (datafellows & SSH_BUG_X11FWD) {
1141 debug2("ssh2 x11 bug compat mode");
1143 packet_put_int(remote_port);
1147 packet_start(SSH_SMSG_X11_OPEN);
1148 packet_put_int(nc->self);
1149 if (packet_get_protocol_flags() &
1150 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1151 packet_put_cstring(buf);
1154 xfree(remote_ipaddr);
1159 port_open_helper(Channel *c, char *rtype)
1163 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1164 u_short remote_port = get_peer_port(c->sock);
1166 direct = (strcmp(rtype, "direct-tcpip") == 0);
1168 snprintf(buf, sizeof buf,
1169 "%s: listening port %d for %.100s port %d, "
1170 "connect from %.200s port %d",
1171 rtype, c->listening_port, c->path, c->host_port,
1172 remote_ipaddr, remote_port);
1174 xfree(c->remote_name);
1175 c->remote_name = xstrdup(buf);
1178 packet_start(SSH2_MSG_CHANNEL_OPEN);
1179 packet_put_cstring(rtype);
1180 packet_put_int(c->self);
1181 packet_put_int(c->local_window_max);
1182 packet_put_int(c->local_maxpacket);
1184 /* target host, port */
1185 packet_put_cstring(c->path);
1186 packet_put_int(c->host_port);
1188 /* listen address, port */
1189 packet_put_cstring(c->path);
1190 packet_put_int(c->listening_port);
1192 /* originator host and port */
1193 packet_put_cstring(remote_ipaddr);
1194 packet_put_int(remote_port);
1197 packet_start(SSH_MSG_PORT_OPEN);
1198 packet_put_int(c->self);
1199 packet_put_cstring(c->path);
1200 packet_put_int(c->host_port);
1201 if (packet_get_protocol_flags() &
1202 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1203 packet_put_cstring(c->remote_name);
1206 xfree(remote_ipaddr);
1210 * This socket is listening for connections to a forwarded TCP/IP port.
1213 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
1216 struct sockaddr addr;
1217 int newsock, nextstate;
1221 if (FD_ISSET(c->sock, readset)) {
1222 debug("Connection to port %d forwarding "
1223 "to %.100s port %d requested.",
1224 c->listening_port, c->path, c->host_port);
1226 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1227 nextstate = SSH_CHANNEL_OPENING;
1228 rtype = "forwarded-tcpip";
1230 if (c->host_port == 0) {
1231 nextstate = SSH_CHANNEL_DYNAMIC;
1232 rtype = "dynamic-tcpip";
1234 nextstate = SSH_CHANNEL_OPENING;
1235 rtype = "direct-tcpip";
1239 addrlen = sizeof(addr);
1240 newsock = accept(c->sock, &addr, &addrlen);
1242 error("accept: %.100s", strerror(errno));
1245 set_nodelay(newsock);
1246 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1247 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1248 nc->listening_port = c->listening_port;
1249 nc->host_port = c->host_port;
1250 strlcpy(nc->path, c->path, sizeof(nc->path));
1252 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1254 * do not call the channel_post handler until
1255 * this flag has been reset by a pre-handler.
1256 * otherwise the FD_ISSET calls might overflow
1260 port_open_helper(nc, rtype);
1266 * This is the authentication agent socket listening for connections from
1270 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
1274 struct sockaddr addr;
1277 if (FD_ISSET(c->sock, readset)) {
1278 addrlen = sizeof(addr);
1279 newsock = accept(c->sock, &addr, &addrlen);
1281 error("accept from auth socket: %.100s", strerror(errno));
1284 nc = channel_new("accepted auth socket",
1285 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1286 c->local_window_max, c->local_maxpacket,
1287 0, "accepted auth socket", 1);
1289 packet_start(SSH2_MSG_CHANNEL_OPEN);
1290 packet_put_cstring("auth-agent@openssh.com");
1291 packet_put_int(nc->self);
1292 packet_put_int(c->local_window_max);
1293 packet_put_int(c->local_maxpacket);
1295 packet_start(SSH_SMSG_AGENT_OPEN);
1296 packet_put_int(nc->self);
1303 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
1306 socklen_t sz = sizeof(err);
1308 if (FD_ISSET(c->sock, writeset)) {
1309 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1311 error("getsockopt SO_ERROR failed");
1314 debug("channel %d: connected", c->self);
1315 c->type = SSH_CHANNEL_OPEN;
1317 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1318 packet_put_int(c->remote_id);
1319 packet_put_int(c->self);
1320 packet_put_int(c->local_window);
1321 packet_put_int(c->local_maxpacket);
1323 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1324 packet_put_int(c->remote_id);
1325 packet_put_int(c->self);
1328 debug("channel %d: not connected: %s",
1329 c->self, strerror(err));
1331 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1332 packet_put_int(c->remote_id);
1333 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1334 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1335 packet_put_cstring(strerror(err));
1336 packet_put_cstring("");
1339 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1340 packet_put_int(c->remote_id);
1349 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
1355 FD_ISSET(c->rfd, readset)) {
1356 len = read(c->rfd, buf, sizeof(buf));
1357 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1360 debug2("channel %d: read<=0 rfd %d len %d",
1361 c->self, c->rfd, len);
1362 if (c->type != SSH_CHANNEL_OPEN) {
1363 debug2("channel %d: not open", c->self);
1366 } else if (compat13) {
1367 buffer_clear(&c->output);
1368 c->type = SSH_CHANNEL_INPUT_DRAINING;
1369 debug2("channel %d: input draining.", c->self);
1371 chan_read_failed(c);
1375 if (c->input_filter != NULL) {
1376 if (c->input_filter(c, buf, len) == -1) {
1377 debug2("channel %d: filter stops", c->self);
1378 chan_read_failed(c);
1381 buffer_append(&c->input, buf, len);
1387 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
1394 /* Send buffered output data to the socket. */
1396 FD_ISSET(c->wfd, writeset) &&
1397 buffer_len(&c->output) > 0) {
1398 data = buffer_ptr(&c->output);
1399 dlen = buffer_len(&c->output);
1401 /* XXX: Later AIX versions can't push as much data to tty */
1402 if (compat20 && c->wfd_isatty && dlen > 8*1024)
1405 len = write(c->wfd, data, dlen);
1406 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1409 if (c->type != SSH_CHANNEL_OPEN) {
1410 debug2("channel %d: not open", c->self);
1413 } else if (compat13) {
1414 buffer_clear(&c->output);
1415 debug2("channel %d: input draining.", c->self);
1416 c->type = SSH_CHANNEL_INPUT_DRAINING;
1418 chan_write_failed(c);
1422 if (compat20 && c->isatty && dlen >= 1 && data[0] != '\r') {
1423 if (tcgetattr(c->wfd, &tio) == 0 &&
1424 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1426 * Simulate echo to reduce the impact of
1427 * traffic analysis. We need to match the
1428 * size of a SSH2_MSG_CHANNEL_DATA message
1429 * (4 byte channel id + data)
1431 packet_send_ignore(4 + len);
1435 buffer_consume(&c->output, len);
1436 if (compat20 && len > 0) {
1437 c->local_consumed += len;
1443 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
1448 /** XXX handle drain efd, too */
1450 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1451 FD_ISSET(c->efd, writeset) &&
1452 buffer_len(&c->extended) > 0) {
1453 len = write(c->efd, buffer_ptr(&c->extended),
1454 buffer_len(&c->extended));
1455 debug2("channel %d: written %d to efd %d",
1456 c->self, len, c->efd);
1457 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1460 debug2("channel %d: closing write-efd %d",
1462 channel_close_fd(&c->efd);
1464 buffer_consume(&c->extended, len);
1465 c->local_consumed += len;
1467 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1468 FD_ISSET(c->efd, readset)) {
1469 len = read(c->efd, buf, sizeof(buf));
1470 debug2("channel %d: read %d from efd %d",
1471 c->self, len, c->efd);
1472 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1475 debug2("channel %d: closing read-efd %d",
1477 channel_close_fd(&c->efd);
1479 buffer_append(&c->extended, buf, len);
1486 channel_check_window(Channel *c)
1488 if (c->type == SSH_CHANNEL_OPEN &&
1489 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1490 c->local_window < c->local_window_max/2 &&
1491 c->local_consumed > 0) {
1492 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1493 packet_put_int(c->remote_id);
1494 packet_put_int(c->local_consumed);
1496 debug2("channel %d: window %d sent adjust %d",
1497 c->self, c->local_window,
1499 c->local_window += c->local_consumed;
1500 c->local_consumed = 0;
1506 channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1510 channel_handle_rfd(c, readset, writeset);
1511 channel_handle_wfd(c, readset, writeset);
1514 channel_handle_efd(c, readset, writeset);
1515 channel_check_window(c);
1519 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1523 /* Send buffered output data to the socket. */
1524 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1525 len = write(c->sock, buffer_ptr(&c->output),
1526 buffer_len(&c->output));
1528 buffer_clear(&c->output);
1530 buffer_consume(&c->output, len);
1535 channel_handler_init_20(void)
1537 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1538 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1539 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1540 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1541 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1542 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1543 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1544 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1546 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1547 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1548 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1549 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1550 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1551 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1552 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1556 channel_handler_init_13(void)
1558 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1559 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1560 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1561 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1562 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1563 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1564 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1565 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1566 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1568 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1569 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1570 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1571 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1572 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1573 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1574 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1578 channel_handler_init_15(void)
1580 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1581 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1582 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1583 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1584 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1585 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1586 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1588 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1589 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1590 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1591 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1592 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1593 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1597 channel_handler_init(void)
1601 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1602 channel_pre[i] = NULL;
1603 channel_post[i] = NULL;
1606 channel_handler_init_20();
1608 channel_handler_init_13();
1610 channel_handler_init_15();
1613 /* gc dead channels */
1615 channel_garbage_collect(Channel *c)
1619 if (c->detach_user != NULL) {
1620 if (!chan_is_dead(c, 0))
1622 debug2("channel %d: gc: notify user", c->self);
1623 c->detach_user(c->self, NULL);
1624 /* if we still have a callback */
1625 if (c->detach_user != NULL)
1627 debug2("channel %d: gc: user detached", c->self);
1629 if (!chan_is_dead(c, 1))
1631 debug2("channel %d: garbage collecting", c->self);
1636 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1638 static int did_init = 0;
1643 channel_handler_init();
1646 for (i = 0; i < channels_alloc; i++) {
1650 if (ftab[c->type] != NULL)
1651 (*ftab[c->type])(c, readset, writeset);
1652 channel_garbage_collect(c);
1657 * Allocate/update select bitmasks and add any bits relevant to channels in
1661 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1662 int *nallocp, int rekeying)
1667 n = MAX(*maxfdp, channel_max_fd);
1669 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1670 /* perhaps check sz < nalloc/2 and shrink? */
1671 if (*readsetp == NULL || sz > *nallocp) {
1672 *readsetp = xrealloc(*readsetp, sz);
1673 *writesetp = xrealloc(*writesetp, sz);
1677 memset(*readsetp, 0, sz);
1678 memset(*writesetp, 0, sz);
1681 channel_handler(channel_pre, *readsetp, *writesetp);
1685 * After select, perform any appropriate operations for channels which have
1689 channel_after_select(fd_set * readset, fd_set * writeset)
1691 channel_handler(channel_post, readset, writeset);
1695 /* If there is data to send to the connection, enqueue some of it now. */
1698 channel_output_poll(void)
1704 for (i = 0; i < channels_alloc; i++) {
1710 * We are only interested in channels that can have buffered
1714 if (c->type != SSH_CHANNEL_OPEN &&
1715 c->type != SSH_CHANNEL_INPUT_DRAINING)
1718 if (c->type != SSH_CHANNEL_OPEN)
1722 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1723 /* XXX is this true? */
1724 debug3("channel %d: will not send data after close", c->self);
1728 /* Get the amount of buffered data for this channel. */
1729 if ((c->istate == CHAN_INPUT_OPEN ||
1730 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1731 (len = buffer_len(&c->input)) > 0) {
1733 * Send some data for the other side over the secure
1737 if (len > c->remote_window)
1738 len = c->remote_window;
1739 if (len > c->remote_maxpacket)
1740 len = c->remote_maxpacket;
1742 if (packet_is_interactive()) {
1746 /* Keep the packets at reasonable size. */
1747 if (len > packet_get_maxsize()/2)
1748 len = packet_get_maxsize()/2;
1752 packet_start(compat20 ?
1753 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1754 packet_put_int(c->remote_id);
1755 packet_put_string(buffer_ptr(&c->input), len);
1757 buffer_consume(&c->input, len);
1758 c->remote_window -= len;
1760 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1762 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1764 * input-buffer is empty and read-socket shutdown:
1765 * tell peer, that we will not send more data: send IEOF.
1766 * hack for extended data: delay EOF if EFD still in use.
1768 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1769 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1770 c->self, c->efd, buffer_len(&c->extended));
1774 /* Send extended data, i.e. stderr */
1776 !(c->flags & CHAN_EOF_SENT) &&
1777 c->remote_window > 0 &&
1778 (len = buffer_len(&c->extended)) > 0 &&
1779 c->extended_usage == CHAN_EXTENDED_READ) {
1780 debug2("channel %d: rwin %u elen %u euse %d",
1781 c->self, c->remote_window, buffer_len(&c->extended),
1783 if (len > c->remote_window)
1784 len = c->remote_window;
1785 if (len > c->remote_maxpacket)
1786 len = c->remote_maxpacket;
1787 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1788 packet_put_int(c->remote_id);
1789 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1790 packet_put_string(buffer_ptr(&c->extended), len);
1792 buffer_consume(&c->extended, len);
1793 c->remote_window -= len;
1794 debug2("channel %d: sent ext data %d", c->self, len);
1800 /* -- protocol input */
1803 channel_input_data(int type, u_int32_t seq, void *ctxt)
1810 /* Get the channel number and verify it. */
1811 id = packet_get_int();
1812 c = channel_lookup(id);
1814 packet_disconnect("Received data for nonexistent channel %d.", id);
1816 /* Ignore any data for non-open channels (might happen on close) */
1817 if (c->type != SSH_CHANNEL_OPEN &&
1818 c->type != SSH_CHANNEL_X11_OPEN)
1821 /* same for protocol 1.5 if output end is no longer open */
1822 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1826 data = packet_get_string(&data_len);
1829 if (data_len > c->local_maxpacket) {
1830 logit("channel %d: rcvd big packet %d, maxpack %d",
1831 c->self, data_len, c->local_maxpacket);
1833 if (data_len > c->local_window) {
1834 logit("channel %d: rcvd too much data %d, win %d",
1835 c->self, data_len, c->local_window);
1839 c->local_window -= data_len;
1842 buffer_append(&c->output, data, data_len);
1847 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1851 u_int data_len, tcode;
1854 /* Get the channel number and verify it. */
1855 id = packet_get_int();
1856 c = channel_lookup(id);
1859 packet_disconnect("Received extended_data for bad channel %d.", id);
1860 if (c->type != SSH_CHANNEL_OPEN) {
1861 logit("channel %d: ext data for non open", id);
1864 if (c->flags & CHAN_EOF_RCVD) {
1865 if (datafellows & SSH_BUG_EXTEOF)
1866 debug("channel %d: accepting ext data after eof", id);
1868 packet_disconnect("Received extended_data after EOF "
1869 "on channel %d.", id);
1871 tcode = packet_get_int();
1873 c->extended_usage != CHAN_EXTENDED_WRITE ||
1874 tcode != SSH2_EXTENDED_DATA_STDERR) {
1875 logit("channel %d: bad ext data", c->self);
1878 data = packet_get_string(&data_len);
1880 if (data_len > c->local_window) {
1881 logit("channel %d: rcvd too much extended_data %d, win %d",
1882 c->self, data_len, c->local_window);
1886 debug2("channel %d: rcvd ext data %d", c->self, data_len);
1887 c->local_window -= data_len;
1888 buffer_append(&c->extended, data, data_len);
1893 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1898 id = packet_get_int();
1900 c = channel_lookup(id);
1902 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1905 /* XXX force input close */
1906 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1907 debug("channel %d: FORCE input drain", c->self);
1908 c->istate = CHAN_INPUT_WAIT_DRAIN;
1909 if (buffer_len(&c->input) == 0)
1916 channel_input_close(int type, u_int32_t seq, void *ctxt)
1921 id = packet_get_int();
1923 c = channel_lookup(id);
1925 packet_disconnect("Received close for nonexistent channel %d.", id);
1928 * Send a confirmation that we have closed the channel and no more
1929 * data is coming for it.
1931 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1932 packet_put_int(c->remote_id);
1936 * If the channel is in closed state, we have sent a close request,
1937 * and the other side will eventually respond with a confirmation.
1938 * Thus, we cannot free the channel here, because then there would be
1939 * no-one to receive the confirmation. The channel gets freed when
1940 * the confirmation arrives.
1942 if (c->type != SSH_CHANNEL_CLOSED) {
1944 * Not a closed channel - mark it as draining, which will
1945 * cause it to be freed later.
1947 buffer_clear(&c->input);
1948 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1952 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1954 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1956 int id = packet_get_int();
1957 Channel *c = channel_lookup(id);
1961 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1962 chan_rcvd_oclose(c);
1966 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
1968 int id = packet_get_int();
1969 Channel *c = channel_lookup(id);
1973 packet_disconnect("Received close confirmation for "
1974 "out-of-range channel %d.", id);
1975 if (c->type != SSH_CHANNEL_CLOSED)
1976 packet_disconnect("Received close confirmation for "
1977 "non-closed channel %d (type %d).", id, c->type);
1982 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
1987 id = packet_get_int();
1988 c = channel_lookup(id);
1990 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1991 packet_disconnect("Received open confirmation for "
1992 "non-opening channel %d.", id);
1993 remote_id = packet_get_int();
1994 /* Record the remote channel number and mark that the channel is now open. */
1995 c->remote_id = remote_id;
1996 c->type = SSH_CHANNEL_OPEN;
1999 c->remote_window = packet_get_int();
2000 c->remote_maxpacket = packet_get_int();
2002 debug2("callback start");
2003 c->confirm(c->self, NULL);
2004 debug2("callback done");
2006 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2007 c->remote_window, c->remote_maxpacket);
2013 reason2txt(int reason)
2016 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2017 return "administratively prohibited";
2018 case SSH2_OPEN_CONNECT_FAILED:
2019 return "connect failed";
2020 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2021 return "unknown channel type";
2022 case SSH2_OPEN_RESOURCE_SHORTAGE:
2023 return "resource shortage";
2025 return "unknown reason";
2029 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2032 char *msg = NULL, *lang = NULL;
2035 id = packet_get_int();
2036 c = channel_lookup(id);
2038 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2039 packet_disconnect("Received open failure for "
2040 "non-opening channel %d.", id);
2042 reason = packet_get_int();
2043 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2044 msg = packet_get_string(NULL);
2045 lang = packet_get_string(NULL);
2047 logit("channel %d: open failed: %s%s%s", id,
2048 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2055 /* Free the channel. This will also close the socket. */
2060 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2069 /* Get the channel number and verify it. */
2070 id = packet_get_int();
2071 c = channel_lookup(id);
2073 if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
2074 logit("Received window adjust for "
2075 "non-open channel %d.", id);
2078 adjust = packet_get_int();
2080 debug2("channel %d: rcvd adjust %u", id, adjust);
2081 c->remote_window += adjust;
2085 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2089 char *host, *originator_string;
2090 int remote_id, sock = -1;
2092 remote_id = packet_get_int();
2093 host = packet_get_string(NULL);
2094 host_port = packet_get_int();
2096 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2097 originator_string = packet_get_string(NULL);
2099 originator_string = xstrdup("unknown (remote did not supply name)");
2102 sock = channel_connect_to(host, host_port);
2104 c = channel_new("connected socket",
2105 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2106 originator_string, 1);
2107 c->remote_id = remote_id;
2109 xfree(originator_string);
2111 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2112 packet_put_int(remote_id);
2119 /* -- tcp forwarding */
2122 channel_set_af(int af)
2128 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2129 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2132 int success, sock, on = 1;
2133 struct addrinfo hints, *ai, *aitop;
2135 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2138 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2139 listen_addr : host_to_connect;
2142 error("No forward host name.");
2145 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2146 error("Forward host name too long.");
2151 * getaddrinfo returns a loopback address if the hostname is
2152 * set to NULL and hints.ai_flags is not AI_PASSIVE
2154 memset(&hints, 0, sizeof(hints));
2155 hints.ai_family = IPv4or6;
2156 hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
2157 hints.ai_socktype = SOCK_STREAM;
2158 snprintf(strport, sizeof strport, "%d", listen_port);
2159 if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
2160 packet_disconnect("getaddrinfo: fatal error");
2162 for (ai = aitop; ai; ai = ai->ai_next) {
2163 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2165 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2166 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2167 error("channel_setup_fwd_listener: getnameinfo failed");
2170 /* Create a port to listen for the host. */
2171 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2173 /* this is no error since kernel may not support ipv6 */
2174 verbose("socket: %.100s", strerror(errno));
2178 * Set socket options.
2179 * Allow local port reuse in TIME_WAIT.
2181 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
2183 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
2185 debug("Local forwarding listening on %s port %s.", ntop, strport);
2187 /* Bind the socket to the address. */
2188 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2189 /* address can be in use ipv6 address is already bound */
2191 error("bind: %.100s", strerror(errno));
2193 verbose("bind: %.100s", strerror(errno));
2198 /* Start listening for connections on the socket. */
2199 if (listen(sock, 5) < 0) {
2200 error("listen: %.100s", strerror(errno));
2204 /* Allocate a channel number for the socket. */
2205 c = channel_new("port listener", type, sock, sock, -1,
2206 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2207 0, "port listener", 1);
2208 strlcpy(c->path, host, sizeof(c->path));
2209 c->host_port = port_to_connect;
2210 c->listening_port = listen_port;
2214 error("channel_setup_fwd_listener: cannot listen to port: %d",
2216 freeaddrinfo(aitop);
2220 /* protocol local port fwd, used by ssh (and sshd in v1) */
2222 channel_setup_local_fwd_listener(u_short listen_port,
2223 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2225 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2226 NULL, listen_port, host_to_connect, port_to_connect, gateway_ports);
2229 /* protocol v2 remote port fwd, used by sshd */
2231 channel_setup_remote_fwd_listener(const char *listen_address,
2232 u_short listen_port, int gateway_ports)
2234 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2235 listen_address, listen_port, NULL, 0, gateway_ports);
2239 * Initiate forwarding of connections to port "port" on remote host through
2240 * the secure channel to host:port from local side.
2244 channel_request_remote_forwarding(u_short listen_port,
2245 const char *host_to_connect, u_short port_to_connect)
2247 int type, success = 0;
2249 /* Record locally that connection to this host/port is permitted. */
2250 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2251 fatal("channel_request_remote_forwarding: too many forwards");
2253 /* Send the forward request to the remote side. */
2255 const char *address_to_bind = "0.0.0.0";
2256 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2257 packet_put_cstring("tcpip-forward");
2258 packet_put_char(1); /* boolean: want reply */
2259 packet_put_cstring(address_to_bind);
2260 packet_put_int(listen_port);
2262 packet_write_wait();
2263 /* Assume that server accepts the request */
2266 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2267 packet_put_int(listen_port);
2268 packet_put_cstring(host_to_connect);
2269 packet_put_int(port_to_connect);
2271 packet_write_wait();
2273 /* Wait for response from the remote side. */
2274 type = packet_read();
2276 case SSH_SMSG_SUCCESS:
2279 case SSH_SMSG_FAILURE:
2280 logit("Warning: Server denied remote port forwarding.");
2283 /* Unknown packet */
2284 packet_disconnect("Protocol error for port forward request:"
2285 "received packet type %d.", type);
2289 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2290 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2291 permitted_opens[num_permitted_opens].listen_port = listen_port;
2292 num_permitted_opens++;
2297 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2298 * listening for the port, and sends back a success reply (or disconnect
2299 * message if there was an error). This never returns if there was an error.
2303 channel_input_port_forward_request(int is_root, int gateway_ports)
2305 u_short port, host_port;
2308 /* Get arguments from the packet. */
2309 port = packet_get_int();
2310 hostname = packet_get_string(NULL);
2311 host_port = packet_get_int();
2315 * Check that an unprivileged user is not trying to forward a
2318 if (port < IPPORT_RESERVED && !is_root)
2320 "Requested forwarding of port %d but user is not root.",
2323 packet_disconnect("Dynamic forwarding denied.");
2326 /* Initiate forwarding */
2327 channel_setup_local_fwd_listener(port, hostname, host_port, gateway_ports);
2329 /* Free the argument string. */
2334 * Permits opening to any host/port if permitted_opens[] is empty. This is
2335 * usually called by the server, because the user could connect to any port
2336 * anyway, and the server has no way to know but to trust the client anyway.
2339 channel_permit_all_opens(void)
2341 if (num_permitted_opens == 0)
2342 all_opens_permitted = 1;
2346 channel_add_permitted_opens(char *host, int port)
2348 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2349 fatal("channel_request_remote_forwarding: too many forwards");
2350 debug("allow port forwarding to host %s port %d", host, port);
2352 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2353 permitted_opens[num_permitted_opens].port_to_connect = port;
2354 num_permitted_opens++;
2356 all_opens_permitted = 0;
2360 channel_clear_permitted_opens(void)
2364 for (i = 0; i < num_permitted_opens; i++)
2365 xfree(permitted_opens[i].host_to_connect);
2366 num_permitted_opens = 0;
2371 /* return socket to remote host, port */
2373 connect_to(const char *host, u_short port)
2375 struct addrinfo hints, *ai, *aitop;
2376 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2380 memset(&hints, 0, sizeof(hints));
2381 hints.ai_family = IPv4or6;
2382 hints.ai_socktype = SOCK_STREAM;
2383 snprintf(strport, sizeof strport, "%d", port);
2384 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2385 error("connect_to %.100s: unknown host (%s)", host,
2386 gai_strerror(gaierr));
2389 for (ai = aitop; ai; ai = ai->ai_next) {
2390 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2392 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2393 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2394 error("connect_to: getnameinfo failed");
2397 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2399 if (ai->ai_next == NULL)
2400 error("socket: %.100s", strerror(errno));
2402 verbose("socket: %.100s", strerror(errno));
2405 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2406 fatal("connect_to: F_SETFL: %s", strerror(errno));
2407 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2408 errno != EINPROGRESS) {
2409 error("connect_to %.100s port %s: %.100s", ntop, strport,
2412 continue; /* fail -- try next */
2414 break; /* success */
2417 freeaddrinfo(aitop);
2419 error("connect_to %.100s port %d: failed.", host, port);
2428 channel_connect_by_listen_address(u_short listen_port)
2432 for (i = 0; i < num_permitted_opens; i++)
2433 if (permitted_opens[i].listen_port == listen_port)
2435 permitted_opens[i].host_to_connect,
2436 permitted_opens[i].port_to_connect);
2437 error("WARNING: Server requests forwarding for unknown listen_port %d",
2442 /* Check if connecting to that port is permitted and connect. */
2444 channel_connect_to(const char *host, u_short port)
2448 permit = all_opens_permitted;
2450 for (i = 0; i < num_permitted_opens; i++)
2451 if (permitted_opens[i].port_to_connect == port &&
2452 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2457 logit("Received request to connect to host %.100s port %d, "
2458 "but the request was denied.", host, port);
2461 return connect_to(host, port);
2464 /* -- X11 forwarding */
2467 * Creates an internet domain socket for listening for X11 connections.
2468 * Returns 0 and a suitable display number for the DISPLAY variable
2469 * stored in display_numberp , or -1 if an error occurs.
2472 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2473 int single_connection, u_int *display_numberp)
2476 int display_number, sock;
2478 struct addrinfo hints, *ai, *aitop;
2479 char strport[NI_MAXSERV];
2480 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2482 for (display_number = x11_display_offset;
2483 display_number < MAX_DISPLAYS;
2485 port = 6000 + display_number;
2486 memset(&hints, 0, sizeof(hints));
2487 hints.ai_family = IPv4or6;
2488 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2489 hints.ai_socktype = SOCK_STREAM;
2490 snprintf(strport, sizeof strport, "%d", port);
2491 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2492 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2495 for (ai = aitop; ai; ai = ai->ai_next) {
2496 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2498 sock = socket(ai->ai_family, ai->ai_socktype,
2501 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2502 error("socket: %.100s", strerror(errno));
2505 debug("x11_create_display_inet: Socket family %d not supported",
2511 if (ai->ai_family == AF_INET6) {
2513 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2514 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2517 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2518 debug2("bind port %d: %.100s", port, strerror(errno));
2524 for (n = 0; n < num_socks; n++) {
2530 socks[num_socks++] = sock;
2531 #ifndef DONT_TRY_OTHER_AF
2532 if (num_socks == NUM_SOCKS)
2535 if (x11_use_localhost) {
2536 if (num_socks == NUM_SOCKS)
2543 freeaddrinfo(aitop);
2547 if (display_number >= MAX_DISPLAYS) {
2548 error("Failed to allocate internet-domain X11 display socket.");
2551 /* Start listening for connections on the socket. */
2552 for (n = 0; n < num_socks; n++) {
2554 if (listen(sock, 5) < 0) {
2555 error("listen: %.100s", strerror(errno));
2561 /* Allocate a channel for each socket. */
2562 for (n = 0; n < num_socks; n++) {
2564 nc = channel_new("x11 listener",
2565 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2566 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2567 0, "X11 inet listener", 1);
2568 nc->single_connection = single_connection;
2571 /* Return the display number for the DISPLAY environment variable. */
2572 *display_numberp = display_number;
2577 connect_local_xsocket(u_int dnr)
2580 struct sockaddr_un addr;
2582 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2584 error("socket: %.100s", strerror(errno));
2585 memset(&addr, 0, sizeof(addr));
2586 addr.sun_family = AF_UNIX;
2587 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2588 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2591 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2596 x11_connect_display(void)
2598 int display_number, sock = 0;
2599 const char *display;
2600 char buf[1024], *cp;
2601 struct addrinfo hints, *ai, *aitop;
2602 char strport[NI_MAXSERV];
2605 /* Try to open a socket for the local X server. */
2606 display = getenv("DISPLAY");
2608 error("DISPLAY not set.");
2612 * Now we decode the value of the DISPLAY variable and make a
2613 * connection to the real X server.
2617 * Check if it is a unix domain socket. Unix domain displays are in
2618 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2620 if (strncmp(display, "unix:", 5) == 0 ||
2621 display[0] == ':') {
2622 /* Connect to the unix domain socket. */
2623 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2624 error("Could not parse display number from DISPLAY: %.100s",
2628 /* Create a socket. */
2629 sock = connect_local_xsocket(display_number);
2633 /* OK, we now have a connection to the display. */
2637 * Connect to an inet socket. The DISPLAY value is supposedly
2638 * hostname:d[.s], where hostname may also be numeric IP address.
2640 strlcpy(buf, display, sizeof(buf));
2641 cp = strchr(buf, ':');
2643 error("Could not find ':' in DISPLAY: %.100s", display);
2647 /* buf now contains the host name. But first we parse the display number. */
2648 if (sscanf(cp + 1, "%d", &display_number) != 1) {
2649 error("Could not parse display number from DISPLAY: %.100s",
2654 /* Look up the host address */
2655 memset(&hints, 0, sizeof(hints));
2656 hints.ai_family = IPv4or6;
2657 hints.ai_socktype = SOCK_STREAM;
2658 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2659 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2660 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2663 for (ai = aitop; ai; ai = ai->ai_next) {
2664 /* Create a socket. */
2665 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2667 debug2("socket: %.100s", strerror(errno));
2670 /* Connect it to the display. */
2671 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2672 debug2("connect %.100s port %d: %.100s", buf,
2673 6000 + display_number, strerror(errno));
2680 freeaddrinfo(aitop);
2682 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2691 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
2692 * the remote channel number. We should do whatever we want, and respond
2693 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2697 x11_input_open(int type, u_int32_t seq, void *ctxt)
2700 int remote_id, sock = 0;
2703 debug("Received X11 open request.");
2705 remote_id = packet_get_int();
2707 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2708 remote_host = packet_get_string(NULL);
2710 remote_host = xstrdup("unknown (remote did not supply name)");
2714 /* Obtain a connection to the real X display. */
2715 sock = x11_connect_display();
2717 /* Allocate a channel for this connection. */
2718 c = channel_new("connected x11 socket",
2719 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
2721 c->remote_id = remote_id;
2726 /* Send refusal to the remote host. */
2727 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2728 packet_put_int(remote_id);
2730 /* Send a confirmation to the remote host. */
2731 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2732 packet_put_int(remote_id);
2733 packet_put_int(c->self);
2738 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2740 deny_input_open(int type, u_int32_t seq, void *ctxt)
2742 int rchan = packet_get_int();
2745 case SSH_SMSG_AGENT_OPEN:
2746 error("Warning: ssh server tried agent forwarding.");
2748 case SSH_SMSG_X11_OPEN:
2749 error("Warning: ssh server tried X11 forwarding.");
2752 error("deny_input_open: type %d", type);
2755 error("Warning: this is probably a break in attempt by a malicious server.");
2756 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2757 packet_put_int(rchan);
2762 * Requests forwarding of X11 connections, generates fake authentication
2763 * data, and enables authentication spoofing.
2764 * This should be called in the client only.
2767 x11_request_forwarding_with_spoofing(int client_session_id,
2768 const char *proto, const char *data)
2770 u_int data_len = (u_int) strlen(data) / 2;
2771 u_int i, value, len;
2777 cp = getenv("DISPLAY");
2779 cp = strchr(cp, ':');
2781 cp = strchr(cp, '.');
2783 screen_number = atoi(cp + 1);
2787 /* Save protocol name. */
2788 x11_saved_proto = xstrdup(proto);
2791 * Extract real authentication data and generate fake data of the
2794 x11_saved_data = xmalloc(data_len);
2795 x11_fake_data = xmalloc(data_len);
2796 for (i = 0; i < data_len; i++) {
2797 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2798 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2800 rand = arc4random();
2801 x11_saved_data[i] = value;
2802 x11_fake_data[i] = rand & 0xff;
2805 x11_saved_data_len = data_len;
2806 x11_fake_data_len = data_len;
2808 /* Convert the fake data into hex. */
2809 len = 2 * data_len + 1;
2810 new_data = xmalloc(len);
2811 for (i = 0; i < data_len; i++)
2812 snprintf(new_data + 2 * i, len - 2 * i,
2813 "%02x", (u_char) x11_fake_data[i]);
2815 /* Send the request packet. */
2817 channel_request_start(client_session_id, "x11-req", 0);
2818 packet_put_char(0); /* XXX bool single connection */
2820 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2822 packet_put_cstring(proto);
2823 packet_put_cstring(new_data);
2824 packet_put_int(screen_number);
2826 packet_write_wait();
2831 /* -- agent forwarding */
2833 /* Sends a message to the server to request authentication fd forwarding. */
2836 auth_request_forwarding(void)
2838 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2840 packet_write_wait();
2843 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2846 auth_input_open_request(int type, u_int32_t seq, void *ctxt)
2849 int remote_id, sock;
2851 /* Read the remote channel number from the message. */
2852 remote_id = packet_get_int();
2856 * Get a connection to the local authentication agent (this may again
2859 sock = ssh_get_authentication_socket();
2862 * If we could not connect the agent, send an error message back to
2863 * the server. This should never happen unless the agent dies,
2864 * because authentication forwarding is only enabled if we have an
2868 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
2869 -1, 0, 0, 0, "authentication agent connection", 1);
2870 c->remote_id = remote_id;
2874 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2875 packet_put_int(remote_id);
2877 /* Send a confirmation to the remote host. */
2878 debug("Forwarding authentication connection.");
2879 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2880 packet_put_int(remote_id);
2881 packet_put_int(c->self);