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".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999,2000 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 RCSID("$OpenBSD: channels.c,v 1.118 2001/05/28 23:14:49 markus Exp $");
45 #include <openssl/rsa.h>
46 #include <openssl/dsa.h>
65 /* Maximum number of fake X11 displays to try. */
66 #define MAX_DISPLAYS 1000
68 /* Max len of agent socket */
69 #define MAX_SOCKET_NAME 100
72 * Pointer to an array containing all allocated channels. The array is
73 * dynamically extended as needed.
75 static Channel **channels = NULL;
78 * Size of the channel array. All slots of the array must always be
79 * initialized (at least the type field); unused slots set to NULL
81 static int channels_alloc = 0;
84 * Maximum file descriptor value used in any of the channels. This is
85 * updated in channel_new.
87 static int channel_max_fd = 0;
89 /* Name and directory of socket for authentication agent forwarding. */
90 static char *channel_forwarded_auth_socket_name = NULL;
91 static char *channel_forwarded_auth_socket_dir = NULL;
93 /* Saved X11 authentication protocol name. */
94 char *x11_saved_proto = NULL;
96 /* Saved X11 authentication data. This is the real data. */
97 char *x11_saved_data = NULL;
98 u_int x11_saved_data_len = 0;
101 * Fake X11 authentication data. This is what the server will be sending us;
102 * we should replace any occurrences of this by the real data.
104 char *x11_fake_data = NULL;
105 u_int x11_fake_data_len;
108 * Data structure for storing which hosts are permitted for forward requests.
109 * The local sides of any remote forwards are stored in this array to prevent
110 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
111 * network (which might be behind a firewall).
114 char *host_to_connect; /* Connect to 'host'. */
115 u_short port_to_connect; /* Connect to 'port'. */
116 u_short listen_port; /* Remote side should listen port number. */
119 /* List of all permitted host/port pairs to connect. */
120 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
121 /* Number of permitted host/port pairs in the array. */
122 static int num_permitted_opens = 0;
124 * If this is true, all opens are permitted. This is the case on the server
125 * on which we have to trust the client anyway, and the user could do
126 * anything after logging in anyway.
128 static int all_opens_permitted = 0;
130 /* This is set to true if both sides support SSH_PROTOFLAG_HOST_IN_FWD_OPEN. */
131 static int have_hostname_in_open = 0;
133 /* AF_UNSPEC or AF_INET or AF_INET6 */
136 void port_open_helper(Channel *c, char *rtype);
138 /* Sets specific protocol options. */
141 channel_set_options(int hostname_in_open)
143 have_hostname_in_open = hostname_in_open;
146 /* lookup channel by id */
149 channel_lookup(int id)
153 if (id < 0 || id > channels_alloc) {
154 log("channel_lookup: %d: bad id", id);
159 log("channel_lookup: %d: bad id: channel free", id);
166 * Register filedescriptors for a channel, used when allocating a channel or
167 * when the channel consumer/producer is ready, e.g. shell exec'd
171 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
172 int extusage, int nonblock)
174 /* Update the maximum file descriptor value. */
175 channel_max_fd = MAX(channel_max_fd, rfd);
176 channel_max_fd = MAX(channel_max_fd, wfd);
177 channel_max_fd = MAX(channel_max_fd, efd);
179 /* XXX set close-on-exec -markus */
183 c->sock = (rfd == wfd) ? rfd : -1;
185 c->extended_usage = extusage;
187 /* XXX ugly hack: nonblock is only set by the server */
188 if (nonblock && isatty(c->rfd)) {
189 debug("channel %d: rfd %d isatty", c->self, c->rfd);
191 if (!isatty(c->wfd)) {
192 error("channel %d: wfd %d is not a tty?",
199 /* enable nonblocking mode */
211 * Allocate a new channel object and set its type and socket. This will cause
212 * remote_name to be freed.
216 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
217 int window, int maxpack, int extusage, char *remote_name, int nonblock)
222 /* Do initial allocation if this is the first call. */
223 if (channels_alloc == 0) {
226 channels = xmalloc(channels_alloc * sizeof(Channel *));
227 for (i = 0; i < channels_alloc; i++)
230 * Kludge: arrange a call to channel_stop_listening if we
231 * terminate with fatal().
233 fatal_add_cleanup((void (*) (void *)) channel_stop_listening, NULL);
235 /* Try to find a free slot where to put the new channel. */
236 for (found = -1, i = 0; i < channels_alloc; i++)
237 if (channels[i] == NULL) {
238 /* Found a free slot. */
243 /* There are no free slots. Take last+1 slot and expand the array. */
244 found = channels_alloc;
245 channels_alloc += 10;
246 debug2("channel: expanding %d", channels_alloc);
247 channels = xrealloc(channels, channels_alloc * sizeof(Channel *));
248 for (i = found; i < channels_alloc; i++)
251 /* Initialize and return new channel. */
252 c = channels[found] = xmalloc(sizeof(Channel));
253 buffer_init(&c->input);
254 buffer_init(&c->output);
255 buffer_init(&c->extended);
256 chan_init_iostates(c);
257 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
261 c->local_window = window;
262 c->local_window_max = window;
263 c->local_consumed = 0;
264 c->local_maxpacket = maxpack;
266 c->remote_name = remote_name;
267 c->remote_window = 0;
268 c->remote_maxpacket = 0;
272 c->dettach_user = NULL;
273 c->input_filter = NULL;
274 debug("channel %d: new [%s]", found, remote_name);
278 /* Close all channel fd/socket. */
281 channel_close_fds(Channel *c)
283 debug3("channel_close_fds: channel %d: r %d w %d e %d",
284 c->self, c->rfd, c->wfd, c->efd);
304 /* Free the channel and close its fd/socket. */
307 channel_free(Channel *c)
312 for (n = 0, i = 0; i < channels_alloc; i++)
316 debug("channel_free: channel %d: (%s) nchannels: %d", c->self,
317 c->remote_name ? c->remote_name : "???", n);
319 s = channel_open_message();
320 debug3("channel_free: status: %s", c->self, s);
323 if (c->dettach_user != NULL) {
324 debug("channel_free: channel %d: dettaching channel user", c->self);
325 c->dettach_user(c->self, NULL);
328 shutdown(c->sock, SHUT_RDWR);
329 channel_close_fds(c);
330 buffer_free(&c->input);
331 buffer_free(&c->output);
332 buffer_free(&c->extended);
333 if (c->remote_name) {
334 xfree(c->remote_name);
335 c->remote_name = NULL;
337 channels[c->self] = NULL;
342 * 'channel_pre*' are called just before select() to add any bits relevant to
343 * channels in the select bitmasks.
346 * 'channel_post*': perform any appropriate operations for channels which
347 * have events pending.
349 typedef void chan_fn(Channel *c, fd_set * readset, fd_set * writeset);
350 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
351 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
354 channel_pre_listener(Channel *c, fd_set * readset, fd_set * writeset)
356 FD_SET(c->sock, readset);
360 channel_pre_connecting(Channel *c, fd_set * readset, fd_set * writeset)
362 debug3("channel %d: waiting for connection", c->self);
363 FD_SET(c->sock, writeset);
367 channel_pre_open_13(Channel *c, fd_set * readset, fd_set * writeset)
369 if (buffer_len(&c->input) < packet_get_maxsize())
370 FD_SET(c->sock, readset);
371 if (buffer_len(&c->output) > 0)
372 FD_SET(c->sock, writeset);
376 channel_pre_open_15(Channel *c, fd_set * readset, fd_set * writeset)
378 /* test whether sockets are 'alive' for read/write */
379 if (c->istate == CHAN_INPUT_OPEN)
380 if (buffer_len(&c->input) < packet_get_maxsize())
381 FD_SET(c->sock, readset);
382 if (c->ostate == CHAN_OUTPUT_OPEN ||
383 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
384 if (buffer_len(&c->output) > 0) {
385 FD_SET(c->sock, writeset);
386 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
393 channel_pre_open_20(Channel *c, fd_set * readset, fd_set * writeset)
395 if (c->istate == CHAN_INPUT_OPEN &&
396 c->remote_window > 0 &&
397 buffer_len(&c->input) < c->remote_window)
398 FD_SET(c->rfd, readset);
399 if (c->ostate == CHAN_OUTPUT_OPEN ||
400 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
401 if (buffer_len(&c->output) > 0) {
402 FD_SET(c->wfd, writeset);
403 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
407 /** XXX check close conditions, too */
409 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
410 buffer_len(&c->extended) > 0)
411 FD_SET(c->efd, writeset);
412 else if (c->extended_usage == CHAN_EXTENDED_READ &&
413 buffer_len(&c->extended) < c->remote_window)
414 FD_SET(c->efd, readset);
419 channel_pre_input_draining(Channel *c, fd_set * readset, fd_set * writeset)
421 if (buffer_len(&c->input) == 0) {
422 packet_start(SSH_MSG_CHANNEL_CLOSE);
423 packet_put_int(c->remote_id);
425 c->type = SSH_CHANNEL_CLOSED;
426 debug("channel %d: closing after input drain.", c->self);
431 channel_pre_output_draining(Channel *c, fd_set * readset, fd_set * writeset)
433 if (buffer_len(&c->output) == 0)
436 FD_SET(c->sock, writeset);
440 * This is a special state for X11 authentication spoofing. An opened X11
441 * connection (when authentication spoofing is being done) remains in this
442 * state until the first packet has been completely read. The authentication
443 * data in that packet is then substituted by the real data if it matches the
444 * fake data, and the channel is put into normal mode.
445 * XXX All this happens at the client side.
448 x11_open_helper(Channel *c)
451 u_int proto_len, data_len;
453 /* Check if the fixed size part of the packet is in buffer. */
454 if (buffer_len(&c->output) < 12)
457 /* Parse the lengths of variable-length fields. */
458 ucp = (u_char *) buffer_ptr(&c->output);
459 if (ucp[0] == 0x42) { /* Byte order MSB first. */
460 proto_len = 256 * ucp[6] + ucp[7];
461 data_len = 256 * ucp[8] + ucp[9];
462 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
463 proto_len = ucp[6] + 256 * ucp[7];
464 data_len = ucp[8] + 256 * ucp[9];
466 debug("Initial X11 packet contains bad byte order byte: 0x%x",
471 /* Check if the whole packet is in buffer. */
472 if (buffer_len(&c->output) <
473 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
476 /* Check if authentication protocol matches. */
477 if (proto_len != strlen(x11_saved_proto) ||
478 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
479 debug("X11 connection uses different authentication protocol.");
482 /* Check if authentication data matches our fake data. */
483 if (data_len != x11_fake_data_len ||
484 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
485 x11_fake_data, x11_fake_data_len) != 0) {
486 debug("X11 auth data does not match fake data.");
489 /* Check fake data length */
490 if (x11_fake_data_len != x11_saved_data_len) {
491 error("X11 fake_data_len %d != saved_data_len %d",
492 x11_fake_data_len, x11_saved_data_len);
496 * Received authentication protocol and data match
497 * our fake data. Substitute the fake data with real
500 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
501 x11_saved_data, x11_saved_data_len);
506 channel_pre_x11_open_13(Channel *c, fd_set * readset, fd_set * writeset)
508 int ret = x11_open_helper(c);
510 /* Start normal processing for the channel. */
511 c->type = SSH_CHANNEL_OPEN;
512 channel_pre_open_13(c, readset, writeset);
513 } else if (ret == -1) {
515 * We have received an X11 connection that has bad
516 * authentication information.
518 log("X11 connection rejected because of wrong authentication.");
519 buffer_clear(&c->input);
520 buffer_clear(&c->output);
523 c->type = SSH_CHANNEL_CLOSED;
524 packet_start(SSH_MSG_CHANNEL_CLOSE);
525 packet_put_int(c->remote_id);
531 channel_pre_x11_open(Channel *c, fd_set * readset, fd_set * writeset)
533 int ret = x11_open_helper(c);
535 c->type = SSH_CHANNEL_OPEN;
537 channel_pre_open_20(c, readset, writeset);
539 channel_pre_open_15(c, readset, writeset);
540 } else if (ret == -1) {
541 debug("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
542 chan_read_failed(c); /** force close? */
543 chan_write_failed(c);
544 debug("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
548 /* try to decode a socks4 header */
550 channel_decode_socks4(Channel *c, fd_set * readset, fd_set * writeset)
553 int len, have, i, found;
559 struct in_addr dest_addr;
562 debug2("channel %d: decode socks4", c->self);
564 have = buffer_len(&c->input);
565 len = sizeof(s4_req);
568 p = buffer_ptr(&c->input);
569 for (found = 0, i = len; i < have; i++) {
575 /* the peer is probably sending garbage */
576 debug("channel %d: decode socks4: too long",
583 buffer_get(&c->input, (char *)&s4_req.version, 1);
584 buffer_get(&c->input, (char *)&s4_req.command, 1);
585 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
586 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
587 have = buffer_len(&c->input);
588 p = buffer_ptr(&c->input);
590 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
592 fatal("channel %d: decode socks4: len %d > have %d",
594 strlcpy(username, p, sizeof(username));
595 buffer_consume(&c->input, len);
596 buffer_consume(&c->input, 1); /* trailing '\0' */
598 host = inet_ntoa(s4_req.dest_addr);
599 strlcpy(c->path, host, sizeof(c->path));
600 c->host_port = ntohs(s4_req.dest_port);
602 debug("channel %d: dynamic request: socks4 host %s port %u command %u",
603 c->self, host, c->host_port, s4_req.command);
605 if (s4_req.command != 1) {
606 debug("channel %d: cannot handle: socks4 cn %d",
607 c->self, s4_req.command);
610 s4_rsp.version = 0; /* vn: 0 for reply */
611 s4_rsp.command = 90; /* cd: req granted */
612 s4_rsp.dest_port = 0; /* ignored */
613 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
614 buffer_append(&c->output, (char *)&s4_rsp, sizeof(s4_rsp));
618 /* dynamic port forwarding */
620 channel_pre_dynamic(Channel *c, fd_set * readset, fd_set * writeset)
625 have = buffer_len(&c->input);
627 debug2("channel %d: pre_dynamic: have %d", c->self, have);
628 /* buffer_dump(&c->input); */
629 /* check if the fixed size part of the packet is in buffer. */
632 FD_SET(c->sock, readset);
635 /* try to guess the protocol */
636 p = buffer_ptr(&c->input);
639 ret = channel_decode_socks4(c, readset, writeset);
647 } else if (ret == 0) {
648 debug2("channel %d: pre_dynamic: need more", c->self);
650 FD_SET(c->sock, readset);
652 /* switch to the next state */
653 c->type = SSH_CHANNEL_OPENING;
654 port_open_helper(c, "direct-tcpip");
658 /* This is our fake X11 server socket. */
660 channel_post_x11_listener(Channel *c, fd_set * readset, fd_set * writeset)
663 struct sockaddr addr;
666 char buf[16384], *remote_ipaddr;
669 if (FD_ISSET(c->sock, readset)) {
670 debug("X11 connection requested.");
671 addrlen = sizeof(addr);
672 newsock = accept(c->sock, &addr, &addrlen);
674 error("accept: %.100s", strerror(errno));
677 remote_ipaddr = get_peer_ipaddr(newsock);
678 remote_port = get_peer_port(newsock);
679 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
680 remote_ipaddr, remote_port);
682 nc = channel_new("accepted x11 socket",
683 SSH_CHANNEL_OPENING, newsock, newsock, -1,
684 c->local_window_max, c->local_maxpacket,
688 xfree(remote_ipaddr);
692 packet_start(SSH2_MSG_CHANNEL_OPEN);
693 packet_put_cstring("x11");
694 packet_put_int(nc->self);
695 packet_put_int(c->local_window_max);
696 packet_put_int(c->local_maxpacket);
697 /* originator ipaddr and port */
698 packet_put_cstring(remote_ipaddr);
699 if (datafellows & SSH_BUG_X11FWD) {
700 debug("ssh2 x11 bug compat mode");
702 packet_put_int(remote_port);
706 packet_start(SSH_SMSG_X11_OPEN);
707 packet_put_int(nc->self);
708 if (have_hostname_in_open)
709 packet_put_string(buf, strlen(buf));
712 xfree(remote_ipaddr);
717 port_open_helper(Channel *c, char *rtype)
721 char *remote_ipaddr = get_peer_ipaddr(c->sock);
722 u_short remote_port = get_peer_port(c->sock);
724 direct = (strcmp(rtype, "direct-tcpip") == 0);
726 snprintf(buf, sizeof buf,
727 "%s: listening port %d for %.100s port %d, "
728 "connect from %.200s port %d",
729 rtype, c->listening_port, c->path, c->host_port,
730 remote_ipaddr, remote_port);
732 xfree(c->remote_name);
733 c->remote_name = xstrdup(buf);
736 packet_start(SSH2_MSG_CHANNEL_OPEN);
737 packet_put_cstring(rtype);
738 packet_put_int(c->self);
739 packet_put_int(c->local_window_max);
740 packet_put_int(c->local_maxpacket);
742 /* target host, port */
743 packet_put_cstring(c->path);
744 packet_put_int(c->host_port);
746 /* listen address, port */
747 packet_put_cstring(c->path);
748 packet_put_int(c->listening_port);
750 /* originator host and port */
751 packet_put_cstring(remote_ipaddr);
752 packet_put_int(remote_port);
755 packet_start(SSH_MSG_PORT_OPEN);
756 packet_put_int(c->self);
757 packet_put_cstring(c->path);
758 packet_put_int(c->host_port);
759 if (have_hostname_in_open)
760 packet_put_cstring(c->remote_name);
763 xfree(remote_ipaddr);
767 * This socket is listening for connections to a forwarded TCP/IP port.
770 channel_post_port_listener(Channel *c, fd_set * readset, fd_set * writeset)
773 struct sockaddr addr;
774 int newsock, nextstate;
778 if (FD_ISSET(c->sock, readset)) {
779 debug("Connection to port %d forwarding "
780 "to %.100s port %d requested.",
781 c->listening_port, c->path, c->host_port);
783 rtype = (c->type == SSH_CHANNEL_RPORT_LISTENER) ?
784 "forwarded-tcpip" : "direct-tcpip";
785 nextstate = (c->host_port == 0 &&
786 c->type != SSH_CHANNEL_RPORT_LISTENER) ?
787 SSH_CHANNEL_DYNAMIC : SSH_CHANNEL_OPENING;
789 addrlen = sizeof(addr);
790 newsock = accept(c->sock, &addr, &addrlen);
792 error("accept: %.100s", strerror(errno));
795 nc = channel_new(rtype,
796 nextstate, newsock, newsock, -1,
797 c->local_window_max, c->local_maxpacket,
798 0, xstrdup(rtype), 1);
800 error("channel_post_port_listener: no new channel:");
804 nc->listening_port = c->listening_port;
805 nc->host_port = c->host_port;
806 strlcpy(nc->path, c->path, sizeof(nc->path));
808 if (nextstate != SSH_CHANNEL_DYNAMIC)
809 port_open_helper(nc, rtype);
814 * This is the authentication agent socket listening for connections from
818 channel_post_auth_listener(Channel *c, fd_set * readset, fd_set * writeset)
822 struct sockaddr addr;
825 if (FD_ISSET(c->sock, readset)) {
826 addrlen = sizeof(addr);
827 newsock = accept(c->sock, &addr, &addrlen);
829 error("accept from auth socket: %.100s", strerror(errno));
832 nc = channel_new("accepted auth socket",
833 SSH_CHANNEL_OPENING, newsock, newsock, -1,
834 c->local_window_max, c->local_maxpacket,
835 0, xstrdup("accepted auth socket"), 1);
837 error("channel_post_auth_listener: channel_new failed");
841 packet_start(SSH2_MSG_CHANNEL_OPEN);
842 packet_put_cstring("auth-agent@openssh.com");
843 packet_put_int(nc->self);
844 packet_put_int(c->local_window_max);
845 packet_put_int(c->local_maxpacket);
847 packet_start(SSH_SMSG_AGENT_OPEN);
848 packet_put_int(nc->self);
855 channel_post_connecting(Channel *c, fd_set * readset, fd_set * writeset)
858 int sz = sizeof(err);
860 if (FD_ISSET(c->sock, writeset)) {
861 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, (char *)&err,
864 error("getsockopt SO_ERROR failed");
867 debug("channel %d: connected", c->self);
868 c->type = SSH_CHANNEL_OPEN;
870 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
871 packet_put_int(c->remote_id);
872 packet_put_int(c->self);
873 packet_put_int(c->local_window);
874 packet_put_int(c->local_maxpacket);
876 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
877 packet_put_int(c->remote_id);
878 packet_put_int(c->self);
881 debug("channel %d: not connected: %s",
882 c->self, strerror(err));
884 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
885 packet_put_int(c->remote_id);
886 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
887 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
888 packet_put_cstring(strerror(err));
889 packet_put_cstring("");
892 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
893 packet_put_int(c->remote_id);
902 channel_handle_rfd(Channel *c, fd_set * readset, fd_set * writeset)
908 FD_ISSET(c->rfd, readset)) {
909 len = read(c->rfd, buf, sizeof(buf));
910 if (len < 0 && (errno == EINTR || errno == EAGAIN))
913 debug("channel %d: read<=0 rfd %d len %d",
914 c->self, c->rfd, len);
915 if (c->type != SSH_CHANNEL_OPEN) {
916 debug("channel %d: not open", c->self);
919 } else if (compat13) {
920 buffer_consume(&c->output, buffer_len(&c->output));
921 c->type = SSH_CHANNEL_INPUT_DRAINING;
922 debug("channel %d: status set to input draining.", c->self);
928 if(c->input_filter != NULL) {
929 if (c->input_filter(c, buf, len) == -1) {
930 debug("channel %d: filter stops", c->self);
934 buffer_append(&c->input, buf, len);
940 channel_handle_wfd(Channel *c, fd_set * readset, fd_set * writeset)
945 /* Send buffered output data to the socket. */
947 FD_ISSET(c->wfd, writeset) &&
948 buffer_len(&c->output) > 0) {
949 len = write(c->wfd, buffer_ptr(&c->output),
950 buffer_len(&c->output));
951 if (len < 0 && (errno == EINTR || errno == EAGAIN))
954 if (c->type != SSH_CHANNEL_OPEN) {
955 debug("channel %d: not open", c->self);
958 } else if (compat13) {
959 buffer_consume(&c->output, buffer_len(&c->output));
960 debug("channel %d: status set to input draining.", c->self);
961 c->type = SSH_CHANNEL_INPUT_DRAINING;
963 chan_write_failed(c);
967 if (compat20 && c->isatty) {
968 if (tcgetattr(c->wfd, &tio) == 0 &&
969 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
971 * Simulate echo to reduce the impact of
972 * traffic analysis. We need to match the
973 * size of a SSH2_MSG_CHANNEL_DATA message
974 * (4 byte channel id + data)
976 packet_send_ignore(4 + len);
980 buffer_consume(&c->output, len);
981 if (compat20 && len > 0) {
982 c->local_consumed += len;
988 channel_handle_efd(Channel *c, fd_set * readset, fd_set * writeset)
993 /** XXX handle drain efd, too */
995 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
996 FD_ISSET(c->efd, writeset) &&
997 buffer_len(&c->extended) > 0) {
998 len = write(c->efd, buffer_ptr(&c->extended),
999 buffer_len(&c->extended));
1000 debug2("channel %d: written %d to efd %d",
1001 c->self, len, c->efd);
1002 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1005 debug2("channel %d: closing write-efd %d",
1010 buffer_consume(&c->extended, len);
1011 c->local_consumed += len;
1013 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1014 FD_ISSET(c->efd, readset)) {
1015 len = read(c->efd, buf, sizeof(buf));
1016 debug2("channel %d: read %d from efd %d",
1017 c->self, len, c->efd);
1018 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1021 debug2("channel %d: closing read-efd %d",
1026 buffer_append(&c->extended, buf, len);
1033 channel_check_window(Channel *c)
1035 if (c->type == SSH_CHANNEL_OPEN &&
1036 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1037 c->local_window < c->local_window_max/2 &&
1038 c->local_consumed > 0) {
1039 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1040 packet_put_int(c->remote_id);
1041 packet_put_int(c->local_consumed);
1043 debug2("channel %d: window %d sent adjust %d",
1044 c->self, c->local_window,
1046 c->local_window += c->local_consumed;
1047 c->local_consumed = 0;
1053 channel_post_open_1(Channel *c, fd_set * readset, fd_set * writeset)
1055 channel_handle_rfd(c, readset, writeset);
1056 channel_handle_wfd(c, readset, writeset);
1060 channel_post_open_2(Channel *c, fd_set * readset, fd_set * writeset)
1062 channel_handle_rfd(c, readset, writeset);
1063 channel_handle_wfd(c, readset, writeset);
1064 channel_handle_efd(c, readset, writeset);
1066 channel_check_window(c);
1070 channel_post_output_drain_13(Channel *c, fd_set * readset, fd_set * writeset)
1073 /* Send buffered output data to the socket. */
1074 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1075 len = write(c->sock, buffer_ptr(&c->output),
1076 buffer_len(&c->output));
1078 buffer_consume(&c->output, buffer_len(&c->output));
1080 buffer_consume(&c->output, len);
1085 channel_handler_init_20(void)
1087 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_20;
1088 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1089 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1090 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1091 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1092 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1093 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1094 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1096 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_2;
1097 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1098 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1099 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1100 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1101 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1102 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open_2;
1106 channel_handler_init_13(void)
1108 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1109 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1110 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1111 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1112 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1113 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1114 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1115 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1116 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1118 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
1119 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1120 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1121 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1122 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1123 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1124 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open_1;
1128 channel_handler_init_15(void)
1130 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_15;
1131 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1132 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1133 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1134 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1135 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1136 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1138 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1139 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1140 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1141 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open_1;
1142 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1143 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open_1;
1147 channel_handler_init(void)
1150 for(i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1151 channel_pre[i] = NULL;
1152 channel_post[i] = NULL;
1155 channel_handler_init_20();
1157 channel_handler_init_13();
1159 channel_handler_init_15();
1163 channel_handler(chan_fn *ftab[], fd_set * readset, fd_set * writeset)
1165 static int did_init = 0;
1170 channel_handler_init();
1173 for (i = 0; i < channels_alloc; i++) {
1177 if (ftab[c->type] != NULL)
1178 (*ftab[c->type])(c, readset, writeset);
1179 if (chan_is_dead(c)) {
1181 * we have to remove the fd's from the select mask
1182 * before the channels are free'd and the fd's are
1186 FD_CLR(c->wfd, writeset);
1188 FD_CLR(c->rfd, readset);
1190 if (c->extended_usage == CHAN_EXTENDED_READ)
1191 FD_CLR(c->efd, readset);
1192 if (c->extended_usage == CHAN_EXTENDED_WRITE)
1193 FD_CLR(c->efd, writeset);
1201 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1207 n = MAX(*maxfdp, channel_max_fd);
1209 sz = howmany(n+1, NFDBITS) * sizeof(fd_mask);
1210 if (*readsetp == NULL || n > *maxfdp) {
1215 *readsetp = xmalloc(sz);
1216 *writesetp = xmalloc(sz);
1219 memset(*readsetp, 0, sz);
1220 memset(*writesetp, 0, sz);
1223 channel_handler(channel_pre, *readsetp, *writesetp);
1227 channel_after_select(fd_set * readset, fd_set * writeset)
1229 channel_handler(channel_post, readset, writeset);
1232 /* If there is data to send to the connection, enqueue some of it now. */
1235 channel_output_poll()
1240 for (i = 0; i < channels_alloc; i++) {
1246 /* We are only interested in channels that can have buffered incoming data. */
1248 if (c->type != SSH_CHANNEL_OPEN &&
1249 c->type != SSH_CHANNEL_INPUT_DRAINING)
1252 if (c->type != SSH_CHANNEL_OPEN)
1256 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1257 /* XXX is this true? */
1258 debug2("channel %d: no data after CLOSE", c->self);
1262 /* Get the amount of buffered data for this channel. */
1263 if ((c->istate == CHAN_INPUT_OPEN ||
1264 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1265 (len = buffer_len(&c->input)) > 0) {
1266 /* Send some data for the other side over the secure connection. */
1268 if (len > c->remote_window)
1269 len = c->remote_window;
1270 if (len > c->remote_maxpacket)
1271 len = c->remote_maxpacket;
1273 if (packet_is_interactive()) {
1277 /* Keep the packets at reasonable size. */
1278 if (len > packet_get_maxsize()/2)
1279 len = packet_get_maxsize()/2;
1283 packet_start(compat20 ?
1284 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1285 packet_put_int(c->remote_id);
1286 packet_put_string(buffer_ptr(&c->input), len);
1288 buffer_consume(&c->input, len);
1289 c->remote_window -= len;
1291 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1293 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1295 * input-buffer is empty and read-socket shutdown:
1296 * tell peer, that we will not send more data: send IEOF
1300 /* Send extended data, i.e. stderr */
1302 c->remote_window > 0 &&
1303 (len = buffer_len(&c->extended)) > 0 &&
1304 c->extended_usage == CHAN_EXTENDED_READ) {
1305 debug2("channel %d: rwin %d elen %d euse %d",
1306 c->self, c->remote_window, buffer_len(&c->extended),
1308 if (len > c->remote_window)
1309 len = c->remote_window;
1310 if (len > c->remote_maxpacket)
1311 len = c->remote_maxpacket;
1312 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1313 packet_put_int(c->remote_id);
1314 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1315 packet_put_string(buffer_ptr(&c->extended), len);
1317 buffer_consume(&c->extended, len);
1318 c->remote_window -= len;
1319 debug2("channel %d: sent ext data %d", c->self, len);
1325 * This is called when a packet of type CHANNEL_DATA has just been received.
1326 * The message type has already been consumed, but channel number and data is
1331 channel_input_data(int type, int plen, void *ctxt)
1338 /* Get the channel number and verify it. */
1339 id = packet_get_int();
1340 c = channel_lookup(id);
1342 packet_disconnect("Received data for nonexistent channel %d.", id);
1344 /* Ignore any data for non-open channels (might happen on close) */
1345 if (c->type != SSH_CHANNEL_OPEN &&
1346 c->type != SSH_CHANNEL_X11_OPEN)
1349 /* same for protocol 1.5 if output end is no longer open */
1350 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN)
1354 data = packet_get_string(&data_len);
1358 if (data_len > c->local_maxpacket) {
1359 log("channel %d: rcvd big packet %d, maxpack %d",
1360 c->self, data_len, c->local_maxpacket);
1362 if (data_len > c->local_window) {
1363 log("channel %d: rcvd too much data %d, win %d",
1364 c->self, data_len, c->local_window);
1368 c->local_window -= data_len;
1370 packet_integrity_check(plen, 4 + 4 + data_len, type);
1372 buffer_append(&c->output, data, data_len);
1376 channel_input_extended_data(int type, int plen, void *ctxt)
1384 /* Get the channel number and verify it. */
1385 id = packet_get_int();
1386 c = channel_lookup(id);
1389 packet_disconnect("Received extended_data for bad channel %d.", id);
1390 if (c->type != SSH_CHANNEL_OPEN) {
1391 log("channel %d: ext data for non open", id);
1394 tcode = packet_get_int();
1396 c->extended_usage != CHAN_EXTENDED_WRITE ||
1397 tcode != SSH2_EXTENDED_DATA_STDERR) {
1398 log("channel %d: bad ext data", c->self);
1401 data = packet_get_string(&data_len);
1403 if (data_len > c->local_window) {
1404 log("channel %d: rcvd too much extended_data %d, win %d",
1405 c->self, data_len, c->local_window);
1409 debug2("channel %d: rcvd ext data %d", c->self, data_len);
1410 c->local_window -= data_len;
1411 buffer_append(&c->extended, data, data_len);
1417 * Returns true if no channel has too much buffered data, and false if one or
1418 * more channel is overfull.
1422 channel_not_very_much_buffered_data()
1427 for (i = 0; i < channels_alloc; i++) {
1429 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
1430 if (!compat20 && buffer_len(&c->input) > packet_get_maxsize()) {
1431 debug("channel %d: big input buffer %d",
1432 c->self, buffer_len(&c->input));
1435 if (buffer_len(&c->output) > packet_get_maxsize()) {
1436 debug("channel %d: big output buffer %d",
1437 c->self, buffer_len(&c->output));
1446 channel_input_ieof(int type, int plen, void *ctxt)
1451 packet_integrity_check(plen, 4, type);
1453 id = packet_get_int();
1454 c = channel_lookup(id);
1456 packet_disconnect("Received ieof for nonexistent channel %d.", id);
1461 channel_input_close(int type, int plen, void *ctxt)
1466 packet_integrity_check(plen, 4, type);
1468 id = packet_get_int();
1469 c = channel_lookup(id);
1471 packet_disconnect("Received close for nonexistent channel %d.", id);
1474 * Send a confirmation that we have closed the channel and no more
1475 * data is coming for it.
1477 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
1478 packet_put_int(c->remote_id);
1482 * If the channel is in closed state, we have sent a close request,
1483 * and the other side will eventually respond with a confirmation.
1484 * Thus, we cannot free the channel here, because then there would be
1485 * no-one to receive the confirmation. The channel gets freed when
1486 * the confirmation arrives.
1488 if (c->type != SSH_CHANNEL_CLOSED) {
1490 * Not a closed channel - mark it as draining, which will
1491 * cause it to be freed later.
1493 buffer_consume(&c->input, buffer_len(&c->input));
1494 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
1498 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
1500 channel_input_oclose(int type, int plen, void *ctxt)
1502 int id = packet_get_int();
1503 Channel *c = channel_lookup(id);
1504 packet_integrity_check(plen, 4, type);
1506 packet_disconnect("Received oclose for nonexistent channel %d.", id);
1507 chan_rcvd_oclose(c);
1511 channel_input_close_confirmation(int type, int plen, void *ctxt)
1513 int id = packet_get_int();
1514 Channel *c = channel_lookup(id);
1518 packet_disconnect("Received close confirmation for "
1519 "out-of-range channel %d.", id);
1520 if (c->type != SSH_CHANNEL_CLOSED)
1521 packet_disconnect("Received close confirmation for "
1522 "non-closed channel %d (type %d).", id, c->type);
1527 channel_input_open_confirmation(int type, int plen, void *ctxt)
1533 packet_integrity_check(plen, 4 + 4, type);
1535 id = packet_get_int();
1536 c = channel_lookup(id);
1538 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1539 packet_disconnect("Received open confirmation for "
1540 "non-opening channel %d.", id);
1541 remote_id = packet_get_int();
1542 /* Record the remote channel number and mark that the channel is now open. */
1543 c->remote_id = remote_id;
1544 c->type = SSH_CHANNEL_OPEN;
1547 c->remote_window = packet_get_int();
1548 c->remote_maxpacket = packet_get_int();
1550 if (c->cb_fn != NULL && c->cb_event == type) {
1551 debug2("callback start");
1552 c->cb_fn(c->self, c->cb_arg);
1553 debug2("callback done");
1555 debug("channel %d: open confirm rwindow %d rmax %d", c->self,
1556 c->remote_window, c->remote_maxpacket);
1561 reason2txt(int reason)
1564 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
1565 return "administratively prohibited";
1566 case SSH2_OPEN_CONNECT_FAILED:
1567 return "connect failed";
1568 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
1569 return "unknown channel type";
1570 case SSH2_OPEN_RESOURCE_SHORTAGE:
1571 return "resource shortage";
1573 return "unknown reason";
1577 channel_input_open_failure(int type, int plen, void *ctxt)
1580 char *msg = NULL, *lang = NULL;
1584 packet_integrity_check(plen, 4, type);
1586 id = packet_get_int();
1587 c = channel_lookup(id);
1589 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
1590 packet_disconnect("Received open failure for "
1591 "non-opening channel %d.", id);
1593 reason = packet_get_int();
1594 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1595 msg = packet_get_string(NULL);
1596 lang = packet_get_string(NULL);
1599 log("channel %d: open failed: %s%s%s", id,
1600 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
1606 /* Free the channel. This will also close the socket. */
1611 channel_input_channel_request(int type, int plen, void *ctxt)
1616 id = packet_get_int();
1617 c = channel_lookup(id);
1620 (c->type != SSH_CHANNEL_OPEN && c->type != SSH_CHANNEL_LARVAL))
1621 packet_disconnect("Received request for "
1622 "non-open channel %d.", id);
1623 if (c->cb_fn != NULL && c->cb_event == type) {
1624 debug2("callback start");
1625 c->cb_fn(c->self, c->cb_arg);
1626 debug2("callback done");
1628 char *service = packet_get_string(NULL);
1629 debug("channel %d: rcvd request for %s", c->self, service);
1630 debug("cb_fn %p cb_event %d", c->cb_fn , c->cb_event);
1636 channel_input_window_adjust(int type, int plen, void *ctxt)
1644 /* Get the channel number and verify it. */
1645 id = packet_get_int();
1646 c = channel_lookup(id);
1648 if (c == NULL || c->type != SSH_CHANNEL_OPEN) {
1649 log("Received window adjust for "
1650 "non-open channel %d.", id);
1653 adjust = packet_get_int();
1655 debug2("channel %d: rcvd adjust %d", id, adjust);
1656 c->remote_window += adjust;
1660 * Stops listening for channels, and removes any unix domain sockets that we
1665 channel_stop_listening()
1670 for (i = 0; i < channels_alloc; i++) {
1674 case SSH_CHANNEL_AUTH_SOCKET:
1679 case SSH_CHANNEL_PORT_LISTENER:
1680 case SSH_CHANNEL_RPORT_LISTENER:
1681 case SSH_CHANNEL_X11_LISTENER:
1693 * Closes the sockets/fds of all channels. This is used to close extra file
1694 * descriptors after a fork.
1702 for (i = 0; i < channels_alloc; i++)
1703 if (channels[i] != NULL)
1704 channel_close_fds(channels[i]);
1707 /* Returns true if any channel is still open. */
1710 channel_still_open()
1715 for (i = 0; i < channels_alloc; i++) {
1720 case SSH_CHANNEL_X11_LISTENER:
1721 case SSH_CHANNEL_PORT_LISTENER:
1722 case SSH_CHANNEL_RPORT_LISTENER:
1723 case SSH_CHANNEL_CLOSED:
1724 case SSH_CHANNEL_AUTH_SOCKET:
1725 case SSH_CHANNEL_DYNAMIC:
1726 case SSH_CHANNEL_CONNECTING:
1727 case SSH_CHANNEL_ZOMBIE:
1729 case SSH_CHANNEL_LARVAL:
1731 fatal("cannot happen: SSH_CHANNEL_LARVAL");
1733 case SSH_CHANNEL_OPENING:
1734 case SSH_CHANNEL_OPEN:
1735 case SSH_CHANNEL_X11_OPEN:
1737 case SSH_CHANNEL_INPUT_DRAINING:
1738 case SSH_CHANNEL_OUTPUT_DRAINING:
1740 fatal("cannot happen: OUT_DRAIN");
1743 fatal("channel_still_open: bad channel type %d", c->type);
1750 /* Returns the id of an open channel suitable for keepaliving */
1758 for (i = 0; i < channels_alloc; i++) {
1763 case SSH_CHANNEL_CLOSED:
1764 case SSH_CHANNEL_DYNAMIC:
1765 case SSH_CHANNEL_X11_LISTENER:
1766 case SSH_CHANNEL_PORT_LISTENER:
1767 case SSH_CHANNEL_RPORT_LISTENER:
1768 case SSH_CHANNEL_OPENING:
1769 case SSH_CHANNEL_CONNECTING:
1770 case SSH_CHANNEL_ZOMBIE:
1772 case SSH_CHANNEL_LARVAL:
1773 case SSH_CHANNEL_AUTH_SOCKET:
1774 case SSH_CHANNEL_OPEN:
1775 case SSH_CHANNEL_X11_OPEN:
1777 case SSH_CHANNEL_INPUT_DRAINING:
1778 case SSH_CHANNEL_OUTPUT_DRAINING:
1780 fatal("cannot happen: OUT_DRAIN");
1783 fatal("channel_find_open: bad channel type %d", c->type);
1792 * Returns a message describing the currently open forwarded connections,
1793 * suitable for sending to the client. The message contains crlf pairs for
1798 channel_open_message()
1802 char buf[1024], *cp;
1805 buffer_init(&buffer);
1806 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
1807 buffer_append(&buffer, buf, strlen(buf));
1808 for (i = 0; i < channels_alloc; i++) {
1813 case SSH_CHANNEL_X11_LISTENER:
1814 case SSH_CHANNEL_PORT_LISTENER:
1815 case SSH_CHANNEL_RPORT_LISTENER:
1816 case SSH_CHANNEL_CLOSED:
1817 case SSH_CHANNEL_AUTH_SOCKET:
1818 case SSH_CHANNEL_ZOMBIE:
1820 case SSH_CHANNEL_LARVAL:
1821 case SSH_CHANNEL_OPENING:
1822 case SSH_CHANNEL_CONNECTING:
1823 case SSH_CHANNEL_DYNAMIC:
1824 case SSH_CHANNEL_OPEN:
1825 case SSH_CHANNEL_X11_OPEN:
1826 case SSH_CHANNEL_INPUT_DRAINING:
1827 case SSH_CHANNEL_OUTPUT_DRAINING:
1828 snprintf(buf, sizeof buf, " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d)\r\n",
1829 c->self, c->remote_name,
1830 c->type, c->remote_id,
1831 c->istate, buffer_len(&c->input),
1832 c->ostate, buffer_len(&c->output),
1834 buffer_append(&buffer, buf, strlen(buf));
1837 fatal("channel_open_message: bad channel type %d", c->type);
1841 buffer_append(&buffer, "\0", 1);
1842 cp = xstrdup(buffer_ptr(&buffer));
1843 buffer_free(&buffer);
1848 * Initiate forwarding of connections to local port "port" through the secure
1849 * channel to host:port from remote side.
1852 channel_request_local_forwarding(u_short listen_port, const char *host_to_connect,
1853 u_short port_to_connect, int gateway_ports)
1855 return channel_request_forwarding(
1857 host_to_connect, port_to_connect,
1858 gateway_ports, /*remote_fwd*/ 0);
1862 * If 'remote_fwd' is true we have a '-R style' listener for protocol 2
1863 * (SSH_CHANNEL_RPORT_LISTENER).
1866 channel_request_forwarding(
1867 const char *listen_address, u_short listen_port,
1868 const char *host_to_connect, u_short port_to_connect,
1869 int gateway_ports, int remote_fwd)
1872 int success, sock, on = 1, ctype;
1873 struct addrinfo hints, *ai, *aitop;
1874 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1876 struct linger linger;
1881 host = listen_address;
1882 ctype = SSH_CHANNEL_RPORT_LISTENER;
1884 host = host_to_connect;
1885 ctype =SSH_CHANNEL_PORT_LISTENER;
1888 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
1889 error("Forward host name too long.");
1893 /* XXX listen_address is currently ignored */
1895 * getaddrinfo returns a loopback address if the hostname is
1896 * set to NULL and hints.ai_flags is not AI_PASSIVE
1898 memset(&hints, 0, sizeof(hints));
1899 hints.ai_family = IPv4or6;
1900 hints.ai_flags = gateway_ports ? AI_PASSIVE : 0;
1901 hints.ai_socktype = SOCK_STREAM;
1902 snprintf(strport, sizeof strport, "%d", listen_port);
1903 if (getaddrinfo(NULL, strport, &hints, &aitop) != 0)
1904 packet_disconnect("getaddrinfo: fatal error");
1906 for (ai = aitop; ai; ai = ai->ai_next) {
1907 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1909 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
1910 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
1911 error("channel_request_forwarding: getnameinfo failed");
1914 /* Create a port to listen for the host. */
1915 sock = socket(ai->ai_family, SOCK_STREAM, 0);
1917 /* this is no error since kernel may not support ipv6 */
1918 verbose("socket: %.100s", strerror(errno));
1922 * Set socket options. We would like the socket to disappear
1923 * as soon as it has been closed for whatever reason.
1925 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on));
1927 linger.l_linger = 5;
1928 setsockopt(sock, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
1929 debug("Local forwarding listening on %s port %s.", ntop, strport);
1931 /* Bind the socket to the address. */
1932 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1933 /* address can be in use ipv6 address is already bound */
1935 error("bind: %.100s", strerror(errno));
1937 verbose("bind: %.100s", strerror(errno));
1942 /* Start listening for connections on the socket. */
1943 if (listen(sock, 5) < 0) {
1944 error("listen: %.100s", strerror(errno));
1948 /* Allocate a channel number for the socket. */
1949 c = channel_new("port listener", ctype, sock, sock, -1,
1950 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1951 0, xstrdup("port listener"), 1);
1953 error("channel_request_forwarding: channel_new failed");
1957 strlcpy(c->path, host, sizeof(c->path));
1958 c->host_port = port_to_connect;
1959 c->listening_port = listen_port;
1963 error("channel_request_forwarding: cannot listen to port: %d",
1965 freeaddrinfo(aitop);
1970 * Initiate forwarding of connections to port "port" on remote host through
1971 * the secure channel to host:port from local side.
1975 channel_request_remote_forwarding(u_short listen_port,
1976 const char *host_to_connect, u_short port_to_connect)
1978 int payload_len, type, success = 0;
1980 /* Record locally that connection to this host/port is permitted. */
1981 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
1982 fatal("channel_request_remote_forwarding: too many forwards");
1984 /* Send the forward request to the remote side. */
1986 const char *address_to_bind = "0.0.0.0";
1987 packet_start(SSH2_MSG_GLOBAL_REQUEST);
1988 packet_put_cstring("tcpip-forward");
1989 packet_put_char(0); /* boolean: want reply */
1990 packet_put_cstring(address_to_bind);
1991 packet_put_int(listen_port);
1993 packet_write_wait();
1994 /* Assume that server accepts the request */
1997 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
1998 packet_put_int(listen_port);
1999 packet_put_cstring(host_to_connect);
2000 packet_put_int(port_to_connect);
2002 packet_write_wait();
2004 /* Wait for response from the remote side. */
2005 type = packet_read(&payload_len);
2007 case SSH_SMSG_SUCCESS:
2010 case SSH_SMSG_FAILURE:
2011 log("Warning: Server denied remote port forwarding.");
2014 /* Unknown packet */
2015 packet_disconnect("Protocol error for port forward request:"
2016 "received packet type %d.", type);
2020 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2021 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2022 permitted_opens[num_permitted_opens].listen_port = listen_port;
2023 num_permitted_opens++;
2028 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2029 * listening for the port, and sends back a success reply (or disconnect
2030 * message if there was an error). This never returns if there was an error.
2034 channel_input_port_forward_request(int is_root, int gateway_ports)
2036 u_short port, host_port;
2039 /* Get arguments from the packet. */
2040 port = packet_get_int();
2041 hostname = packet_get_string(NULL);
2042 host_port = packet_get_int();
2046 * Check that an unprivileged user is not trying to forward a
2049 if (port < IPPORT_RESERVED && !is_root)
2050 packet_disconnect("Requested forwarding of port %d but user is not root.",
2053 /* Initiate forwarding */
2054 channel_request_local_forwarding(port, hostname, host_port, gateway_ports);
2056 /* Free the argument string. */
2061 * Permits opening to any host/port if permitted_opens[] is empty. This is
2062 * usually called by the server, because the user could connect to any port
2063 * anyway, and the server has no way to know but to trust the client anyway.
2066 channel_permit_all_opens()
2068 if (num_permitted_opens == 0)
2069 all_opens_permitted = 1;
2073 channel_add_permitted_opens(char *host, int port)
2075 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2076 fatal("channel_request_remote_forwarding: too many forwards");
2077 debug("allow port forwarding to host %s port %d", host, port);
2079 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2080 permitted_opens[num_permitted_opens].port_to_connect = port;
2081 num_permitted_opens++;
2083 all_opens_permitted = 0;
2087 channel_clear_permitted_opens(void)
2091 for (i = 0; i < num_permitted_opens; i++)
2092 xfree(permitted_opens[i].host_to_connect);
2093 num_permitted_opens = 0;
2098 /* return socket to remote host, port */
2100 connect_to(const char *host, u_short port)
2102 struct addrinfo hints, *ai, *aitop;
2103 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2107 memset(&hints, 0, sizeof(hints));
2108 hints.ai_family = IPv4or6;
2109 hints.ai_socktype = SOCK_STREAM;
2110 snprintf(strport, sizeof strport, "%d", port);
2111 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2112 error("connect_to %.100s: unknown host (%s)", host,
2113 gai_strerror(gaierr));
2116 for (ai = aitop; ai; ai = ai->ai_next) {
2117 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2119 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2120 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2121 error("connect_to: getnameinfo failed");
2124 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2126 error("socket: %.100s", strerror(errno));
2129 if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0)
2130 fatal("connect_to: F_SETFL: %s", strerror(errno));
2131 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2132 errno != EINPROGRESS) {
2133 error("connect_to %.100s port %s: %.100s", ntop, strport,
2136 continue; /* fail -- try next */
2138 break; /* success */
2141 freeaddrinfo(aitop);
2143 error("connect_to %.100s port %d: failed.", host, port);
2151 channel_connect_by_listen_adress(u_short listen_port)
2155 for (i = 0; i < num_permitted_opens; i++)
2156 if (permitted_opens[i].listen_port == listen_port)
2158 permitted_opens[i].host_to_connect,
2159 permitted_opens[i].port_to_connect);
2160 error("WARNING: Server requests forwarding for unknown listen_port %d",
2165 /* Check if connecting to that port is permitted and connect. */
2167 channel_connect_to(const char *host, u_short port)
2171 permit = all_opens_permitted;
2173 for (i = 0; i < num_permitted_opens; i++)
2174 if (permitted_opens[i].port_to_connect == port &&
2175 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2180 log("Received request to connect to host %.100s port %d, "
2181 "but the request was denied.", host, port);
2184 return connect_to(host, port);
2188 * This is called after receiving PORT_OPEN message. This attempts to
2189 * connect to the given host:port, and sends back CHANNEL_OPEN_CONFIRMATION
2190 * or CHANNEL_OPEN_FAILURE.
2194 channel_input_port_open(int type, int plen, void *ctxt)
2198 char *host, *originator_string;
2199 int remote_id, sock = -1;
2201 remote_id = packet_get_int();
2202 host = packet_get_string(NULL);
2203 host_port = packet_get_int();
2205 if (have_hostname_in_open) {
2206 originator_string = packet_get_string(NULL);
2208 originator_string = xstrdup("unknown (remote did not supply name)");
2211 sock = channel_connect_to(host, host_port);
2213 c = channel_new("connected socket",
2214 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2215 originator_string, 1);
2217 error("channel_input_port_open: channel_new failed");
2220 c->remote_id = remote_id;
2224 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2225 packet_put_int(remote_id);
2232 * Creates an internet domain socket for listening for X11 connections.
2233 * Returns a suitable value for the DISPLAY variable, or NULL if an error
2237 #define NUM_SOCKS 10
2240 x11_create_display_inet(int screen_number, int x11_display_offset)
2242 int display_number, sock;
2244 struct addrinfo hints, *ai, *aitop;
2245 char strport[NI_MAXSERV];
2246 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2248 char hostname[MAXHOSTNAMELEN];
2250 for (display_number = x11_display_offset;
2251 display_number < MAX_DISPLAYS;
2253 port = 6000 + display_number;
2254 memset(&hints, 0, sizeof(hints));
2255 hints.ai_family = IPv4or6;
2256 hints.ai_flags = AI_PASSIVE; /* XXX loopback only ? */
2257 hints.ai_socktype = SOCK_STREAM;
2258 snprintf(strport, sizeof strport, "%d", port);
2259 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2260 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2263 for (ai = aitop; ai; ai = ai->ai_next) {
2264 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2266 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2268 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2269 error("socket: %.100s", strerror(errno));
2272 debug("x11_create_display_inet: Socket family %d not supported",
2277 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2278 debug("bind port %d: %.100s", port, strerror(errno));
2279 shutdown(sock, SHUT_RDWR);
2285 for (n = 0; n < num_socks; n++) {
2286 shutdown(socks[n], SHUT_RDWR);
2292 socks[num_socks++] = sock;
2293 #ifndef DONT_TRY_OTHER_AF
2294 if (num_socks == NUM_SOCKS)
2300 freeaddrinfo(aitop);
2304 if (display_number >= MAX_DISPLAYS) {
2305 error("Failed to allocate internet-domain X11 display socket.");
2308 /* Start listening for connections on the socket. */
2309 for (n = 0; n < num_socks; n++) {
2311 if (listen(sock, 5) < 0) {
2312 error("listen: %.100s", strerror(errno));
2313 shutdown(sock, SHUT_RDWR);
2319 /* Set up a suitable value for the DISPLAY variable. */
2320 if (gethostname(hostname, sizeof(hostname)) < 0)
2321 fatal("gethostname: %.100s", strerror(errno));
2323 #ifdef IPADDR_IN_DISPLAY
2325 * HPUX detects the local hostname in the DISPLAY variable and tries
2326 * to set up a shared memory connection to the server, which it
2327 * incorrectly supposes to be local.
2329 * The workaround - as used in later $$H and other programs - is
2330 * is to set display to the host's IP address.
2334 struct in_addr my_addr;
2336 he = gethostbyname(hostname);
2338 error("[X11-broken-fwd-hostname-workaround] Could not get "
2339 "IP address for hostname %s.", hostname);
2341 packet_send_debug("[X11-broken-fwd-hostname-workaround]"
2342 "Could not get IP address for hostname %s.", hostname);
2344 shutdown(sock, SHUT_RDWR);
2350 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
2352 /* Set DISPLAY to <ip address>:screen.display */
2353 snprintf(display, sizeof(display), "%.50s:%d.%d", inet_ntoa(my_addr),
2354 display_number, screen_number);
2356 #else /* IPADDR_IN_DISPLAY */
2357 /* Just set DISPLAY to hostname:screen.display */
2358 snprintf(display, sizeof display, "%.400s:%d.%d", hostname,
2359 display_number, screen_number);
2360 #endif /* IPADDR_IN_DISPLAY */
2362 /* Allocate a channel for each socket. */
2363 for (n = 0; n < num_socks; n++) {
2365 (void) channel_new("x11 listener",
2366 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2367 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2368 0, xstrdup("X11 inet listener"), 1);
2371 /* Return a suitable value for the DISPLAY environment variable. */
2372 return xstrdup(display);
2376 #define X_UNIX_PATH "/tmp/.X11-unix/X"
2381 connect_local_xsocket(u_int dnr)
2383 static const char *const x_sockets[] = {
2385 "/var/X/.X11-unix/X" "%u",
2386 "/usr/spool/sockets/X11/" "%u",
2390 struct sockaddr_un addr;
2391 const char *const * path;
2393 for (path = x_sockets; *path; ++path) {
2394 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2396 error("socket: %.100s", strerror(errno));
2397 memset(&addr, 0, sizeof(addr));
2398 addr.sun_family = AF_UNIX;
2399 snprintf(addr.sun_path, sizeof addr.sun_path, *path, dnr);
2400 if (connect(sock, (struct sockaddr *) & addr, sizeof(addr)) == 0)
2404 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2409 x11_connect_display(void)
2411 int display_number, sock = 0;
2412 const char *display;
2413 char buf[1024], *cp;
2414 struct addrinfo hints, *ai, *aitop;
2415 char strport[NI_MAXSERV];
2418 /* Try to open a socket for the local X server. */
2419 display = getenv("DISPLAY");
2421 error("DISPLAY not set.");
2425 * Now we decode the value of the DISPLAY variable and make a
2426 * connection to the real X server.
2430 * Check if it is a unix domain socket. Unix domain displays are in
2431 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2433 if (strncmp(display, "unix:", 5) == 0 ||
2434 display[0] == ':') {
2435 /* Connect to the unix domain socket. */
2436 if (sscanf(strrchr(display, ':') + 1, "%d", &display_number) != 1) {
2437 error("Could not parse display number from DISPLAY: %.100s",
2441 /* Create a socket. */
2442 sock = connect_local_xsocket(display_number);
2446 /* OK, we now have a connection to the display. */
2450 * Connect to an inet socket. The DISPLAY value is supposedly
2451 * hostname:d[.s], where hostname may also be numeric IP address.
2453 strncpy(buf, display, sizeof(buf));
2454 buf[sizeof(buf) - 1] = 0;
2455 cp = strchr(buf, ':');
2457 error("Could not find ':' in DISPLAY: %.100s", display);
2461 /* buf now contains the host name. But first we parse the display number. */
2462 if (sscanf(cp + 1, "%d", &display_number) != 1) {
2463 error("Could not parse display number from DISPLAY: %.100s",
2468 /* Look up the host address */
2469 memset(&hints, 0, sizeof(hints));
2470 hints.ai_family = IPv4or6;
2471 hints.ai_socktype = SOCK_STREAM;
2472 snprintf(strport, sizeof strport, "%d", 6000 + display_number);
2473 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2474 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2477 for (ai = aitop; ai; ai = ai->ai_next) {
2478 /* Create a socket. */
2479 sock = socket(ai->ai_family, SOCK_STREAM, 0);
2481 debug("socket: %.100s", strerror(errno));
2484 /* Connect it to the display. */
2485 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2486 debug("connect %.100s port %d: %.100s", buf,
2487 6000 + display_number, strerror(errno));
2494 freeaddrinfo(aitop);
2496 error("connect %.100s port %d: %.100s", buf, 6000 + display_number,
2504 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
2505 * the remote channel number. We should do whatever we want, and respond
2506 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
2510 x11_input_open(int type, int plen, void *ctxt)
2513 int remote_id, sock = 0;
2516 debug("Received X11 open request.");
2518 remote_id = packet_get_int();
2519 if (have_hostname_in_open) {
2520 remote_host = packet_get_string(NULL);
2522 remote_host = xstrdup("unknown (remote did not supply name)");
2526 /* Obtain a connection to the real X display. */
2527 sock = x11_connect_display();
2529 /* Allocate a channel for this connection. */
2530 c = channel_new("connected x11 socket",
2531 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
2534 error("x11_input_open: channel_new failed");
2537 c->remote_id = remote_id;
2541 /* Send refusal to the remote host. */
2542 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2543 packet_put_int(remote_id);
2545 /* Send a confirmation to the remote host. */
2546 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2547 packet_put_int(remote_id);
2548 packet_put_int(c->self);
2553 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
2555 deny_input_open(int type, int plen, void *ctxt)
2557 int rchan = packet_get_int();
2559 case SSH_SMSG_AGENT_OPEN:
2560 error("Warning: ssh server tried agent forwarding.");
2562 case SSH_SMSG_X11_OPEN:
2563 error("Warning: ssh server tried X11 forwarding.");
2566 error("deny_input_open: type %d plen %d", type, plen);
2569 error("Warning: this is probably a break in attempt by a malicious server.");
2570 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2571 packet_put_int(rchan);
2576 * Requests forwarding of X11 connections, generates fake authentication
2577 * data, and enables authentication spoofing.
2581 x11_request_forwarding_with_spoofing(int client_session_id,
2582 const char *proto, const char *data)
2584 u_int data_len = (u_int) strlen(data) / 2;
2585 u_int i, value, len;
2591 cp = getenv("DISPLAY");
2593 cp = strchr(cp, ':');
2595 cp = strchr(cp, '.');
2597 screen_number = atoi(cp + 1);
2601 /* Save protocol name. */
2602 x11_saved_proto = xstrdup(proto);
2605 * Extract real authentication data and generate fake data of the
2608 x11_saved_data = xmalloc(data_len);
2609 x11_fake_data = xmalloc(data_len);
2610 for (i = 0; i < data_len; i++) {
2611 if (sscanf(data + 2 * i, "%2x", &value) != 1)
2612 fatal("x11_request_forwarding: bad authentication data: %.100s", data);
2614 rand = arc4random();
2615 x11_saved_data[i] = value;
2616 x11_fake_data[i] = rand & 0xff;
2619 x11_saved_data_len = data_len;
2620 x11_fake_data_len = data_len;
2622 /* Convert the fake data into hex. */
2623 len = 2 * data_len + 1;
2624 new_data = xmalloc(len);
2625 for (i = 0; i < data_len; i++)
2626 snprintf(new_data + 2 * i, len - 2 * i,
2627 "%02x", (u_char) x11_fake_data[i]);
2629 /* Send the request packet. */
2631 channel_request_start(client_session_id, "x11-req", 0);
2632 packet_put_char(0); /* XXX bool single connection */
2634 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
2636 packet_put_cstring(proto);
2637 packet_put_cstring(new_data);
2638 packet_put_int(screen_number);
2640 packet_write_wait();
2644 /* Sends a message to the server to request authentication fd forwarding. */
2647 auth_request_forwarding()
2649 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
2651 packet_write_wait();
2655 * Returns the name of the forwarded authentication socket. Returns NULL if
2656 * there is no forwarded authentication socket. The returned value points to
2661 auth_get_socket_name()
2663 return channel_forwarded_auth_socket_name;
2666 /* removes the agent forwarding socket */
2669 cleanup_socket(void)
2671 unlink(channel_forwarded_auth_socket_name);
2672 rmdir(channel_forwarded_auth_socket_dir);
2676 * This is called to process SSH_CMSG_AGENT_REQUEST_FORWARDING on the server.
2677 * This starts forwarding authentication requests.
2681 auth_input_request_forwarding(struct passwd * pw)
2685 struct sockaddr_un sunaddr;
2687 if (auth_get_socket_name() != NULL)
2688 fatal("Protocol error: authentication forwarding requested twice.");
2690 /* Temporarily drop privileged uid for mkdir/bind. */
2691 temporarily_use_uid(pw);
2693 /* Allocate a buffer for the socket name, and format the name. */
2694 channel_forwarded_auth_socket_name = xmalloc(MAX_SOCKET_NAME);
2695 channel_forwarded_auth_socket_dir = xmalloc(MAX_SOCKET_NAME);
2696 strlcpy(channel_forwarded_auth_socket_dir, "/tmp/ssh-XXXXXXXX", MAX_SOCKET_NAME);
2698 /* Create private directory for socket */
2699 if (mkdtemp(channel_forwarded_auth_socket_dir) == NULL) {
2700 packet_send_debug("Agent forwarding disabled: mkdtemp() failed: %.100s",
2703 xfree(channel_forwarded_auth_socket_name);
2704 xfree(channel_forwarded_auth_socket_dir);
2705 channel_forwarded_auth_socket_name = NULL;
2706 channel_forwarded_auth_socket_dir = NULL;
2709 snprintf(channel_forwarded_auth_socket_name, MAX_SOCKET_NAME, "%s/agent.%d",
2710 channel_forwarded_auth_socket_dir, (int) getpid());
2712 if (atexit(cleanup_socket) < 0) {
2715 packet_disconnect("socket: %.100s", strerror(saved));
2717 /* Create the socket. */
2718 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2720 packet_disconnect("socket: %.100s", strerror(errno));
2722 /* Bind it to the name. */
2723 memset(&sunaddr, 0, sizeof(sunaddr));
2724 sunaddr.sun_family = AF_UNIX;
2725 strncpy(sunaddr.sun_path, channel_forwarded_auth_socket_name,
2726 sizeof(sunaddr.sun_path));
2728 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
2729 packet_disconnect("bind: %.100s", strerror(errno));
2731 /* Restore the privileged uid. */
2734 /* Start listening on the socket. */
2735 if (listen(sock, 5) < 0)
2736 packet_disconnect("listen: %.100s", strerror(errno));
2738 /* Allocate a channel for the authentication agent socket. */
2739 nc = channel_new("auth socket",
2740 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
2741 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2742 0, xstrdup("auth socket"), 1);
2744 error("auth_input_request_forwarding: channel_new failed");
2748 strlcpy(nc->path, channel_forwarded_auth_socket_name, sizeof(nc->path));
2752 /* This is called to process an SSH_SMSG_AGENT_OPEN message. */
2755 auth_input_open_request(int type, int plen, void *ctxt)
2758 int remote_id, sock;
2761 packet_integrity_check(plen, 4, type);
2763 /* Read the remote channel number from the message. */
2764 remote_id = packet_get_int();
2767 * Get a connection to the local authentication agent (this may again
2770 sock = ssh_get_authentication_socket();
2773 * If we could not connect the agent, send an error message back to
2774 * the server. This should never happen unless the agent dies,
2775 * because authentication forwarding is only enabled if we have an
2779 dummyname = xstrdup("authentication agent connection");
2780 c = channel_new("", SSH_CHANNEL_OPEN, sock, sock, -1, 0, 0, 0, dummyname, 1);
2782 error("auth_input_open_request: channel_new failed");
2785 c->remote_id = remote_id;
2789 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2790 packet_put_int(remote_id);
2792 /* Send a confirmation to the remote host. */
2793 debug("Forwarding authentication connection.");
2794 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
2795 packet_put_int(remote_id);
2796 packet_put_int(c->self);
2802 channel_start_open(int id)
2804 Channel *c = channel_lookup(id);
2806 log("channel_open: %d: bad id", id);
2809 debug("send channel open %d", id);
2810 packet_start(SSH2_MSG_CHANNEL_OPEN);
2811 packet_put_cstring(c->ctype);
2812 packet_put_int(c->self);
2813 packet_put_int(c->local_window);
2814 packet_put_int(c->local_maxpacket);
2817 channel_open(int id)
2820 channel_start_open(id);
2824 channel_request(int id, char *service, int wantconfirm)
2826 channel_request_start(id, service, wantconfirm);
2828 debug("channel request %d: %s", id, service) ;
2831 channel_request_start(int id, char *service, int wantconfirm)
2833 Channel *c = channel_lookup(id);
2835 log("channel_request: %d: bad id", id);
2838 packet_start(SSH2_MSG_CHANNEL_REQUEST);
2839 packet_put_int(c->remote_id);
2840 packet_put_cstring(service);
2841 packet_put_char(wantconfirm);
2844 channel_register_callback(int id, int mtype, channel_callback_fn *fn, void *arg)
2846 Channel *c = channel_lookup(id);
2848 log("channel_register_callback: %d: bad id", id);
2851 c->cb_event = mtype;
2856 channel_register_cleanup(int id, channel_callback_fn *fn)
2858 Channel *c = channel_lookup(id);
2860 log("channel_register_cleanup: %d: bad id", id);
2863 c->dettach_user = fn;
2866 channel_cancel_cleanup(int id)
2868 Channel *c = channel_lookup(id);
2870 log("channel_cancel_cleanup: %d: bad id", id);
2873 c->dettach_user = NULL;
2876 channel_register_filter(int id, channel_filter_fn *fn)
2878 Channel *c = channel_lookup(id);
2880 log("channel_register_filter: %d: bad id", id);
2883 c->input_filter = fn;
2887 channel_set_fds(int id, int rfd, int wfd, int efd,
2888 int extusage, int nonblock)
2890 Channel *c = channel_lookup(id);
2891 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
2892 fatal("channel_activate for non-larval channel %d.", id);
2893 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
2894 c->type = SSH_CHANNEL_OPEN;
2895 /* XXX window size? */
2896 c->local_window = c->local_window_max = c->local_maxpacket * 2;
2897 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2898 packet_put_int(c->remote_id);
2899 packet_put_int(c->local_window);