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.183 2002/09/17 07:47:02 itojun Exp $");
43 RCSID("$FreeBSD: src/crypto/openssh/channels.c,v 1.1.1.1.2.8 2003/02/03 17:31:06 des Exp $");
57 #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 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 authentication protocol name. */
114 static char *x11_saved_proto = NULL;
116 /* Saved X11 authentication data. This is the real data. */
117 static char *x11_saved_data = NULL;
118 static u_int x11_saved_data_len = 0;
121 * Fake X11 authentication data. This is what the server will be sending us;
122 * we should replace any occurrences of this by the real data.
124 static char *x11_fake_data = NULL;
125 static u_int x11_fake_data_len;
128 /* -- agent forwarding */
132 /* AF_UNSPEC or AF_INET or AF_INET6 */
133 static int IPv4or6 = AF_UNSPEC;
136 static void port_open_helper(Channel *c, char *rtype);
138 /* -- channel core */
141 channel_lookup(int id)
145 if (id < 0 || id >= channels_alloc) {
146 log("channel_lookup: %d: bad id", id);
151 log("channel_lookup: %d: bad id: channel free", id);
158 * Register filedescriptors for a channel, used when allocating a channel or
159 * when the channel consumer/producer is ready, e.g. shell exec'd
163 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
164 int extusage, int nonblock)
166 /* Update the maximum file descriptor value. */
167 channel_max_fd = MAX(channel_max_fd, rfd);
168 channel_max_fd = MAX(channel_max_fd, wfd);
169 channel_max_fd = MAX(channel_max_fd, efd);
171 /* XXX set close-on-exec -markus */
175 c->sock = (rfd == wfd) ? rfd : -1;
177 c->extended_usage = extusage;
179 /* XXX ugly hack: nonblock is only set by the server */
180 if (nonblock && isatty(c->rfd)) {
181 debug("channel %d: rfd %d isatty", c->self, c->rfd);
183 if (!isatty(c->wfd)) {
184 error("channel %d: wfd %d is not a tty?",
190 c->wfd_isatty = isatty(c->wfd);
192 /* enable nonblocking mode */
204 * Allocate a new channel object and set its type and socket. This will cause
205 * remote_name to be freed.
209 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
210 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
215 /* Do initial allocation if this is the first call. */
216 if (channels_alloc == 0) {
218 channels = xmalloc(channels_alloc * sizeof(Channel *));
219 for (i = 0; i < channels_alloc; i++)
221 fatal_add_cleanup((void (*) (void *)) channel_free_all, NULL);
223 /* Try to find a free slot where to put the new channel. */
224 for (found = -1, i = 0; i < channels_alloc; i++)
225 if (channels[i] == NULL) {
226 /* Found a free slot. */
231 /* There are no free slots. Take last+1 slot and expand the array. */
232 found = channels_alloc;
233 channels_alloc += 10;
234 if (channels_alloc > 10000)
235 fatal("channel_new: internal error: channels_alloc %d "
236 "too big.", channels_alloc);
237 debug2("channel: expanding %d", channels_alloc);
238 channels = xrealloc(channels, channels_alloc * sizeof(Channel *));
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 = 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_close_fds: channel %d: 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_free: channel %d: %s, nchannels %d", c->self,
329 c->remote_name ? c->remote_name : "???", n);
331 s = channel_open_message();
332 debug3("channel_free: status: %s", 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 debug("channel %d: big input buffer %d",
418 c->self, buffer_len(&c->input));
422 if (buffer_len(&c->output) > packet_get_maxsize()) {
423 debug("channel %d: big output buffer %d > %d",
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 log("channel_send_open: %d: bad id", id);
582 debug("send channel open %d", 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 local_id, char *service, int wantconfirm)
594 Channel *c = channel_lookup(local_id);
597 log("channel_request_start: %d: unknown channel id", local_id);
600 debug("channel request %d: %s", local_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 log("channel_register_comfirm: %d: bad id", id);
618 channel_register_cleanup(int id, channel_callback_fn *fn)
620 Channel *c = channel_lookup(id);
623 log("channel_register_cleanup: %d: bad id", id);
629 channel_cancel_cleanup(int id)
631 Channel *c = channel_lookup(id);
634 log("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 log("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 debug("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 debug("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 debug("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 debug("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 log("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 log("X11 connection rejected because of wrong authentication.");
861 debug("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 debug("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 debug("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 /* dynamic port forwarding */
947 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
952 have = buffer_len(&c->input);
954 debug2("channel %d: pre_dynamic: have %d", c->self, have);
955 /* buffer_dump(&c->input); */
956 /* check if the fixed size part of the packet is in buffer. */
959 FD_SET(c->sock, readset);
962 /* try to guess the protocol */
963 p = buffer_ptr(&c->input);
966 ret = channel_decode_socks4(c, readset, writeset);
974 } else if (ret == 0) {
975 debug2("channel %d: pre_dynamic: need more", c->self);
977 FD_SET(c->sock, readset);
979 /* switch to the next state */
980 c->type = SSH_CHANNEL_OPENING;
981 port_open_helper(c, "direct-tcpip");
985 /* This is our fake X11 server socket. */
987 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
990 struct sockaddr addr;
993 char buf[16384], *remote_ipaddr;
996 if (FD_ISSET(c->sock, readset)) {
997 debug("X11 connection requested.");
998 addrlen = sizeof(addr);
999 newsock = accept(c->sock, &addr, &addrlen);
1000 if (c->single_connection) {
1001 debug("single_connection: closing X11 listener.");
1002 channel_close_fd(&c->sock);
1006 error("accept: %.100s", strerror(errno));
1009 set_nodelay(newsock);
1010 remote_ipaddr = get_peer_ipaddr(newsock);
1011 remote_port = get_peer_port(newsock);
1012 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1013 remote_ipaddr, remote_port);
1015 nc = channel_new("accepted x11 socket",
1016 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1017 c->local_window_max, c->local_maxpacket,
1018 0, xstrdup(buf), 1);
1020 packet_start(SSH2_MSG_CHANNEL_OPEN);
1021 packet_put_cstring("x11");
1022 packet_put_int(nc->self);
1023 packet_put_int(nc->local_window_max);
1024 packet_put_int(nc->local_maxpacket);
1025 /* originator ipaddr and port */
1026 packet_put_cstring(remote_ipaddr);
1027 if (datafellows & SSH_BUG_X11FWD) {
1028 debug("ssh2 x11 bug compat mode");
1030 packet_put_int(remote_port);
1034 packet_start(SSH_SMSG_X11_OPEN);
1035 packet_put_int(nc->self);
1036 if (packet_get_protocol_flags() &
1037 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1038 packet_put_cstring(buf);
1041 xfree(remote_ipaddr);
1046 port_open_helper(Channel *c, char *rtype)
1050 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1051 u_short remote_port = get_peer_port(c->sock);
1053 direct = (strcmp(rtype, "direct-tcpip") == 0);
1055 snprintf(buf, sizeof buf,
1056 "%s: listening port %d for %.100s port %d, "
1057 "connect from %.200s port %d",
1058 rtype, c->listening_port, c->path, c->host_port,
1059 remote_ipaddr, remote_port);
1061 xfree(c->remote_name);
1062 c->remote_name = xstrdup(buf);
1065 packet_start(SSH2_MSG_CHANNEL_OPEN);
1066 packet_put_cstring(rtype);
1067 packet_put_int(c->self);
1068 packet_put_int(c->local_window_max);
1069 packet_put_int(c->local_maxpacket);
1071 /* target host, port */
1072 packet_put_cstring(c->path);
1073 packet_put_int(c->host_port);
1075 /* listen address, port */
1076 packet_put_cstring(c->path);
1077 packet_put_int(c->listening_port);
1079 /* originator host and port */
1080 packet_put_cstring(remote_ipaddr);
1081 packet_put_int(remote_port);
1084 packet_start(SSH_MSG_PORT_OPEN);
1085 packet_put_int(c->self);
1086 packet_put_cstring(c->path);
1087 packet_put_int(c->host_port);
1088 if (packet_get_protocol_flags() &
1089 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1090 packet_put_cstring(c->remote_name);
1093 xfree(remote_ipaddr);
1097 * This socket is listening for connections to a forwarded TCP/IP port.
1100 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
1103 struct sockaddr addr;
1104 int newsock, nextstate;
1108 if (FD_ISSET(c->sock, readset)) {
1109 debug("Connection to port %d forwarding "
1110 "to %.100s port %d requested.",
1111 c->listening_port, c->path, c->host_port);
1113 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1114 nextstate = SSH_CHANNEL_OPENING;
1115 rtype = "forwarded-tcpip";
1117 if (c->host_port == 0) {
1118 nextstate = SSH_CHANNEL_DYNAMIC;
1119 rtype = "dynamic-tcpip";
1121 nextstate = SSH_CHANNEL_OPENING;
1122 rtype = "direct-tcpip";
1126 addrlen = sizeof(addr);
1127 newsock = accept(c->sock, &addr, &addrlen);
1129 error("accept: %.100s", strerror(errno));
1132 set_nodelay(newsock);
1133 nc = channel_new(rtype,
1134 nextstate, newsock, newsock, -1,
1135 c->local_window_max, c->local_maxpacket,
1136 0, xstrdup(rtype), 1);
1137 nc->listening_port = c->listening_port;
1138 nc->host_port = c->host_port;
1139 strlcpy(nc->path, c->path, sizeof(nc->path));
1141 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1143 * do not call the channel_post handler until
1144 * this flag has been reset by a pre-handler.
1145 * otherwise the FD_ISSET calls might overflow
1149 port_open_helper(nc, rtype);
1155 * This is the authentication agent socket listening for connections from
1159 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
1164 struct sockaddr addr;
1167 if (FD_ISSET(c->sock, readset)) {
1168 addrlen = sizeof(addr);
1169 newsock = accept(c->sock, &addr, &addrlen);
1171 error("accept from auth socket: %.100s", strerror(errno));
1174 name = xstrdup("accepted auth socket");
1175 nc = channel_new("accepted auth socket",
1176 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1177 c->local_window_max, c->local_maxpacket,
1180 packet_start(SSH2_MSG_CHANNEL_OPEN);
1181 packet_put_cstring("auth-agent@openssh.com");
1182 packet_put_int(nc->self);
1183 packet_put_int(c->local_window_max);
1184 packet_put_int(c->local_maxpacket);
1186 packet_start(SSH_SMSG_AGENT_OPEN);
1187 packet_put_int(nc->self);
1194 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
1197 socklen_t sz = sizeof(err);
1199 if (FD_ISSET(c->sock, writeset)) {
1200 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1202 error("getsockopt SO_ERROR failed");
1205 debug("channel %d: connected", c->self);
1206 c->type = SSH_CHANNEL_OPEN;
1208 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1209 packet_put_int(c->remote_id);
1210 packet_put_int(c->self);
1211 packet_put_int(c->local_window);
1212 packet_put_int(c->local_maxpacket);
1214 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1215 packet_put_int(c->remote_id);
1216 packet_put_int(c->self);
1219 debug("channel %d: not connected: %s",
1220 c->self, strerror(err));
1222 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1223 packet_put_int(c->remote_id);
1224 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1225 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1226 packet_put_cstring(strerror(err));
1227 packet_put_cstring("");
1230 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1231 packet_put_int(c->remote_id);
1240 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
1246 FD_ISSET(c->rfd, readset)) {
1247 len = read(c->rfd, buf, sizeof(buf));
1248 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1251 debug("channel %d: read<=0 rfd %d len %d",
1252 c->self, c->rfd, len);
1253 if (c->type != SSH_CHANNEL_OPEN) {
1254 debug("channel %d: not open", c->self);
1257 } else if (compat13) {
1258 buffer_clear(&c->output);
1259 c->type = SSH_CHANNEL_INPUT_DRAINING;
1260 debug("channel %d: input draining.", c->self);
1262 chan_read_failed(c);
1266 if (c->input_filter != NULL) {
1267 if (c->input_filter(c, buf, len) == -1) {
1268 debug("channel %d: filter stops", c->self);
1269 chan_read_failed(c);
1272 buffer_append(&c->input, buf, len);
1278 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
1285 /* Send buffered output data to the socket. */
1287 FD_ISSET(c->wfd, writeset) &&
1288 buffer_len(&c->output) > 0) {
1289 data = buffer_ptr(&c->output);
1290 dlen = buffer_len(&c->output);
1292 /* XXX: Later AIX versions can't push as much data to tty */
1293 if (compat20 && c->wfd_isatty && dlen > 8*1024)
1296 len = write(c->wfd, data, dlen);
1297 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1300 if (c->type != SSH_CHANNEL_OPEN) {
1301 debug("channel %d: not open", c->self);
1304 } else if (compat13) {
1305 buffer_clear(&c->output);
1306 debug("channel %d: input draining.", c->self);
1307 c->type = SSH_CHANNEL_INPUT_DRAINING;
1309 chan_write_failed(c);
1313 if (compat20 && c->isatty && dlen >= 1 && data[0] != '\r') {
1314 if (tcgetattr(c->wfd, &tio) == 0 &&
1315 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1317 * Simulate echo to reduce the impact of
1318 * traffic analysis. We need to match the
1319 * size of a SSH2_MSG_CHANNEL_DATA message
1320 * (4 byte channel id + data)
1322 packet_send_ignore(4 + len);
1326 buffer_consume(&c->output, len);
1327 if (compat20 && len > 0) {
1328 c->local_consumed += len;
1334 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
1339 /** XXX handle drain efd, too */
1341 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1342 FD_ISSET(c->efd, writeset) &&
1343 buffer_len(&c->extended) > 0) {
1344 len = write(c->efd, buffer_ptr(&c->extended),
1345 buffer_len(&c->extended));
1346 debug2("channel %d: written %d to efd %d",
1347 c->self, len, c->efd);
1348 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1351 debug2("channel %d: closing write-efd %d",
1353 channel_close_fd(&c->efd);
1355 buffer_consume(&c->extended, len);
1356 c->local_consumed += len;
1358 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1359 FD_ISSET(c->efd, readset)) {
1360 len = read(c->efd, buf, sizeof(buf));
1361 debug2("channel %d: read %d from efd %d",
1362 c->self, len, c->efd);
1363 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1366 debug2("channel %d: closing read-efd %d",
1368 channel_close_fd(&c->efd);
1370 buffer_append(&c->extended, buf, len);
1377 channel_check_window(Channel *c)
1379 if (c->type == SSH_CHANNEL_OPEN &&
1380 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1381 c->local_window < c->local_window_max/2 &&
1382 c->local_consumed > 0) {
1383 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1384 packet_put_int(c->remote_id);
1385 packet_put_int(c->local_consumed);
1387 debug2("channel %d: window %d sent adjust %d",
1388 c->self, c->local_window,
1390 c->local_window += c->local_consumed;
1391 c->local_consumed = 0;
1397 channel_post_open(Channel *c, fd_set * readset, fd_set * writeset)
1401 channel_handle_rfd(c, readset, writeset);
1402 channel_handle_wfd(c, readset, writeset);
1405 channel_handle_efd(c, readset, writeset);
1406 channel_check_window(c);
1410 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1414 /* Send buffered output data to the socket. */
1415 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1416 len = write(c->sock, buffer_ptr(&c->output),
1417 buffer_len(&c->output));
1419 buffer_clear(&c->output);
1421 buffer_consume(&c->output, len);
1426 channel_handler_init_20(void)
1428 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1429 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1430 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1431 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1432 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1433 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1434 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1435 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1437 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1438 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1439 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1440 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1441 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1442 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1443 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1447 channel_handler_init_13(void)
1449 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1450 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1451 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1452 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1453 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1454 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1455 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1456 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1457 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1459 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1460 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1461 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1462 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1463 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1464 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1465 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1469 channel_handler_init_15(void)
1471 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1472 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1473 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1474 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1475 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1476 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1477 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1479 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1480 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1481 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1482 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1483 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1484 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1488 channel_handler_init(void)
1492 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1493 channel_pre[i] = NULL;
1494 channel_post[i] = NULL;
1497 channel_handler_init_20();
1499 channel_handler_init_13();
1501 channel_handler_init_15();
1504 /* gc dead channels */
1506 channel_garbage_collect(Channel *c)
1510 if (c->detach_user != NULL) {
1511 if (!chan_is_dead(c, 0))
1513 debug("channel %d: gc: notify user", c->self);
1514 c->detach_user(c->self, NULL);
1515 /* if we still have a callback */
1516 if (c->detach_user != NULL)
1518 debug("channel %d: gc: user detached", c->self);
1520 if (!chan_is_dead(c, 1))
1522 debug("channel %d: garbage collecting", c->self);
1527 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1529 static int did_init = 0;
1534 channel_handler_init();
1537 for (i = 0; i < channels_alloc; i++) {
1541 if (ftab[c->type] != NULL)
1542 (*ftab[c->type])(c, readset, writeset);
1543 channel_garbage_collect(c);
1548 * Allocate/update select bitmasks and add any bits relevant to channels in
1552 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1553 int *nallocp, int rekeying)
1558 n = MAX(*maxfdp, channel_max_fd);
1560 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1561 /* perhaps check sz < nalloc/2 and shrink? */
1562 if (*readsetp == NULL || sz > *nallocp) {
1563 *readsetp = xrealloc(*readsetp, sz);
1564 *writesetp = xrealloc(*writesetp, sz);
1568 memset(*readsetp, 0, sz);
1569 memset(*writesetp, 0, sz);
1572 channel_handler(channel_pre, *readsetp, *writesetp);
1576 * After select, perform any appropriate operations for channels which have
1580 channel_after_select(fd_set * readset, fd_set * writeset)
1582 channel_handler(channel_post, readset, writeset);
1586 /* If there is data to send to the connection, enqueue some of it now. */
1589 channel_output_poll(void)
1595 for (i = 0; i < channels_alloc; i++) {
1601 * We are only interested in channels that can have buffered
1605 if (c->type != SSH_CHANNEL_OPEN &&
1606 c->type != SSH_CHANNEL_INPUT_DRAINING)
1609 if (c->type != SSH_CHANNEL_OPEN)
1613 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1614 /* XXX is this true? */
1615 debug3("channel %d: will not send data after close", c->self);
1619 /* Get the amount of buffered data for this channel. */
1620 if ((c->istate == CHAN_INPUT_OPEN ||
1621 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1622 (len = buffer_len(&c->input)) > 0) {
1624 * Send some data for the other side over the secure
1628 if (len > c->remote_window)
1629 len = c->remote_window;
1630 if (len > c->remote_maxpacket)
1631 len = c->remote_maxpacket;
1633 if (packet_is_interactive()) {
1637 /* Keep the packets at reasonable size. */
1638 if (len > packet_get_maxsize()/2)
1639 len = packet_get_maxsize()/2;
1643 packet_start(compat20 ?
1644 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1645 packet_put_int(c->remote_id);
1646 packet_put_string(buffer_ptr(&c->input), len);
1648 buffer_consume(&c->input, len);
1649 c->remote_window -= len;
1651 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1653 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1655 * input-buffer is empty and read-socket shutdown:
1656 * tell peer, that we will not send more data: send IEOF.
1657 * hack for extended data: delay EOF if EFD still in use.
1659 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1660 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1661 c->self, c->efd, buffer_len(&c->extended));
1665 /* Send extended data, i.e. stderr */
1667 !(c->flags & CHAN_EOF_SENT) &&
1668 c->remote_window > 0 &&
1669 (len = buffer_len(&c->extended)) > 0 &&
1670 c->extended_usage == CHAN_EXTENDED_READ) {
1671 debug2("channel %d: rwin %u elen %u euse %d",
1672 c->self, c->remote_window, buffer_len(&c->extended),
1674 if (len > c->remote_window)
1675 len = c->remote_window;
1676 if (len > c->remote_maxpacket)
1677 len = c->remote_maxpacket;
1678 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1679 packet_put_int(c->remote_id);
1680 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1681 packet_put_string(buffer_ptr(&c->extended), len);
1683 buffer_consume(&c->extended, len);
1684 c->remote_window -= len;
1685 debug2("channel %d: sent ext data %d", c->self, len);
1691 /* -- protocol input */
1694 channel_input_data(int type, u_int32_t seq, void *ctxt)
1701 /* Get the channel number and verify it. */
1702 id = packet_get_int();
1703 c = channel_lookup(id);
1705 packet_disconnect("Received data for nonexistent channel %d.", id);
1707 /* Ignore any data for non-open channels (might happen on close) */
1708 if (c->type != SSH_CHANNEL_OPEN &&
1709 c->type != SSH_CHANNEL_X11_OPEN)
1712 /* same for protocol 1.5 if output end is no longer open */
1713 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1717 data = packet_get_string(&data_len);
1720 if (data_len > c->local_maxpacket) {
1721 log("channel %d: rcvd big packet %d, maxpack %d",
1722 c->self, data_len, c->local_maxpacket);
1724 if (data_len > c->local_window) {
1725 log("channel %d: rcvd too much data %d, win %d",
1726 c->self, data_len, c->local_window);
1730 c->local_window -= data_len;
1733 buffer_append(&c->output, data, data_len);
1738 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
1742 u_int data_len, tcode;
1745 /* Get the channel number and verify it. */
1746 id = packet_get_int();
1747 c = channel_lookup(id);
1750 packet_disconnect("Received extended_data for bad channel %d.", id);
1751 if (c->type != SSH_CHANNEL_OPEN) {
1752 log("channel %d: ext data for non open", id);
1755 if (c->flags & CHAN_EOF_RCVD) {
1756 if (datafellows & SSH_BUG_EXTEOF)
1757 debug("channel %d: accepting ext data after eof", id);
1759 packet_disconnect("Received extended_data after EOF "
1760 "on channel %d.", id);
1762 tcode = packet_get_int();
1764 c->extended_usage != CHAN_EXTENDED_WRITE ||
1765 tcode != SSH2_EXTENDED_DATA_STDERR) {
1766 log("channel %d: bad ext data", c->self);
1769 data = packet_get_string(&data_len);
1771 if (data_len > c->local_window) {
1772 log("channel %d: rcvd too much extended_data %d, win %d",
1773 c->self, data_len, c->local_window);
1777 debug2("channel %d: rcvd ext data %d", c->self, data_len);
1778 c->local_window -= data_len;
1779 buffer_append(&c->extended, data, data_len);
1784 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
1789 id = packet_get_int();
1791 c = channel_lookup(id);
1793 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1796 /* XXX force input close */
1797 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
1798 debug("channel %d: FORCE input drain", c->self);
1799 c->istate = CHAN_INPUT_WAIT_DRAIN;
1800 if (buffer_len(&c->input) == 0)
1807 channel_input_close(int type, u_int32_t seq, void *ctxt)
1812 id = packet_get_int();
1814 c = channel_lookup(id);
1816 packet_disconnect("Received close for nonexistent channel %d.", id);
1819 * Send a confirmation that we have closed the channel and no more
1820 * data is coming for it.
1822 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1823 packet_put_int(c->remote_id);
1827 * If the channel is in closed state, we have sent a close request,
1828 * and the other side will eventually respond with a confirmation.
1829 * Thus, we cannot free the channel here, because then there would be
1830 * no-one to receive the confirmation. The channel gets freed when
1831 * the confirmation arrives.
1833 if (c->type != SSH_CHANNEL_CLOSED) {
1835 * Not a closed channel - mark it as draining, which will
1836 * cause it to be freed later.
1838 buffer_clear(&c->input);
1839 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1843 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1845 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
1847 int id = packet_get_int();
1848 Channel *c = channel_lookup(id);
1852 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1853 chan_rcvd_oclose(c);
1857 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
1859 int id = packet_get_int();
1860 Channel *c = channel_lookup(id);
1864 packet_disconnect("Received close confirmation for "
1865 "out-of-range channel %d.", id);
1866 if (c->type != SSH_CHANNEL_CLOSED)
1867 packet_disconnect("Received close confirmation for "
1868 "non-closed channel %d (type %d).", id, c->type);
1873 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
1878 id = packet_get_int();
1879 c = channel_lookup(id);
1881 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1882 packet_disconnect("Received open confirmation for "
1883 "non-opening channel %d.", id);
1884 remote_id = packet_get_int();
1885 /* Record the remote channel number and mark that the channel is now open. */
1886 c->remote_id = remote_id;
1887 c->type = SSH_CHANNEL_OPEN;
1890 c->remote_window = packet_get_int();
1891 c->remote_maxpacket = packet_get_int();
1893 debug2("callback start");
1894 c->confirm(c->self, NULL);
1895 debug2("callback done");
1897 debug("channel %d: open confirm rwindow %u rmax %u", c->self,
1898 c->remote_window, c->remote_maxpacket);
1904 reason2txt(int reason)
1907 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
1908 return "administratively prohibited";
1909 case SSH2_OPEN_CONNECT_FAILED:
1910 return "connect failed";
1911 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
1912 return "unknown channel type";
1913 case SSH2_OPEN_RESOURCE_SHORTAGE:
1914 return "resource shortage";
1916 return "unknown reason";
1920 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
1923 char *msg = NULL, *lang = NULL;
1926 id = packet_get_int();
1927 c = channel_lookup(id);
1929 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1930 packet_disconnect("Received open failure for "
1931 "non-opening channel %d.", id);
1933 reason = packet_get_int();
1934 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1935 msg = packet_get_string(NULL);
1936 lang = packet_get_string(NULL);
1938 log("channel %d: open failed: %s%s%s", id,
1939 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1946 /* Free the channel. This will also close the socket. */
1951 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
1960 /* Get the channel number and verify it. */
1961 id = packet_get_int();
1962 c = channel_lookup(id);
1964 if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1965 log("Received window adjust for "
1966 "non-open channel %d.", id);
1969 adjust = packet_get_int();
1971 debug2("channel %d: rcvd adjust %u", id, adjust);
1972 c->remote_window += adjust;
1976 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
1980 char *host, *originator_string;
1981 int remote_id, sock = -1;
1983 remote_id = packet_get_int();
1984 host = packet_get_string(NULL);
1985 host_port = packet_get_int();
1987 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
1988 originator_string = packet_get_string(NULL);
1990 originator_string = xstrdup("unknown (remote did not supply name)");
1993 sock = channel_connect_to(host, host_port);
1995 c = channel_new("connected socket",
1996 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
1997 originator_string, 1);
1998 c->remote_id = remote_id;
2001 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2002 packet_put_int(remote_id);
2009 /* -- tcp forwarding */
2012 channel_set_af(int af)
2018 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2019 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2022 int success, sock, on = 1;
2023 struct addrinfo hints, *ai, *aitop;
2025 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2028 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2029 listen_addr : host_to_connect;
2032 error("No forward host name.");
2035 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2036 error("Forward host name too long.");
2041 * getaddrinfo returns a loopback address if the hostname is
2042 * set to NULL and hints.ai_flags is not AI_PASSIVE
2044 memset(&hints, 0, sizeof(hints));
2045 hints.ai_family = IPv4or6;
2046 hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
2047 hints.ai_socktype = SOCK_STREAM;
2048 snprintf(strport, sizeof strport, "%d", listen_port);
2049 if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
2050 packet_disconnect("getaddrinfo: fatal error");
2052 for (ai = aitop; ai; ai = ai->ai_next) {
2053 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2055 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2056 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2057 error("channel_setup_fwd_listener: getnameinfo failed");
2060 /* Create a port to listen for the host. */
2061 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2063 /* this is no error since kernel may not support ipv6 */
2064 verbose("socket: %.100s", strerror(errno));
2068 * Set socket options.
2069 * Allow local port reuse in TIME_WAIT.
2071 if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
2073 error("setsockopt SO_REUSEADDR: %s", strerror(errno));
2075 debug("Local forwarding listening on %s port %s.", ntop, strport);
2077 /* Bind the socket to the address. */
2078 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2079 /* address can be in use ipv6 address is already bound */
2081 error("bind: %.100s", strerror(errno));
2083 verbose("bind: %.100s", strerror(errno));
2088 /* Start listening for connections on the socket. */
2089 if (listen(sock, 5) < 0) {
2090 error("listen: %.100s", strerror(errno));
2094 /* Allocate a channel number for the socket. */
2095 c = channel_new("port listener", type, sock, sock, -1,
2096 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2097 0, xstrdup("port listener"), 1);
2098 strlcpy(c->path, host, sizeof(c->path));
2099 c->host_port = port_to_connect;
2100 c->listening_port = listen_port;
2104 error("channel_setup_fwd_listener: cannot listen to port: %d",
2106 freeaddrinfo(aitop);
2110 /* protocol local port fwd, used by ssh (and sshd in v1) */
2112 channel_setup_local_fwd_listener(u_short listen_port,
2113 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2115 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2116 NULL, listen_port, host_to_connect, port_to_connect, gateway_ports);
2119 /* protocol v2 remote port fwd, used by sshd */
2121 channel_setup_remote_fwd_listener(const char *listen_address,
2122 u_short listen_port, int gateway_ports)
2124 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2125 listen_address, listen_port, NULL, 0, gateway_ports);
2129 * Initiate forwarding of connections to port "port" on remote host through
2130 * the secure channel to host:port from local side.
2134 channel_request_remote_forwarding(u_short listen_port,
2135 const char *host_to_connect, u_short port_to_connect)
2137 int type, success = 0;
2139 /* Record locally that connection to this host/port is permitted. */
2140 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2141 fatal("channel_request_remote_forwarding: too many forwards");
2143 /* Send the forward request to the remote side. */
2145 const char *address_to_bind = "0.0.0.0";
2146 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2147 packet_put_cstring("tcpip-forward");
2148 packet_put_char(1); /* boolean: want reply */
2149 packet_put_cstring(address_to_bind);
2150 packet_put_int(listen_port);
2152 packet_write_wait();
2153 /* Assume that server accepts the request */
2156 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2157 packet_put_int(listen_port);
2158 packet_put_cstring(host_to_connect);
2159 packet_put_int(port_to_connect);
2161 packet_write_wait();
2163 /* Wait for response from the remote side. */
2164 type = packet_read();
2166 case SSH_SMSG_SUCCESS:
2169 case SSH_SMSG_FAILURE:
2170 log("Warning: Server denied remote port forwarding.");
2173 /* Unknown packet */
2174 packet_disconnect("Protocol error for port forward request:"
2175 "received packet type %d.", type);
2179 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2180 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2181 permitted_opens[num_permitted_opens].listen_port = listen_port;
2182 num_permitted_opens++;
2187 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2188 * listening for the port, and sends back a success reply (or disconnect
2189 * message if there was an error). This never returns if there was an error.
2193 channel_input_port_forward_request(int is_root, int gateway_ports)
2195 u_short port, host_port;
2198 /* Get arguments from the packet. */
2199 port = packet_get_int();
2200 hostname = packet_get_string(NULL);
2201 host_port = packet_get_int();
2205 * Check that an unprivileged user is not trying to forward a
2208 if (port < IPPORT_RESERVED && !is_root)
2209 packet_disconnect("Requested forwarding of port %d but user is not root.",
2212 /* Initiate forwarding */
2213 channel_setup_local_fwd_listener(port, hostname, host_port, gateway_ports);
2215 /* Free the argument string. */
2220 * Permits opening to any host/port if permitted_opens[] is empty. This is
2221 * usually called by the server, because the user could connect to any port
2222 * anyway, and the server has no way to know but to trust the client anyway.
2225 channel_permit_all_opens(void)
2227 if (num_permitted_opens == 0)
2228 all_opens_permitted = 1;
2232 channel_add_permitted_opens(char *host, int port)
2234 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2235 fatal("channel_request_remote_forwarding: too many forwards");
2236 debug("allow port forwarding to host %s port %d", host, port);
2238 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2239 permitted_opens[num_permitted_opens].port_to_connect = port;
2240 num_permitted_opens++;
2242 all_opens_permitted = 0;
2246 channel_clear_permitted_opens(void)
2250 for (i = 0; i < num_permitted_opens; i++)
2251 xfree(permitted_opens[i].host_to_connect);
2252 num_permitted_opens = 0;
2257 /* return socket to remote host, port */
2259 connect_to(const char *host, u_short port)
2261 struct addrinfo hints, *ai, *aitop;
2262 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2266 memset(&hints, 0, sizeof(hints));
2267 hints.ai_family = IPv4or6;
2268 hints.ai_socktype = SOCK_STREAM;
2269 snprintf(strport, sizeof strport, "%d", port);
2270 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2271 error("connect_to %.100s: unknown host (%s)", host,
2272 gai_strerror(gaierr));
2275 for (ai = aitop; ai; ai = ai->ai_next) {
2276 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2278 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2279 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2280 error("connect_to: getnameinfo failed");
2283 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2285 error("socket: %.100s", strerror(errno));
2288 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2289 fatal("connect_to: F_SETFL: %s", strerror(errno));
2290 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2291 errno != EINPROGRESS) {
2292 error("connect_to %.100s port %s: %.100s", ntop, strport,
2295 continue; /* fail -- try next */
2297 break; /* success */
2300 freeaddrinfo(aitop);
2302 error("connect_to %.100s port %d: failed.", host, port);
2311 channel_connect_by_listen_address(u_short listen_port)
2315 for (i = 0; i < num_permitted_opens; i++)
2316 if (permitted_opens[i].listen_port == listen_port)
2318 permitted_opens[i].host_to_connect,
2319 permitted_opens[i].port_to_connect);
2320 error("WARNING: Server requests forwarding for unknown listen_port %d",
2325 /* Check if connecting to that port is permitted and connect. */
2327 channel_connect_to(const char *host, u_short port)
2331 permit = all_opens_permitted;
2333 for (i = 0; i < num_permitted_opens; i++)
2334 if (permitted_opens[i].port_to_connect == port &&
2335 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2340 log("Received request to connect to host %.100s port %d, "
2341 "but the request was denied.", host, port);
2344 return connect_to(host, port);
2347 /* -- X11 forwarding */
2350 * Creates an internet domain socket for listening for X11 connections.
2351 * Returns 0 and a suitable display number for the DISPLAY variable
2352 * stored in display_numberp , or -1 if an error occurs.
2355 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2356 int single_connection, u_int *display_numberp)
2359 int display_number, sock;
2361 struct addrinfo hints, *ai, *aitop;
2362 char strport[NI_MAXSERV];
2363 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2365 for (display_number = x11_display_offset;
2366 display_number < MAX_DISPLAYS;
2368 port = 6000 + display_number;
2369 memset(&hints, 0, sizeof(hints));
2370 hints.ai_family = IPv4or6;
2371 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2372 hints.ai_socktype = SOCK_STREAM;
2373 snprintf(strport, sizeof strport, "%d", port);
2374 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2375 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2378 for (ai = aitop; ai; ai = ai->ai_next) {
2379 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2381 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2383 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2384 error("socket: %.100s", strerror(errno));
2387 debug("x11_create_display_inet: Socket family %d not supported",
2393 if (ai->ai_family == AF_INET6) {
2395 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2396 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2399 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2400 debug("bind port %d: %.100s", port, strerror(errno));
2406 for (n = 0; n < num_socks; n++) {
2412 socks[num_socks++] = sock;
2413 #ifndef DONT_TRY_OTHER_AF
2414 if (num_socks == NUM_SOCKS)
2417 if (x11_use_localhost) {
2418 if (num_socks == NUM_SOCKS)
2425 freeaddrinfo(aitop);
2429 if (display_number >= MAX_DISPLAYS) {
2430 error("Failed to allocate internet-domain X11 display socket.");
2433 /* Start listening for connections on the socket. */
2434 for (n = 0; n < num_socks; n++) {
2436 if (listen(sock, 5) < 0) {
2437 error("listen: %.100s", strerror(errno));
2443 /* Allocate a channel for each socket. */
2444 for (n = 0; n < num_socks; n++) {
2446 nc = channel_new("x11 listener",
2447 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2448 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2449 0, xstrdup("X11 inet listener"), 1);
2450 nc->single_connection = single_connection;
2453 /* Return the display number for the DISPLAY environment variable. */
2454 *display_numberp = display_number;
2459 connect_local_xsocket(u_int dnr)
2462 struct sockaddr_un addr;
2464 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2466 error("socket: %.100s", strerror(errno));
2467 memset(&addr, 0, sizeof(addr));
2468 addr.sun_family = AF_UNIX;
2469 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2470 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2473 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2478 x11_connect_display(void)
2480 int display_number, sock = 0;
2481 const char *display;
2482 char buf[1024], *cp;
2483 struct addrinfo hints, *ai, *aitop;
2484 char strport[NI_MAXSERV];
2487 /* Try to open a socket for the local X server. */
2488 display = getenv("DISPLAY");
2490 error("DISPLAY not set.");
2494 * Now we decode the value of the DISPLAY variable and make a
2495 * connection to the real X server.
2499 * Check if it is a unix domain socket. Unix domain displays are in
2500 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2502 if (strncmp(display, "unix:", 5) == 0 ||
2503 display[0] == ':') {
2504 /* Connect to the unix domain socket. */
2505 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2506 error("Could not parse display number from DISPLAY: %.100s",
2510 /* Create a socket. */
2511 sock = connect_local_xsocket(display_number);
2515 /* OK, we now have a connection to the display. */
2519 * Connect to an inet socket. The DISPLAY value is supposedly
2520 * hostname:d[.s], where hostname may also be numeric IP address.
2522 strlcpy(buf, display, sizeof(buf));
2523 cp = strchr(buf, ':');
2525 error("Could not find ':' in DISPLAY: %.100s", display);
2529 /* buf now contains the host name. But first we parse the display number. */
2530 if (sscanf(cp + 1, "%d", &display_number) != 1) {
2531 error("Could not parse display number from DISPLAY: %.100s",
2536 /* Look up the host address */
2537 memset(&hints, 0, sizeof(hints));
2538 hints.ai_family = IPv4or6;
2539 hints.ai_socktype = SOCK_STREAM;
2540 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2541 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2542 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2545 for (ai = aitop; ai; ai = ai->ai_next) {
2546 /* Create a socket. */
2547 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2549 debug("socket: %.100s", strerror(errno));
2552 /* Connect it to the display. */
2553 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2554 debug("connect %.100s port %d: %.100s", buf,
2555 6000 + display_number, strerror(errno));
2562 freeaddrinfo(aitop);
2564 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2573 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
2574 * the remote channel number. We should do whatever we want, and respond
2575 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2579 x11_input_open(int type, u_int32_t seq, void *ctxt)
2582 int remote_id, sock = 0;
2585 debug("Received X11 open request.");
2587 remote_id = packet_get_int();
2589 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2590 remote_host = packet_get_string(NULL);
2592 remote_host = xstrdup("unknown (remote did not supply name)");
2596 /* Obtain a connection to the real X display. */
2597 sock = x11_connect_display();
2599 /* Allocate a channel for this connection. */
2600 c = channel_new("connected x11 socket",
2601 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
2603 c->remote_id = remote_id;
2607 /* Send refusal to the remote host. */
2608 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2609 packet_put_int(remote_id);
2611 /* Send a confirmation to the remote host. */
2612 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2613 packet_put_int(remote_id);
2614 packet_put_int(c->self);
2619 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2621 deny_input_open(int type, u_int32_t seq, void *ctxt)
2623 int rchan = packet_get_int();
2626 case SSH_SMSG_AGENT_OPEN:
2627 error("Warning: ssh server tried agent forwarding.");
2629 case SSH_SMSG_X11_OPEN:
2630 error("Warning: ssh server tried X11 forwarding.");
2633 error("deny_input_open: type %d", type);
2636 error("Warning: this is probably a break in attempt by a malicious server.");
2637 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2638 packet_put_int(rchan);
2643 * Requests forwarding of X11 connections, generates fake authentication
2644 * data, and enables authentication spoofing.
2645 * This should be called in the client only.
2648 x11_request_forwarding_with_spoofing(int client_session_id,
2649 const char *proto, const char *data)
2651 u_int data_len = (u_int) strlen(data) / 2;
2652 u_int i, value, len;
2658 cp = getenv("DISPLAY");
2660 cp = strchr(cp, ':');
2662 cp = strchr(cp, '.');
2664 screen_number = atoi(cp + 1);
2668 /* Save protocol name. */
2669 x11_saved_proto = xstrdup(proto);
2672 * Extract real authentication data and generate fake data of the
2675 x11_saved_data = xmalloc(data_len);
2676 x11_fake_data = xmalloc(data_len);
2677 for (i = 0; i < data_len; i++) {
2678 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2679 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2681 rand = arc4random();
2682 x11_saved_data[i] = value;
2683 x11_fake_data[i] = rand & 0xff;
2686 x11_saved_data_len = data_len;
2687 x11_fake_data_len = data_len;
2689 /* Convert the fake data into hex. */
2690 len = 2 * data_len + 1;
2691 new_data = xmalloc(len);
2692 for (i = 0; i < data_len; i++)
2693 snprintf(new_data + 2 * i, len - 2 * i,
2694 "%02x", (u_char) x11_fake_data[i]);
2696 /* Send the request packet. */
2698 channel_request_start(client_session_id, "x11-req", 0);
2699 packet_put_char(0); /* XXX bool single connection */
2701 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2703 packet_put_cstring(proto);
2704 packet_put_cstring(new_data);
2705 packet_put_int(screen_number);
2707 packet_write_wait();
2712 /* -- agent forwarding */
2714 /* Sends a message to the server to request authentication fd forwarding. */
2717 auth_request_forwarding(void)
2719 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2721 packet_write_wait();
2724 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2727 auth_input_open_request(int type, u_int32_t seq, void *ctxt)
2730 int remote_id, sock;
2733 /* Read the remote channel number from the message. */
2734 remote_id = packet_get_int();
2738 * Get a connection to the local authentication agent (this may again
2741 sock = ssh_get_authentication_socket();
2744 * If we could not connect the agent, send an error message back to
2745 * the server. This should never happen unless the agent dies,
2746 * because authentication forwarding is only enabled if we have an
2750 name = xstrdup("authentication agent connection");
2751 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock,
2752 -1, 0, 0, 0, name, 1);
2753 c->remote_id = remote_id;
2757 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2758 packet_put_int(remote_id);
2760 /* Send a confirmation to the remote host. */
2761 debug("Forwarding authentication connection.");
2762 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2763 packet_put_int(remote_id);
2764 packet_put_int(c->self);