1 /* $OpenBSD: channels.c,v 1.261 2006/07/25 02:59:21 stevesk Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for generic socket connection forwarding.
7 * There is also code for initiating connection forwarding for X11 connections,
8 * arbitrary tcp/ip connections, and the authentication agent connection.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/ioctl.h>
45 #include <sys/types.h>
47 #include <sys/socket.h>
48 #ifdef HAVE_SYS_TIME_H
49 # include <sys/time.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
73 #include "pathnames.h"
79 * Pointer to an array containing all allocated channels. The array is
80 * dynamically extended as needed.
82 static Channel **channels = NULL;
85 * Size of the channel array. All slots of the array must always be
86 * initialized (at least the type field); unused slots set to NULL
88 static u_int channels_alloc = 0;
91 * Maximum file descriptor value used in any of the channels. This is
92 * updated in channel_new.
94 static int channel_max_fd = 0;
97 /* -- tcp forwarding */
100 * Data structure for storing which hosts are permitted for forward requests.
101 * The local sides of any remote forwards are stored in this array to prevent
102 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
103 * network (which might be behind a firewall).
106 char *host_to_connect; /* Connect to 'host'. */
107 u_short port_to_connect; /* Connect to 'port'. */
108 u_short listen_port; /* Remote side should listen port number. */
111 /* List of all permitted host/port pairs to connect by the user. */
112 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
114 /* List of all permitted host/port pairs to connect by the admin. */
115 static ForwardPermission permitted_adm_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
117 /* Number of permitted host/port pairs in the array permitted by the user. */
118 static int num_permitted_opens = 0;
120 /* Number of permitted host/port pair in the array permitted by the admin. */
121 static int num_adm_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;
131 /* -- X11 forwarding */
133 /* Maximum number of fake X11 displays to try. */
134 #define MAX_DISPLAYS 1000
136 /* Saved X11 local (client) display. */
137 static char *x11_saved_display = NULL;
139 /* Saved X11 authentication protocol name. */
140 static char *x11_saved_proto = NULL;
142 /* Saved X11 authentication data. This is the real data. */
143 static char *x11_saved_data = NULL;
144 static u_int x11_saved_data_len = 0;
147 * Fake X11 authentication data. This is what the server will be sending us;
148 * we should replace any occurrences of this by the real data.
150 static u_char *x11_fake_data = NULL;
151 static u_int x11_fake_data_len;
154 /* -- agent forwarding */
158 /* AF_UNSPEC or AF_INET or AF_INET6 */
159 static int IPv4or6 = AF_UNSPEC;
162 static void port_open_helper(Channel *c, char *rtype);
164 /* -- channel core */
167 channel_by_id(int id)
171 if (id < 0 || (u_int)id >= channels_alloc) {
172 logit("channel_by_id: %d: bad id", id);
177 logit("channel_by_id: %d: bad id: channel free", id);
184 * Returns the channel if it is allowed to receive protocol messages.
185 * Private channels, like listening sockets, may not receive messages.
188 channel_lookup(int id)
192 if ((c = channel_by_id(id)) == NULL)
196 case SSH_CHANNEL_X11_OPEN:
197 case SSH_CHANNEL_LARVAL:
198 case SSH_CHANNEL_CONNECTING:
199 case SSH_CHANNEL_DYNAMIC:
200 case SSH_CHANNEL_OPENING:
201 case SSH_CHANNEL_OPEN:
202 case SSH_CHANNEL_INPUT_DRAINING:
203 case SSH_CHANNEL_OUTPUT_DRAINING:
206 logit("Non-public channel %d, type %d.", id, c->type);
211 * Register filedescriptors for a channel, used when allocating a channel or
212 * when the channel consumer/producer is ready, e.g. shell exec'd
215 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
216 int extusage, int nonblock)
218 /* Update the maximum file descriptor value. */
219 channel_max_fd = MAX(channel_max_fd, rfd);
220 channel_max_fd = MAX(channel_max_fd, wfd);
221 channel_max_fd = MAX(channel_max_fd, efd);
223 /* XXX set close-on-exec -markus */
227 c->sock = (rfd == wfd) ? rfd : -1;
228 c->ctl_fd = -1; /* XXX: set elsewhere */
230 c->extended_usage = extusage;
232 /* XXX ugly hack: nonblock is only set by the server */
233 if (nonblock && isatty(c->rfd)) {
234 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
236 if (!isatty(c->wfd)) {
237 error("channel %d: wfd %d is not a tty?",
243 c->wfd_isatty = isatty(c->wfd);
245 /* enable nonblocking mode */
257 * Allocate a new channel object and set its type and socket. This will cause
258 * remote_name to be freed.
261 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
262 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
268 /* Do initial allocation if this is the first call. */
269 if (channels_alloc == 0) {
271 channels = xcalloc(channels_alloc, sizeof(Channel *));
272 for (i = 0; i < channels_alloc; i++)
275 /* Try to find a free slot where to put the new channel. */
276 for (found = -1, i = 0; i < channels_alloc; i++)
277 if (channels[i] == NULL) {
278 /* Found a free slot. */
283 /* There are no free slots. Take last+1 slot and expand the array. */
284 found = channels_alloc;
285 if (channels_alloc > 10000)
286 fatal("channel_new: internal error: channels_alloc %d "
287 "too big.", channels_alloc);
288 channels = xrealloc(channels, channels_alloc + 10,
290 channels_alloc += 10;
291 debug2("channel: expanding %d", channels_alloc);
292 for (i = found; i < channels_alloc; i++)
295 /* Initialize and return new channel. */
296 c = channels[found] = xcalloc(1, sizeof(Channel));
297 buffer_init(&c->input);
298 buffer_init(&c->output);
299 buffer_init(&c->extended);
300 c->ostate = CHAN_OUTPUT_OPEN;
301 c->istate = CHAN_INPUT_OPEN;
303 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
307 c->local_window = window;
308 c->local_window_max = window;
309 c->local_consumed = 0;
310 c->local_maxpacket = maxpack;
312 c->remote_name = xstrdup(remote_name);
313 c->remote_window = 0;
314 c->remote_maxpacket = 0;
316 c->single_connection = 0;
317 c->detach_user = NULL;
320 c->confirm_ctx = NULL;
321 c->input_filter = NULL;
322 c->output_filter = NULL;
323 debug("channel %d: new [%s]", found, remote_name);
328 channel_find_maxfd(void)
334 for (i = 0; i < channels_alloc; i++) {
337 max = MAX(max, c->rfd);
338 max = MAX(max, c->wfd);
339 max = MAX(max, c->efd);
346 channel_close_fd(int *fdp)
348 int ret = 0, fd = *fdp;
353 if (fd == channel_max_fd)
354 channel_max_fd = channel_find_maxfd();
359 /* Close all channel fd/socket. */
361 channel_close_fds(Channel *c)
363 debug3("channel %d: close_fds r %d w %d e %d c %d",
364 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
366 channel_close_fd(&c->sock);
367 channel_close_fd(&c->ctl_fd);
368 channel_close_fd(&c->rfd);
369 channel_close_fd(&c->wfd);
370 channel_close_fd(&c->efd);
373 /* Free the channel and close its fd/socket. */
375 channel_free(Channel *c)
380 for (n = 0, i = 0; i < channels_alloc; i++)
383 debug("channel %d: free: %s, nchannels %u", c->self,
384 c->remote_name ? c->remote_name : "???", n);
386 s = channel_open_message();
387 debug3("channel %d: status: %s", c->self, s);
391 shutdown(c->sock, SHUT_RDWR);
393 shutdown(c->ctl_fd, SHUT_RDWR);
394 channel_close_fds(c);
395 buffer_free(&c->input);
396 buffer_free(&c->output);
397 buffer_free(&c->extended);
398 if (c->remote_name) {
399 xfree(c->remote_name);
400 c->remote_name = NULL;
402 channels[c->self] = NULL;
407 channel_free_all(void)
411 for (i = 0; i < channels_alloc; i++)
412 if (channels[i] != NULL)
413 channel_free(channels[i]);
417 * Closes the sockets/fds of all channels. This is used to close extra file
418 * descriptors after a fork.
421 channel_close_all(void)
425 for (i = 0; i < channels_alloc; i++)
426 if (channels[i] != NULL)
427 channel_close_fds(channels[i]);
431 * Stop listening to channels.
434 channel_stop_listening(void)
439 for (i = 0; i < channels_alloc; i++) {
443 case SSH_CHANNEL_AUTH_SOCKET:
444 case SSH_CHANNEL_PORT_LISTENER:
445 case SSH_CHANNEL_RPORT_LISTENER:
446 case SSH_CHANNEL_X11_LISTENER:
447 channel_close_fd(&c->sock);
456 * Returns true if no channel has too much buffered data, and false if one or
457 * more channel is overfull.
460 channel_not_very_much_buffered_data(void)
465 for (i = 0; i < channels_alloc; i++) {
467 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
470 buffer_len(&c->input) > packet_get_maxsize()) {
471 debug2("channel %d: big input buffer %d",
472 c->self, buffer_len(&c->input));
476 if (buffer_len(&c->output) > packet_get_maxsize()) {
477 debug2("channel %d: big output buffer %u > %u",
478 c->self, buffer_len(&c->output),
479 packet_get_maxsize());
487 /* Returns true if any channel is still open. */
489 channel_still_open(void)
494 for (i = 0; i < channels_alloc; i++) {
499 case SSH_CHANNEL_X11_LISTENER:
500 case SSH_CHANNEL_PORT_LISTENER:
501 case SSH_CHANNEL_RPORT_LISTENER:
502 case SSH_CHANNEL_CLOSED:
503 case SSH_CHANNEL_AUTH_SOCKET:
504 case SSH_CHANNEL_DYNAMIC:
505 case SSH_CHANNEL_CONNECTING:
506 case SSH_CHANNEL_ZOMBIE:
508 case SSH_CHANNEL_LARVAL:
510 fatal("cannot happen: SSH_CHANNEL_LARVAL");
512 case SSH_CHANNEL_OPENING:
513 case SSH_CHANNEL_OPEN:
514 case SSH_CHANNEL_X11_OPEN:
516 case SSH_CHANNEL_INPUT_DRAINING:
517 case SSH_CHANNEL_OUTPUT_DRAINING:
519 fatal("cannot happen: OUT_DRAIN");
522 fatal("channel_still_open: bad channel type %d", c->type);
529 /* Returns the id of an open channel suitable for keepaliving */
531 channel_find_open(void)
536 for (i = 0; i < channels_alloc; i++) {
538 if (c == NULL || c->remote_id < 0)
541 case SSH_CHANNEL_CLOSED:
542 case SSH_CHANNEL_DYNAMIC:
543 case SSH_CHANNEL_X11_LISTENER:
544 case SSH_CHANNEL_PORT_LISTENER:
545 case SSH_CHANNEL_RPORT_LISTENER:
546 case SSH_CHANNEL_OPENING:
547 case SSH_CHANNEL_CONNECTING:
548 case SSH_CHANNEL_ZOMBIE:
550 case SSH_CHANNEL_LARVAL:
551 case SSH_CHANNEL_AUTH_SOCKET:
552 case SSH_CHANNEL_OPEN:
553 case SSH_CHANNEL_X11_OPEN:
555 case SSH_CHANNEL_INPUT_DRAINING:
556 case SSH_CHANNEL_OUTPUT_DRAINING:
558 fatal("cannot happen: OUT_DRAIN");
561 fatal("channel_find_open: bad channel type %d", c->type);
570 * Returns a message describing the currently open forwarded connections,
571 * suitable for sending to the client. The message contains crlf pairs for
575 channel_open_message(void)
582 buffer_init(&buffer);
583 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
584 buffer_append(&buffer, buf, strlen(buf));
585 for (i = 0; i < channels_alloc; i++) {
590 case SSH_CHANNEL_X11_LISTENER:
591 case SSH_CHANNEL_PORT_LISTENER:
592 case SSH_CHANNEL_RPORT_LISTENER:
593 case SSH_CHANNEL_CLOSED:
594 case SSH_CHANNEL_AUTH_SOCKET:
595 case SSH_CHANNEL_ZOMBIE:
597 case SSH_CHANNEL_LARVAL:
598 case SSH_CHANNEL_OPENING:
599 case SSH_CHANNEL_CONNECTING:
600 case SSH_CHANNEL_DYNAMIC:
601 case SSH_CHANNEL_OPEN:
602 case SSH_CHANNEL_X11_OPEN:
603 case SSH_CHANNEL_INPUT_DRAINING:
604 case SSH_CHANNEL_OUTPUT_DRAINING:
605 snprintf(buf, sizeof buf,
606 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
607 c->self, c->remote_name,
608 c->type, c->remote_id,
609 c->istate, buffer_len(&c->input),
610 c->ostate, buffer_len(&c->output),
611 c->rfd, c->wfd, c->ctl_fd);
612 buffer_append(&buffer, buf, strlen(buf));
615 fatal("channel_open_message: bad channel type %d", c->type);
619 buffer_append(&buffer, "\0", 1);
620 cp = xstrdup(buffer_ptr(&buffer));
621 buffer_free(&buffer);
626 channel_send_open(int id)
628 Channel *c = channel_lookup(id);
631 logit("channel_send_open: %d: bad id", id);
634 debug2("channel %d: send open", id);
635 packet_start(SSH2_MSG_CHANNEL_OPEN);
636 packet_put_cstring(c->ctype);
637 packet_put_int(c->self);
638 packet_put_int(c->local_window);
639 packet_put_int(c->local_maxpacket);
644 channel_request_start(int id, char *service, int wantconfirm)
646 Channel *c = channel_lookup(id);
649 logit("channel_request_start: %d: unknown channel id", id);
652 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
653 packet_start(SSH2_MSG_CHANNEL_REQUEST);
654 packet_put_int(c->remote_id);
655 packet_put_cstring(service);
656 packet_put_char(wantconfirm);
660 channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
662 Channel *c = channel_lookup(id);
665 logit("channel_register_comfirm: %d: bad id", id);
669 c->confirm_ctx = ctx;
673 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
675 Channel *c = channel_by_id(id);
678 logit("channel_register_cleanup: %d: bad id", id);
682 c->detach_close = do_close;
686 channel_cancel_cleanup(int id)
688 Channel *c = channel_by_id(id);
691 logit("channel_cancel_cleanup: %d: bad id", id);
694 c->detach_user = NULL;
699 channel_register_filter(int id, channel_infilter_fn *ifn,
700 channel_outfilter_fn *ofn)
702 Channel *c = channel_lookup(id);
705 logit("channel_register_filter: %d: bad id", id);
708 c->input_filter = ifn;
709 c->output_filter = ofn;
713 channel_set_fds(int id, int rfd, int wfd, int efd,
714 int extusage, int nonblock, u_int window_max)
716 Channel *c = channel_lookup(id);
718 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
719 fatal("channel_activate for non-larval channel %d.", id);
720 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
721 c->type = SSH_CHANNEL_OPEN;
722 c->local_window = c->local_window_max = window_max;
723 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
724 packet_put_int(c->remote_id);
725 packet_put_int(c->local_window);
730 * 'channel_pre*' are called just before select() to add any bits relevant to
731 * channels in the select bitmasks.
734 * 'channel_post*': perform any appropriate operations for channels which
735 * have events pending.
737 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
738 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
739 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
743 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
745 FD_SET(c->sock, readset);
750 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
752 debug3("channel %d: waiting for connection", c->self);
753 FD_SET(c->sock, writeset);
757 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
759 if (buffer_len(&c->input) < packet_get_maxsize())
760 FD_SET(c->sock, readset);
761 if (buffer_len(&c->output) > 0)
762 FD_SET(c->sock, writeset);
766 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
768 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
770 if (c->istate == CHAN_INPUT_OPEN &&
772 buffer_len(&c->input) < limit &&
773 buffer_check_alloc(&c->input, CHAN_RBUF))
774 FD_SET(c->rfd, readset);
775 if (c->ostate == CHAN_OUTPUT_OPEN ||
776 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
777 if (buffer_len(&c->output) > 0) {
778 FD_SET(c->wfd, writeset);
779 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
780 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
781 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
782 c->self, c->efd, buffer_len(&c->extended));
787 /** XXX check close conditions, too */
788 if (compat20 && c->efd != -1) {
789 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
790 buffer_len(&c->extended) > 0)
791 FD_SET(c->efd, writeset);
792 else if (!(c->flags & CHAN_EOF_SENT) &&
793 c->extended_usage == CHAN_EXTENDED_READ &&
794 buffer_len(&c->extended) < c->remote_window)
795 FD_SET(c->efd, readset);
797 /* XXX: What about efd? races? */
798 if (compat20 && c->ctl_fd != -1 &&
799 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
800 FD_SET(c->ctl_fd, readset);
805 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
807 if (buffer_len(&c->input) == 0) {
808 packet_start(SSH_MSG_CHANNEL_CLOSE);
809 packet_put_int(c->remote_id);
811 c->type = SSH_CHANNEL_CLOSED;
812 debug2("channel %d: closing after input drain.", c->self);
818 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
820 if (buffer_len(&c->output) == 0)
823 FD_SET(c->sock, writeset);
827 * This is a special state for X11 authentication spoofing. An opened X11
828 * connection (when authentication spoofing is being done) remains in this
829 * state until the first packet has been completely read. The authentication
830 * data in that packet is then substituted by the real data if it matches the
831 * fake data, and the channel is put into normal mode.
832 * XXX All this happens at the client side.
833 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
836 x11_open_helper(Buffer *b)
839 u_int proto_len, data_len;
841 /* Check if the fixed size part of the packet is in buffer. */
842 if (buffer_len(b) < 12)
845 /* Parse the lengths of variable-length fields. */
847 if (ucp[0] == 0x42) { /* Byte order MSB first. */
848 proto_len = 256 * ucp[6] + ucp[7];
849 data_len = 256 * ucp[8] + ucp[9];
850 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
851 proto_len = ucp[6] + 256 * ucp[7];
852 data_len = ucp[8] + 256 * ucp[9];
854 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
859 /* Check if the whole packet is in buffer. */
861 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
864 /* Check if authentication protocol matches. */
865 if (proto_len != strlen(x11_saved_proto) ||
866 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
867 debug2("X11 connection uses different authentication protocol.");
870 /* Check if authentication data matches our fake data. */
871 if (data_len != x11_fake_data_len ||
872 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
873 x11_fake_data, x11_fake_data_len) != 0) {
874 debug2("X11 auth data does not match fake data.");
877 /* Check fake data length */
878 if (x11_fake_data_len != x11_saved_data_len) {
879 error("X11 fake_data_len %d != saved_data_len %d",
880 x11_fake_data_len, x11_saved_data_len);
884 * Received authentication protocol and data match
885 * our fake data. Substitute the fake data with real
888 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
889 x11_saved_data, x11_saved_data_len);
894 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
896 int ret = x11_open_helper(&c->output);
899 /* Start normal processing for the channel. */
900 c->type = SSH_CHANNEL_OPEN;
901 channel_pre_open_13(c, readset, writeset);
902 } else if (ret == -1) {
904 * We have received an X11 connection that has bad
905 * authentication information.
907 logit("X11 connection rejected because of wrong authentication.");
908 buffer_clear(&c->input);
909 buffer_clear(&c->output);
910 channel_close_fd(&c->sock);
912 c->type = SSH_CHANNEL_CLOSED;
913 packet_start(SSH_MSG_CHANNEL_CLOSE);
914 packet_put_int(c->remote_id);
920 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
922 int ret = x11_open_helper(&c->output);
924 /* c->force_drain = 1; */
927 c->type = SSH_CHANNEL_OPEN;
928 channel_pre_open(c, readset, writeset);
929 } else if (ret == -1) {
930 logit("X11 connection rejected because of wrong authentication.");
931 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
933 buffer_clear(&c->input);
935 buffer_clear(&c->output);
936 /* for proto v1, the peer will send an IEOF */
938 chan_write_failed(c);
940 c->type = SSH_CHANNEL_OPEN;
941 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
945 /* try to decode a socks4 header */
948 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
951 u_int len, have, i, found;
957 struct in_addr dest_addr;
960 debug2("channel %d: decode socks4", c->self);
962 have = buffer_len(&c->input);
963 len = sizeof(s4_req);
966 p = buffer_ptr(&c->input);
967 for (found = 0, i = len; i < have; i++) {
973 /* the peer is probably sending garbage */
974 debug("channel %d: decode socks4: too long",
981 buffer_get(&c->input, (char *)&s4_req.version, 1);
982 buffer_get(&c->input, (char *)&s4_req.command, 1);
983 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
984 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
985 have = buffer_len(&c->input);
986 p = buffer_ptr(&c->input);
988 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
990 fatal("channel %d: decode socks4: len %d > have %d",
992 strlcpy(username, p, sizeof(username));
993 buffer_consume(&c->input, len);
994 buffer_consume(&c->input, 1); /* trailing '\0' */
996 host = inet_ntoa(s4_req.dest_addr);
997 strlcpy(c->path, host, sizeof(c->path));
998 c->host_port = ntohs(s4_req.dest_port);
1000 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1001 c->self, host, c->host_port, s4_req.command);
1003 if (s4_req.command != 1) {
1004 debug("channel %d: cannot handle: socks4 cn %d",
1005 c->self, s4_req.command);
1008 s4_rsp.version = 0; /* vn: 0 for reply */
1009 s4_rsp.command = 90; /* cd: req granted */
1010 s4_rsp.dest_port = 0; /* ignored */
1011 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1012 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1016 /* try to decode a socks5 header */
1017 #define SSH_SOCKS5_AUTHDONE 0x1000
1018 #define SSH_SOCKS5_NOAUTH 0x00
1019 #define SSH_SOCKS5_IPV4 0x01
1020 #define SSH_SOCKS5_DOMAIN 0x03
1021 #define SSH_SOCKS5_IPV6 0x04
1022 #define SSH_SOCKS5_CONNECT 0x01
1023 #define SSH_SOCKS5_SUCCESS 0x00
1027 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1035 u_int16_t dest_port;
1036 u_char *p, dest_addr[255+1];
1037 u_int have, need, i, found, nmethods, addrlen, af;
1039 debug2("channel %d: decode socks5", c->self);
1040 p = buffer_ptr(&c->input);
1043 have = buffer_len(&c->input);
1044 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1045 /* format: ver | nmethods | methods */
1049 if (have < nmethods + 2)
1051 /* look for method: "NO AUTHENTICATION REQUIRED" */
1052 for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1053 if (p[i] == SSH_SOCKS5_NOAUTH ) {
1059 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1063 buffer_consume(&c->input, nmethods + 2);
1064 buffer_put_char(&c->output, 0x05); /* version */
1065 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1066 FD_SET(c->sock, writeset);
1067 c->flags |= SSH_SOCKS5_AUTHDONE;
1068 debug2("channel %d: socks5 auth done", c->self);
1069 return 0; /* need more */
1071 debug2("channel %d: socks5 post auth", c->self);
1072 if (have < sizeof(s5_req)+1)
1073 return 0; /* need more */
1074 memcpy(&s5_req, p, sizeof(s5_req));
1075 if (s5_req.version != 0x05 ||
1076 s5_req.command != SSH_SOCKS5_CONNECT ||
1077 s5_req.reserved != 0x00) {
1078 debug2("channel %d: only socks5 connect supported", c->self);
1081 switch (s5_req.atyp){
1082 case SSH_SOCKS5_IPV4:
1086 case SSH_SOCKS5_DOMAIN:
1087 addrlen = p[sizeof(s5_req)];
1090 case SSH_SOCKS5_IPV6:
1095 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1098 need = sizeof(s5_req) + addrlen + 2;
1099 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1103 buffer_consume(&c->input, sizeof(s5_req));
1104 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1105 buffer_consume(&c->input, 1); /* host string length */
1106 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1107 buffer_get(&c->input, (char *)&dest_port, 2);
1108 dest_addr[addrlen] = '\0';
1109 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1110 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1111 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1113 c->host_port = ntohs(dest_port);
1115 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1116 c->self, c->path, c->host_port, s5_req.command);
1118 s5_rsp.version = 0x05;
1119 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1120 s5_rsp.reserved = 0; /* ignored */
1121 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1122 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1123 dest_port = 0; /* ignored */
1125 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1126 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1127 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1131 /* dynamic port forwarding */
1133 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1139 have = buffer_len(&c->input);
1141 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1142 /* buffer_dump(&c->input); */
1143 /* check if the fixed size part of the packet is in buffer. */
1146 FD_SET(c->sock, readset);
1149 /* try to guess the protocol */
1150 p = buffer_ptr(&c->input);
1153 ret = channel_decode_socks4(c, readset, writeset);
1156 ret = channel_decode_socks5(c, readset, writeset);
1164 } else if (ret == 0) {
1165 debug2("channel %d: pre_dynamic: need more", c->self);
1167 FD_SET(c->sock, readset);
1169 /* switch to the next state */
1170 c->type = SSH_CHANNEL_OPENING;
1171 port_open_helper(c, "direct-tcpip");
1175 /* This is our fake X11 server socket. */
1178 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1181 struct sockaddr addr;
1184 char buf[16384], *remote_ipaddr;
1187 if (FD_ISSET(c->sock, readset)) {
1188 debug("X11 connection requested.");
1189 addrlen = sizeof(addr);
1190 newsock = accept(c->sock, &addr, &addrlen);
1191 if (c->single_connection) {
1192 debug2("single_connection: closing X11 listener.");
1193 channel_close_fd(&c->sock);
1197 error("accept: %.100s", strerror(errno));
1200 set_nodelay(newsock);
1201 remote_ipaddr = get_peer_ipaddr(newsock);
1202 remote_port = get_peer_port(newsock);
1203 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1204 remote_ipaddr, remote_port);
1206 nc = channel_new("accepted x11 socket",
1207 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1208 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1210 packet_start(SSH2_MSG_CHANNEL_OPEN);
1211 packet_put_cstring("x11");
1212 packet_put_int(nc->self);
1213 packet_put_int(nc->local_window_max);
1214 packet_put_int(nc->local_maxpacket);
1215 /* originator ipaddr and port */
1216 packet_put_cstring(remote_ipaddr);
1217 if (datafellows & SSH_BUG_X11FWD) {
1218 debug2("ssh2 x11 bug compat mode");
1220 packet_put_int(remote_port);
1224 packet_start(SSH_SMSG_X11_OPEN);
1225 packet_put_int(nc->self);
1226 if (packet_get_protocol_flags() &
1227 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1228 packet_put_cstring(buf);
1231 xfree(remote_ipaddr);
1236 port_open_helper(Channel *c, char *rtype)
1240 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1241 int remote_port = get_peer_port(c->sock);
1243 direct = (strcmp(rtype, "direct-tcpip") == 0);
1245 snprintf(buf, sizeof buf,
1246 "%s: listening port %d for %.100s port %d, "
1247 "connect from %.200s port %d",
1248 rtype, c->listening_port, c->path, c->host_port,
1249 remote_ipaddr, remote_port);
1251 xfree(c->remote_name);
1252 c->remote_name = xstrdup(buf);
1255 packet_start(SSH2_MSG_CHANNEL_OPEN);
1256 packet_put_cstring(rtype);
1257 packet_put_int(c->self);
1258 packet_put_int(c->local_window_max);
1259 packet_put_int(c->local_maxpacket);
1261 /* target host, port */
1262 packet_put_cstring(c->path);
1263 packet_put_int(c->host_port);
1265 /* listen address, port */
1266 packet_put_cstring(c->path);
1267 packet_put_int(c->listening_port);
1269 /* originator host and port */
1270 packet_put_cstring(remote_ipaddr);
1271 packet_put_int((u_int)remote_port);
1274 packet_start(SSH_MSG_PORT_OPEN);
1275 packet_put_int(c->self);
1276 packet_put_cstring(c->path);
1277 packet_put_int(c->host_port);
1278 if (packet_get_protocol_flags() &
1279 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1280 packet_put_cstring(c->remote_name);
1283 xfree(remote_ipaddr);
1287 channel_set_reuseaddr(int fd)
1292 * Set socket options.
1293 * Allow local port reuse in TIME_WAIT.
1295 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1296 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1300 * This socket is listening for connections to a forwarded TCP/IP port.
1304 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1307 struct sockaddr addr;
1308 int newsock, nextstate;
1312 if (FD_ISSET(c->sock, readset)) {
1313 debug("Connection to port %d forwarding "
1314 "to %.100s port %d requested.",
1315 c->listening_port, c->path, c->host_port);
1317 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1318 nextstate = SSH_CHANNEL_OPENING;
1319 rtype = "forwarded-tcpip";
1321 if (c->host_port == 0) {
1322 nextstate = SSH_CHANNEL_DYNAMIC;
1323 rtype = "dynamic-tcpip";
1325 nextstate = SSH_CHANNEL_OPENING;
1326 rtype = "direct-tcpip";
1330 addrlen = sizeof(addr);
1331 newsock = accept(c->sock, &addr, &addrlen);
1333 error("accept: %.100s", strerror(errno));
1336 set_nodelay(newsock);
1337 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1338 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1339 nc->listening_port = c->listening_port;
1340 nc->host_port = c->host_port;
1341 strlcpy(nc->path, c->path, sizeof(nc->path));
1343 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1345 * do not call the channel_post handler until
1346 * this flag has been reset by a pre-handler.
1347 * otherwise the FD_ISSET calls might overflow
1351 port_open_helper(nc, rtype);
1357 * This is the authentication agent socket listening for connections from
1362 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1366 struct sockaddr addr;
1369 if (FD_ISSET(c->sock, readset)) {
1370 addrlen = sizeof(addr);
1371 newsock = accept(c->sock, &addr, &addrlen);
1373 error("accept from auth socket: %.100s", strerror(errno));
1376 nc = channel_new("accepted auth socket",
1377 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1378 c->local_window_max, c->local_maxpacket,
1379 0, "accepted auth socket", 1);
1381 packet_start(SSH2_MSG_CHANNEL_OPEN);
1382 packet_put_cstring("auth-agent@openssh.com");
1383 packet_put_int(nc->self);
1384 packet_put_int(c->local_window_max);
1385 packet_put_int(c->local_maxpacket);
1387 packet_start(SSH_SMSG_AGENT_OPEN);
1388 packet_put_int(nc->self);
1396 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1399 socklen_t sz = sizeof(err);
1401 if (FD_ISSET(c->sock, writeset)) {
1402 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1404 error("getsockopt SO_ERROR failed");
1407 debug("channel %d: connected", c->self);
1408 c->type = SSH_CHANNEL_OPEN;
1410 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1411 packet_put_int(c->remote_id);
1412 packet_put_int(c->self);
1413 packet_put_int(c->local_window);
1414 packet_put_int(c->local_maxpacket);
1416 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1417 packet_put_int(c->remote_id);
1418 packet_put_int(c->self);
1421 debug("channel %d: not connected: %s",
1422 c->self, strerror(err));
1424 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1425 packet_put_int(c->remote_id);
1426 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1427 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1428 packet_put_cstring(strerror(err));
1429 packet_put_cstring("");
1432 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1433 packet_put_int(c->remote_id);
1443 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1445 char buf[CHAN_RBUF];
1449 FD_ISSET(c->rfd, readset)) {
1451 len = read(c->rfd, buf, sizeof(buf));
1452 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1454 #ifndef PTY_ZEROREAD
1457 if ((!c->isatty && len <= 0) ||
1458 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1460 debug2("channel %d: read<=0 rfd %d len %d",
1461 c->self, c->rfd, len);
1462 if (c->type != SSH_CHANNEL_OPEN) {
1463 debug2("channel %d: not open", c->self);
1466 } else if (compat13) {
1467 buffer_clear(&c->output);
1468 c->type = SSH_CHANNEL_INPUT_DRAINING;
1469 debug2("channel %d: input draining.", c->self);
1471 chan_read_failed(c);
1475 if (c->input_filter != NULL) {
1476 if (c->input_filter(c, buf, len) == -1) {
1477 debug2("channel %d: filter stops", c->self);
1478 chan_read_failed(c);
1480 } else if (c->datagram) {
1481 buffer_put_string(&c->input, buf, len);
1483 buffer_append(&c->input, buf, len);
1491 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1494 u_char *data = NULL, *buf;
1498 /* Send buffered output data to the socket. */
1500 FD_ISSET(c->wfd, writeset) &&
1501 buffer_len(&c->output) > 0) {
1502 if (c->output_filter != NULL) {
1503 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1504 debug2("channel %d: filter stops", c->self);
1505 if (c->type != SSH_CHANNEL_OPEN)
1508 chan_write_failed(c);
1511 } else if (c->datagram) {
1512 buf = data = buffer_get_string(&c->output, &dlen);
1514 buf = data = buffer_ptr(&c->output);
1515 dlen = buffer_len(&c->output);
1519 /* ignore truncated writes, datagrams might get lost */
1520 c->local_consumed += dlen + 4;
1521 len = write(c->wfd, buf, dlen);
1523 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1526 if (c->type != SSH_CHANNEL_OPEN)
1529 chan_write_failed(c);
1535 /* XXX: Later AIX versions can't push as much data to tty */
1536 if (compat20 && c->wfd_isatty)
1537 dlen = MIN(dlen, 8*1024);
1540 len = write(c->wfd, buf, dlen);
1541 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1544 if (c->type != SSH_CHANNEL_OPEN) {
1545 debug2("channel %d: not open", c->self);
1548 } else if (compat13) {
1549 buffer_clear(&c->output);
1550 debug2("channel %d: input draining.", c->self);
1551 c->type = SSH_CHANNEL_INPUT_DRAINING;
1553 chan_write_failed(c);
1557 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1558 if (tcgetattr(c->wfd, &tio) == 0 &&
1559 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1561 * Simulate echo to reduce the impact of
1562 * traffic analysis. We need to match the
1563 * size of a SSH2_MSG_CHANNEL_DATA message
1564 * (4 byte channel id + buf)
1566 packet_send_ignore(4 + len);
1570 buffer_consume(&c->output, len);
1571 if (compat20 && len > 0) {
1572 c->local_consumed += len;
1579 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1581 char buf[CHAN_RBUF];
1584 /** XXX handle drain efd, too */
1586 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1587 FD_ISSET(c->efd, writeset) &&
1588 buffer_len(&c->extended) > 0) {
1589 len = write(c->efd, buffer_ptr(&c->extended),
1590 buffer_len(&c->extended));
1591 debug2("channel %d: written %d to efd %d",
1592 c->self, len, c->efd);
1593 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1596 debug2("channel %d: closing write-efd %d",
1598 channel_close_fd(&c->efd);
1600 buffer_consume(&c->extended, len);
1601 c->local_consumed += len;
1603 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1604 FD_ISSET(c->efd, readset)) {
1605 len = read(c->efd, buf, sizeof(buf));
1606 debug2("channel %d: read %d from efd %d",
1607 c->self, len, c->efd);
1608 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1611 debug2("channel %d: closing read-efd %d",
1613 channel_close_fd(&c->efd);
1615 buffer_append(&c->extended, buf, len);
1624 channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
1629 /* Monitor control fd to detect if the slave client exits */
1630 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1631 len = read(c->ctl_fd, buf, sizeof(buf));
1632 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1635 debug2("channel %d: ctl read<=0", c->self);
1636 if (c->type != SSH_CHANNEL_OPEN) {
1637 debug2("channel %d: not open", c->self);
1641 chan_read_failed(c);
1642 chan_write_failed(c);
1646 fatal("%s: unexpected data on ctl fd", __func__);
1652 channel_check_window(Channel *c)
1654 if (c->type == SSH_CHANNEL_OPEN &&
1655 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1656 c->local_window < c->local_window_max/2 &&
1657 c->local_consumed > 0) {
1658 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1659 packet_put_int(c->remote_id);
1660 packet_put_int(c->local_consumed);
1662 debug2("channel %d: window %d sent adjust %d",
1663 c->self, c->local_window,
1665 c->local_window += c->local_consumed;
1666 c->local_consumed = 0;
1672 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1676 channel_handle_rfd(c, readset, writeset);
1677 channel_handle_wfd(c, readset, writeset);
1680 channel_handle_efd(c, readset, writeset);
1681 channel_handle_ctl(c, readset, writeset);
1682 channel_check_window(c);
1687 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1691 /* Send buffered output data to the socket. */
1692 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1693 len = write(c->sock, buffer_ptr(&c->output),
1694 buffer_len(&c->output));
1696 buffer_clear(&c->output);
1698 buffer_consume(&c->output, len);
1703 channel_handler_init_20(void)
1705 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1706 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1707 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1708 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1709 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1710 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1711 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1712 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1714 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1715 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1716 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1717 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1718 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1719 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1720 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1724 channel_handler_init_13(void)
1726 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1727 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1728 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1729 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1730 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1731 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1732 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1733 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1734 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1736 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1737 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1738 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1739 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1740 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1741 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1742 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1746 channel_handler_init_15(void)
1748 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1749 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1750 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1751 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1752 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1753 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1754 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1756 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1757 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1758 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1759 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1760 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1761 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1765 channel_handler_init(void)
1769 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1770 channel_pre[i] = NULL;
1771 channel_post[i] = NULL;
1774 channel_handler_init_20();
1776 channel_handler_init_13();
1778 channel_handler_init_15();
1781 /* gc dead channels */
1783 channel_garbage_collect(Channel *c)
1787 if (c->detach_user != NULL) {
1788 if (!chan_is_dead(c, c->detach_close))
1790 debug2("channel %d: gc: notify user", c->self);
1791 c->detach_user(c->self, NULL);
1792 /* if we still have a callback */
1793 if (c->detach_user != NULL)
1795 debug2("channel %d: gc: user detached", c->self);
1797 if (!chan_is_dead(c, 1))
1799 debug2("channel %d: garbage collecting", c->self);
1804 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1806 static int did_init = 0;
1811 channel_handler_init();
1814 for (i = 0; i < channels_alloc; i++) {
1818 if (ftab[c->type] != NULL)
1819 (*ftab[c->type])(c, readset, writeset);
1820 channel_garbage_collect(c);
1825 * Allocate/update select bitmasks and add any bits relevant to channels in
1829 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1830 u_int *nallocp, int rekeying)
1832 u_int n, sz, nfdset;
1834 n = MAX(*maxfdp, channel_max_fd);
1836 nfdset = howmany(n+1, NFDBITS);
1837 /* Explicitly test here, because xrealloc isn't always called */
1838 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
1839 fatal("channel_prepare_select: max_fd (%d) is too large", n);
1840 sz = nfdset * sizeof(fd_mask);
1842 /* perhaps check sz < nalloc/2 and shrink? */
1843 if (*readsetp == NULL || sz > *nallocp) {
1844 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
1845 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1849 memset(*readsetp, 0, sz);
1850 memset(*writesetp, 0, sz);
1853 channel_handler(channel_pre, *readsetp, *writesetp);
1857 * After select, perform any appropriate operations for channels which have
1861 channel_after_select(fd_set *readset, fd_set *writeset)
1863 channel_handler(channel_post, readset, writeset);
1867 /* If there is data to send to the connection, enqueue some of it now. */
1869 channel_output_poll(void)
1874 for (i = 0; i < channels_alloc; i++) {
1880 * We are only interested in channels that can have buffered
1884 if (c->type != SSH_CHANNEL_OPEN &&
1885 c->type != SSH_CHANNEL_INPUT_DRAINING)
1888 if (c->type != SSH_CHANNEL_OPEN)
1892 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1893 /* XXX is this true? */
1894 debug3("channel %d: will not send data after close", c->self);
1898 /* Get the amount of buffered data for this channel. */
1899 if ((c->istate == CHAN_INPUT_OPEN ||
1900 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1901 (len = buffer_len(&c->input)) > 0) {
1907 data = buffer_get_string(&c->input,
1909 packet_start(SSH2_MSG_CHANNEL_DATA);
1910 packet_put_int(c->remote_id);
1911 packet_put_string(data, dlen);
1913 c->remote_window -= dlen + 4;
1919 * Send some data for the other side over the secure
1923 if (len > c->remote_window)
1924 len = c->remote_window;
1925 if (len > c->remote_maxpacket)
1926 len = c->remote_maxpacket;
1928 if (packet_is_interactive()) {
1932 /* Keep the packets at reasonable size. */
1933 if (len > packet_get_maxsize()/2)
1934 len = packet_get_maxsize()/2;
1938 packet_start(compat20 ?
1939 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1940 packet_put_int(c->remote_id);
1941 packet_put_string(buffer_ptr(&c->input), len);
1943 buffer_consume(&c->input, len);
1944 c->remote_window -= len;
1946 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1948 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1950 * input-buffer is empty and read-socket shutdown:
1951 * tell peer, that we will not send more data: send IEOF.
1952 * hack for extended data: delay EOF if EFD still in use.
1954 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1955 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1956 c->self, c->efd, buffer_len(&c->extended));
1960 /* Send extended data, i.e. stderr */
1962 !(c->flags & CHAN_EOF_SENT) &&
1963 c->remote_window > 0 &&
1964 (len = buffer_len(&c->extended)) > 0 &&
1965 c->extended_usage == CHAN_EXTENDED_READ) {
1966 debug2("channel %d: rwin %u elen %u euse %d",
1967 c->self, c->remote_window, buffer_len(&c->extended),
1969 if (len > c->remote_window)
1970 len = c->remote_window;
1971 if (len > c->remote_maxpacket)
1972 len = c->remote_maxpacket;
1973 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1974 packet_put_int(c->remote_id);
1975 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1976 packet_put_string(buffer_ptr(&c->extended), len);
1978 buffer_consume(&c->extended, len);
1979 c->remote_window -= len;
1980 debug2("channel %d: sent ext data %d", c->self, len);
1986 /* -- protocol input */
1990 channel_input_data(int type, u_int32_t seq, void *ctxt)
1997 /* Get the channel number and verify it. */
1998 id = packet_get_int();
1999 c = channel_lookup(id);
2001 packet_disconnect("Received data for nonexistent channel %d.", id);
2003 /* Ignore any data for non-open channels (might happen on close) */
2004 if (c->type != SSH_CHANNEL_OPEN &&
2005 c->type != SSH_CHANNEL_X11_OPEN)
2009 data = packet_get_string(&data_len);
2012 * Ignore data for protocol > 1.3 if output end is no longer open.
2013 * For protocol 2 the sending side is reducing its window as it sends
2014 * data, so we must 'fake' consumption of the data in order to ensure
2015 * that window updates are sent back. Otherwise the connection might
2018 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2020 c->local_window -= data_len;
2021 c->local_consumed += data_len;
2028 if (data_len > c->local_maxpacket) {
2029 logit("channel %d: rcvd big packet %d, maxpack %d",
2030 c->self, data_len, c->local_maxpacket);
2032 if (data_len > c->local_window) {
2033 logit("channel %d: rcvd too much data %d, win %d",
2034 c->self, data_len, c->local_window);
2038 c->local_window -= data_len;
2042 buffer_put_string(&c->output, data, data_len);
2044 buffer_append(&c->output, data, data_len);
2050 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2054 u_int data_len, tcode;
2057 /* Get the channel number and verify it. */
2058 id = packet_get_int();
2059 c = channel_lookup(id);
2062 packet_disconnect("Received extended_data for bad channel %d.", id);
2063 if (c->type != SSH_CHANNEL_OPEN) {
2064 logit("channel %d: ext data for non open", id);
2067 if (c->flags & CHAN_EOF_RCVD) {
2068 if (datafellows & SSH_BUG_EXTEOF)
2069 debug("channel %d: accepting ext data after eof", id);
2071 packet_disconnect("Received extended_data after EOF "
2072 "on channel %d.", id);
2074 tcode = packet_get_int();
2076 c->extended_usage != CHAN_EXTENDED_WRITE ||
2077 tcode != SSH2_EXTENDED_DATA_STDERR) {
2078 logit("channel %d: bad ext data", c->self);
2081 data = packet_get_string(&data_len);
2083 if (data_len > c->local_window) {
2084 logit("channel %d: rcvd too much extended_data %d, win %d",
2085 c->self, data_len, c->local_window);
2089 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2090 c->local_window -= data_len;
2091 buffer_append(&c->extended, data, data_len);
2097 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2102 id = packet_get_int();
2104 c = channel_lookup(id);
2106 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2109 /* XXX force input close */
2110 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2111 debug("channel %d: FORCE input drain", c->self);
2112 c->istate = CHAN_INPUT_WAIT_DRAIN;
2113 if (buffer_len(&c->input) == 0)
2121 channel_input_close(int type, u_int32_t seq, void *ctxt)
2126 id = packet_get_int();
2128 c = channel_lookup(id);
2130 packet_disconnect("Received close for nonexistent channel %d.", id);
2133 * Send a confirmation that we have closed the channel and no more
2134 * data is coming for it.
2136 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2137 packet_put_int(c->remote_id);
2141 * If the channel is in closed state, we have sent a close request,
2142 * and the other side will eventually respond with a confirmation.
2143 * Thus, we cannot free the channel here, because then there would be
2144 * no-one to receive the confirmation. The channel gets freed when
2145 * the confirmation arrives.
2147 if (c->type != SSH_CHANNEL_CLOSED) {
2149 * Not a closed channel - mark it as draining, which will
2150 * cause it to be freed later.
2152 buffer_clear(&c->input);
2153 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2157 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2160 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2162 int id = packet_get_int();
2163 Channel *c = channel_lookup(id);
2167 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2168 chan_rcvd_oclose(c);
2173 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2175 int id = packet_get_int();
2176 Channel *c = channel_lookup(id);
2180 packet_disconnect("Received close confirmation for "
2181 "out-of-range channel %d.", id);
2182 if (c->type != SSH_CHANNEL_CLOSED)
2183 packet_disconnect("Received close confirmation for "
2184 "non-closed channel %d (type %d).", id, c->type);
2190 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2195 id = packet_get_int();
2196 c = channel_lookup(id);
2198 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2199 packet_disconnect("Received open confirmation for "
2200 "non-opening channel %d.", id);
2201 remote_id = packet_get_int();
2202 /* Record the remote channel number and mark that the channel is now open. */
2203 c->remote_id = remote_id;
2204 c->type = SSH_CHANNEL_OPEN;
2207 c->remote_window = packet_get_int();
2208 c->remote_maxpacket = packet_get_int();
2210 debug2("callback start");
2211 c->confirm(c->self, c->confirm_ctx);
2212 debug2("callback done");
2214 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2215 c->remote_window, c->remote_maxpacket);
2221 reason2txt(int reason)
2224 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2225 return "administratively prohibited";
2226 case SSH2_OPEN_CONNECT_FAILED:
2227 return "connect failed";
2228 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2229 return "unknown channel type";
2230 case SSH2_OPEN_RESOURCE_SHORTAGE:
2231 return "resource shortage";
2233 return "unknown reason";
2238 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2241 char *msg = NULL, *lang = NULL;
2244 id = packet_get_int();
2245 c = channel_lookup(id);
2247 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2248 packet_disconnect("Received open failure for "
2249 "non-opening channel %d.", id);
2251 reason = packet_get_int();
2252 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2253 msg = packet_get_string(NULL);
2254 lang = packet_get_string(NULL);
2256 logit("channel %d: open failed: %s%s%s", id,
2257 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2264 /* Free the channel. This will also close the socket. */
2270 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2279 /* Get the channel number and verify it. */
2280 id = packet_get_int();
2281 c = channel_lookup(id);
2284 logit("Received window adjust for non-open channel %d.", id);
2287 adjust = packet_get_int();
2289 debug2("channel %d: rcvd adjust %u", id, adjust);
2290 c->remote_window += adjust;
2295 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2299 char *host, *originator_string;
2300 int remote_id, sock = -1;
2302 remote_id = packet_get_int();
2303 host = packet_get_string(NULL);
2304 host_port = packet_get_int();
2306 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2307 originator_string = packet_get_string(NULL);
2309 originator_string = xstrdup("unknown (remote did not supply name)");
2312 sock = channel_connect_to(host, host_port);
2314 c = channel_new("connected socket",
2315 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2316 originator_string, 1);
2317 c->remote_id = remote_id;
2319 xfree(originator_string);
2321 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2322 packet_put_int(remote_id);
2329 /* -- tcp forwarding */
2332 channel_set_af(int af)
2338 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2339 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2342 int sock, r, success = 0, wildcard = 0, is_client;
2343 struct addrinfo hints, *ai, *aitop;
2344 const char *host, *addr;
2345 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2347 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2348 listen_addr : host_to_connect;
2349 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2352 error("No forward host name.");
2355 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2356 error("Forward host name too long.");
2361 * Determine whether or not a port forward listens to loopback,
2362 * specified address or wildcard. On the client, a specified bind
2363 * address will always override gateway_ports. On the server, a
2364 * gateway_ports of 1 (``yes'') will override the client's
2365 * specification and force a wildcard bind, whereas a value of 2
2366 * (``clientspecified'') will bind to whatever address the client
2369 * Special-case listen_addrs are:
2371 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2372 * "" (empty string), "*" -> wildcard v4/v6
2373 * "localhost" -> loopback v4/v6
2376 if (listen_addr == NULL) {
2377 /* No address specified: default to gateway_ports setting */
2380 } else if (gateway_ports || is_client) {
2381 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2382 strcmp(listen_addr, "0.0.0.0") == 0) ||
2383 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2384 (!is_client && gateway_ports == 1))
2386 else if (strcmp(listen_addr, "localhost") != 0)
2390 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2391 type, wildcard, (addr == NULL) ? "NULL" : addr);
2394 * getaddrinfo returns a loopback address if the hostname is
2395 * set to NULL and hints.ai_flags is not AI_PASSIVE
2397 memset(&hints, 0, sizeof(hints));
2398 hints.ai_family = IPv4or6;
2399 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2400 hints.ai_socktype = SOCK_STREAM;
2401 snprintf(strport, sizeof strport, "%d", listen_port);
2402 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2404 /* This really shouldn't happen */
2405 packet_disconnect("getaddrinfo: fatal error: %s",
2408 error("channel_setup_fwd_listener: "
2409 "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
2414 for (ai = aitop; ai; ai = ai->ai_next) {
2415 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2417 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2418 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2419 error("channel_setup_fwd_listener: getnameinfo failed");
2422 /* Create a port to listen for the host. */
2423 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2425 /* this is no error since kernel may not support ipv6 */
2426 verbose("socket: %.100s", strerror(errno));
2430 channel_set_reuseaddr(sock);
2432 debug("Local forwarding listening on %s port %s.", ntop, strport);
2434 /* Bind the socket to the address. */
2435 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2436 /* address can be in use ipv6 address is already bound */
2438 error("bind: %.100s", strerror(errno));
2440 verbose("bind: %.100s", strerror(errno));
2445 /* Start listening for connections on the socket. */
2446 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2447 error("listen: %.100s", strerror(errno));
2451 /* Allocate a channel number for the socket. */
2452 c = channel_new("port listener", type, sock, sock, -1,
2453 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2454 0, "port listener", 1);
2455 strlcpy(c->path, host, sizeof(c->path));
2456 c->host_port = port_to_connect;
2457 c->listening_port = listen_port;
2461 error("channel_setup_fwd_listener: cannot listen to port: %d",
2463 freeaddrinfo(aitop);
2468 channel_cancel_rport_listener(const char *host, u_short port)
2473 for (i = 0; i < channels_alloc; i++) {
2474 Channel *c = channels[i];
2476 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2477 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2478 c->listening_port == port) {
2479 debug2("%s: close channel %d", __func__, i);
2488 /* protocol local port fwd, used by ssh (and sshd in v1) */
2490 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2491 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2493 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2494 listen_host, listen_port, host_to_connect, port_to_connect,
2498 /* protocol v2 remote port fwd, used by sshd */
2500 channel_setup_remote_fwd_listener(const char *listen_address,
2501 u_short listen_port, int gateway_ports)
2503 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2504 listen_address, listen_port, NULL, 0, gateway_ports);
2508 * Initiate forwarding of connections to port "port" on remote host through
2509 * the secure channel to host:port from local side.
2513 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2514 const char *host_to_connect, u_short port_to_connect)
2516 int type, success = 0;
2518 /* Record locally that connection to this host/port is permitted. */
2519 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2520 fatal("channel_request_remote_forwarding: too many forwards");
2522 /* Send the forward request to the remote side. */
2524 const char *address_to_bind;
2525 if (listen_host == NULL)
2526 address_to_bind = "localhost";
2527 else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
2528 address_to_bind = "";
2530 address_to_bind = listen_host;
2532 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2533 packet_put_cstring("tcpip-forward");
2534 packet_put_char(1); /* boolean: want reply */
2535 packet_put_cstring(address_to_bind);
2536 packet_put_int(listen_port);
2538 packet_write_wait();
2539 /* Assume that server accepts the request */
2542 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2543 packet_put_int(listen_port);
2544 packet_put_cstring(host_to_connect);
2545 packet_put_int(port_to_connect);
2547 packet_write_wait();
2549 /* Wait for response from the remote side. */
2550 type = packet_read();
2552 case SSH_SMSG_SUCCESS:
2555 case SSH_SMSG_FAILURE:
2558 /* Unknown packet */
2559 packet_disconnect("Protocol error for port forward request:"
2560 "received packet type %d.", type);
2564 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2565 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2566 permitted_opens[num_permitted_opens].listen_port = listen_port;
2567 num_permitted_opens++;
2569 return (success ? 0 : -1);
2573 * Request cancellation of remote forwarding of connection host:port from
2577 channel_request_rforward_cancel(const char *host, u_short port)
2584 for (i = 0; i < num_permitted_opens; i++) {
2585 if (permitted_opens[i].host_to_connect != NULL &&
2586 permitted_opens[i].listen_port == port)
2589 if (i >= num_permitted_opens) {
2590 debug("%s: requested forward not found", __func__);
2593 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2594 packet_put_cstring("cancel-tcpip-forward");
2596 packet_put_cstring(host == NULL ? "" : host);
2597 packet_put_int(port);
2600 permitted_opens[i].listen_port = 0;
2601 permitted_opens[i].port_to_connect = 0;
2602 xfree(permitted_opens[i].host_to_connect);
2603 permitted_opens[i].host_to_connect = NULL;
2607 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2608 * listening for the port, and sends back a success reply (or disconnect
2609 * message if there was an error).
2612 channel_input_port_forward_request(int is_root, int gateway_ports)
2614 u_short port, host_port;
2618 /* Get arguments from the packet. */
2619 port = packet_get_int();
2620 hostname = packet_get_string(NULL);
2621 host_port = packet_get_int();
2625 * Check that an unprivileged user is not trying to forward a
2628 if (port < IPPORT_RESERVED && !is_root)
2630 "Requested forwarding of port %d but user is not root.",
2633 packet_disconnect("Dynamic forwarding denied.");
2636 /* Initiate forwarding */
2637 success = channel_setup_local_fwd_listener(NULL, port, hostname,
2638 host_port, gateway_ports);
2640 /* Free the argument string. */
2643 return (success ? 0 : -1);
2647 * Permits opening to any host/port if permitted_opens[] is empty. This is
2648 * usually called by the server, because the user could connect to any port
2649 * anyway, and the server has no way to know but to trust the client anyway.
2652 channel_permit_all_opens(void)
2654 if (num_permitted_opens == 0)
2655 all_opens_permitted = 1;
2659 channel_add_permitted_opens(char *host, int port)
2661 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2662 fatal("channel_add_permitted_opens: too many forwards");
2663 debug("allow port forwarding to host %s port %d", host, port);
2665 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2666 permitted_opens[num_permitted_opens].port_to_connect = port;
2667 num_permitted_opens++;
2669 all_opens_permitted = 0;
2673 channel_add_adm_permitted_opens(char *host, int port)
2675 if (num_adm_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2676 fatal("channel_add_adm_permitted_opens: too many forwards");
2677 debug("config allows port forwarding to host %s port %d", host, port);
2679 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
2681 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
2682 return ++num_adm_permitted_opens;
2686 channel_clear_permitted_opens(void)
2690 for (i = 0; i < num_permitted_opens; i++)
2691 if (permitted_opens[i].host_to_connect != NULL)
2692 xfree(permitted_opens[i].host_to_connect);
2693 num_permitted_opens = 0;
2697 channel_clear_adm_permitted_opens(void)
2701 for (i = 0; i < num_adm_permitted_opens; i++)
2702 if (permitted_adm_opens[i].host_to_connect != NULL)
2703 xfree(permitted_adm_opens[i].host_to_connect);
2704 num_adm_permitted_opens = 0;
2707 /* return socket to remote host, port */
2709 connect_to(const char *host, u_short port)
2711 struct addrinfo hints, *ai, *aitop;
2712 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2716 memset(&hints, 0, sizeof(hints));
2717 hints.ai_family = IPv4or6;
2718 hints.ai_socktype = SOCK_STREAM;
2719 snprintf(strport, sizeof strport, "%d", port);
2720 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2721 error("connect_to %.100s: unknown host (%s)", host,
2722 gai_strerror(gaierr));
2725 for (ai = aitop; ai; ai = ai->ai_next) {
2726 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2728 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2729 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2730 error("connect_to: getnameinfo failed");
2733 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2735 if (ai->ai_next == NULL)
2736 error("socket: %.100s", strerror(errno));
2738 verbose("socket: %.100s", strerror(errno));
2741 if (set_nonblock(sock) == -1)
2742 fatal("%s: set_nonblock(%d)", __func__, sock);
2743 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2744 errno != EINPROGRESS) {
2745 error("connect_to %.100s port %s: %.100s", ntop, strport,
2748 continue; /* fail -- try next */
2750 break; /* success */
2753 freeaddrinfo(aitop);
2755 error("connect_to %.100s port %d: failed.", host, port);
2764 channel_connect_by_listen_address(u_short listen_port)
2768 for (i = 0; i < num_permitted_opens; i++)
2769 if (permitted_opens[i].host_to_connect != NULL &&
2770 permitted_opens[i].listen_port == listen_port)
2772 permitted_opens[i].host_to_connect,
2773 permitted_opens[i].port_to_connect);
2774 error("WARNING: Server requests forwarding for unknown listen_port %d",
2779 /* Check if connecting to that port is permitted and connect. */
2781 channel_connect_to(const char *host, u_short port)
2783 int i, permit, permit_adm = 1;
2785 permit = all_opens_permitted;
2787 for (i = 0; i < num_permitted_opens; i++)
2788 if (permitted_opens[i].host_to_connect != NULL &&
2789 permitted_opens[i].port_to_connect == port &&
2790 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2794 if (num_adm_permitted_opens > 0) {
2796 for (i = 0; i < num_adm_permitted_opens; i++)
2797 if (permitted_adm_opens[i].host_to_connect != NULL &&
2798 permitted_adm_opens[i].port_to_connect == port &&
2799 strcmp(permitted_adm_opens[i].host_to_connect, host)
2804 if (!permit || !permit_adm) {
2805 logit("Received request to connect to host %.100s port %d, "
2806 "but the request was denied.", host, port);
2809 return connect_to(host, port);
2813 channel_send_window_changes(void)
2818 for (i = 0; i < channels_alloc; i++) {
2819 if (channels[i] == NULL || !channels[i]->client_tty ||
2820 channels[i]->type != SSH_CHANNEL_OPEN)
2822 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2824 channel_request_start(i, "window-change", 0);
2825 packet_put_int((u_int)ws.ws_col);
2826 packet_put_int((u_int)ws.ws_row);
2827 packet_put_int((u_int)ws.ws_xpixel);
2828 packet_put_int((u_int)ws.ws_ypixel);
2833 /* -- X11 forwarding */
2836 * Creates an internet domain socket for listening for X11 connections.
2837 * Returns 0 and a suitable display number for the DISPLAY variable
2838 * stored in display_numberp , or -1 if an error occurs.
2841 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2842 int single_connection, u_int *display_numberp, int **chanids)
2845 int display_number, sock;
2847 struct addrinfo hints, *ai, *aitop;
2848 char strport[NI_MAXSERV];
2849 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2851 if (chanids == NULL)
2854 for (display_number = x11_display_offset;
2855 display_number < MAX_DISPLAYS;
2857 port = 6000 + display_number;
2858 memset(&hints, 0, sizeof(hints));
2859 hints.ai_family = IPv4or6;
2860 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2861 hints.ai_socktype = SOCK_STREAM;
2862 snprintf(strport, sizeof strport, "%d", port);
2863 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2864 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2867 for (ai = aitop; ai; ai = ai->ai_next) {
2868 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2870 sock = socket(ai->ai_family, ai->ai_socktype,
2873 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2874 error("socket: %.100s", strerror(errno));
2875 freeaddrinfo(aitop);
2878 debug("x11_create_display_inet: Socket family %d not supported",
2884 if (ai->ai_family == AF_INET6) {
2886 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2887 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2890 channel_set_reuseaddr(sock);
2891 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2892 debug2("bind port %d: %.100s", port, strerror(errno));
2898 for (n = 0; n < num_socks; n++) {
2904 socks[num_socks++] = sock;
2905 #ifndef DONT_TRY_OTHER_AF
2906 if (num_socks == NUM_SOCKS)
2909 if (x11_use_localhost) {
2910 if (num_socks == NUM_SOCKS)
2917 freeaddrinfo(aitop);
2921 if (display_number >= MAX_DISPLAYS) {
2922 error("Failed to allocate internet-domain X11 display socket.");
2925 /* Start listening for connections on the socket. */
2926 for (n = 0; n < num_socks; n++) {
2928 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2929 error("listen: %.100s", strerror(errno));
2935 /* Allocate a channel for each socket. */
2936 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
2937 for (n = 0; n < num_socks; n++) {
2939 nc = channel_new("x11 listener",
2940 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2941 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2942 0, "X11 inet listener", 1);
2943 nc->single_connection = single_connection;
2944 (*chanids)[n] = nc->self;
2948 /* Return the display number for the DISPLAY environment variable. */
2949 *display_numberp = display_number;
2954 connect_local_xsocket(u_int dnr)
2957 struct sockaddr_un addr;
2959 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2961 error("socket: %.100s", strerror(errno));
2962 memset(&addr, 0, sizeof(addr));
2963 addr.sun_family = AF_UNIX;
2964 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2965 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
2968 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2973 x11_connect_display(void)
2975 u_int display_number;
2976 const char *display;
2977 char buf[1024], *cp;
2978 struct addrinfo hints, *ai, *aitop;
2979 char strport[NI_MAXSERV];
2980 int gaierr, sock = 0;
2982 /* Try to open a socket for the local X server. */
2983 display = getenv("DISPLAY");
2985 error("DISPLAY not set.");
2989 * Now we decode the value of the DISPLAY variable and make a
2990 * connection to the real X server.
2994 * Check if it is a unix domain socket. Unix domain displays are in
2995 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2997 if (strncmp(display, "unix:", 5) == 0 ||
2998 display[0] == ':') {
2999 /* Connect to the unix domain socket. */
3000 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
3001 error("Could not parse display number from DISPLAY: %.100s",
3005 /* Create a socket. */
3006 sock = connect_local_xsocket(display_number);
3010 /* OK, we now have a connection to the display. */
3014 * Connect to an inet socket. The DISPLAY value is supposedly
3015 * hostname:d[.s], where hostname may also be numeric IP address.
3017 strlcpy(buf, display, sizeof(buf));
3018 cp = strchr(buf, ':');
3020 error("Could not find ':' in DISPLAY: %.100s", display);
3024 /* buf now contains the host name. But first we parse the display number. */
3025 if (sscanf(cp + 1, "%u", &display_number) != 1) {
3026 error("Could not parse display number from DISPLAY: %.100s",
3031 /* Look up the host address */
3032 memset(&hints, 0, sizeof(hints));
3033 hints.ai_family = IPv4or6;
3034 hints.ai_socktype = SOCK_STREAM;
3035 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
3036 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
3037 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
3040 for (ai = aitop; ai; ai = ai->ai_next) {
3041 /* Create a socket. */
3042 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3044 debug2("socket: %.100s", strerror(errno));
3047 /* Connect it to the display. */
3048 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3049 debug2("connect %.100s port %u: %.100s", buf,
3050 6000 + display_number, strerror(errno));
3057 freeaddrinfo(aitop);
3059 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3068 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3069 * the remote channel number. We should do whatever we want, and respond
3070 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3075 x11_input_open(int type, u_int32_t seq, void *ctxt)
3078 int remote_id, sock = 0;
3081 debug("Received X11 open request.");
3083 remote_id = packet_get_int();
3085 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3086 remote_host = packet_get_string(NULL);
3088 remote_host = xstrdup("unknown (remote did not supply name)");
3092 /* Obtain a connection to the real X display. */
3093 sock = x11_connect_display();
3095 /* Allocate a channel for this connection. */
3096 c = channel_new("connected x11 socket",
3097 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3099 c->remote_id = remote_id;
3104 /* Send refusal to the remote host. */
3105 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3106 packet_put_int(remote_id);
3108 /* Send a confirmation to the remote host. */
3109 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3110 packet_put_int(remote_id);
3111 packet_put_int(c->self);
3116 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3119 deny_input_open(int type, u_int32_t seq, void *ctxt)
3121 int rchan = packet_get_int();
3124 case SSH_SMSG_AGENT_OPEN:
3125 error("Warning: ssh server tried agent forwarding.");
3127 case SSH_SMSG_X11_OPEN:
3128 error("Warning: ssh server tried X11 forwarding.");
3131 error("deny_input_open: type %d", type);
3134 error("Warning: this is probably a break-in attempt by a malicious server.");
3135 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3136 packet_put_int(rchan);
3141 * Requests forwarding of X11 connections, generates fake authentication
3142 * data, and enables authentication spoofing.
3143 * This should be called in the client only.
3146 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3147 const char *proto, const char *data)
3149 u_int data_len = (u_int) strlen(data) / 2;
3156 if (x11_saved_display == NULL)
3157 x11_saved_display = xstrdup(disp);
3158 else if (strcmp(disp, x11_saved_display) != 0) {
3159 error("x11_request_forwarding_with_spoofing: different "
3160 "$DISPLAY already forwarded");
3166 cp = strchr(disp, ':');
3168 cp = strchr(cp, '.');
3170 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3174 if (x11_saved_proto == NULL) {
3175 /* Save protocol name. */
3176 x11_saved_proto = xstrdup(proto);
3178 * Extract real authentication data and generate fake data
3179 * of the same length.
3181 x11_saved_data = xmalloc(data_len);
3182 x11_fake_data = xmalloc(data_len);
3183 for (i = 0; i < data_len; i++) {
3184 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3185 fatal("x11_request_forwarding: bad "
3186 "authentication data: %.100s", data);
3189 x11_saved_data[i] = value;
3190 x11_fake_data[i] = rnd & 0xff;
3193 x11_saved_data_len = data_len;
3194 x11_fake_data_len = data_len;
3197 /* Convert the fake data into hex. */
3198 new_data = tohex(x11_fake_data, data_len);
3200 /* Send the request packet. */
3202 channel_request_start(client_session_id, "x11-req", 0);
3203 packet_put_char(0); /* XXX bool single connection */
3205 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3207 packet_put_cstring(proto);
3208 packet_put_cstring(new_data);
3209 packet_put_int(screen_number);
3211 packet_write_wait();
3216 /* -- agent forwarding */
3218 /* Sends a message to the server to request authentication fd forwarding. */
3221 auth_request_forwarding(void)
3223 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3225 packet_write_wait();