1 /* $OpenBSD: channels.c,v 1.252 2006/07/10 12:08:08 djm 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>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
66 #include "pathnames.h"
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 u_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;
90 /* -- tcp forwarding */
93 * Data structure for storing which hosts are permitted for forward requests.
94 * The local sides of any remote forwards are stored in this array to prevent
95 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
96 * network (which might be behind a firewall).
99 char *host_to_connect; /* Connect to 'host'. */
100 u_short port_to_connect; /* Connect to 'port'. */
101 u_short listen_port; /* Remote side should listen port number. */
104 /* List of all permitted host/port pairs to connect. */
105 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
107 /* Number of permitted host/port pairs in the array. */
108 static int num_permitted_opens = 0;
110 * If this is true, all opens are permitted. This is the case on the server
111 * on which we have to trust the client anyway, and the user could do
112 * anything after logging in anyway.
114 static int all_opens_permitted = 0;
117 /* -- X11 forwarding */
119 /* Maximum number of fake X11 displays to try. */
120 #define MAX_DISPLAYS 1000
122 /* Saved X11 local (client) display. */
123 static char *x11_saved_display = NULL;
125 /* Saved X11 authentication protocol name. */
126 static char *x11_saved_proto = NULL;
128 /* Saved X11 authentication data. This is the real data. */
129 static char *x11_saved_data = NULL;
130 static u_int x11_saved_data_len = 0;
133 * Fake X11 authentication data. This is what the server will be sending us;
134 * we should replace any occurrences of this by the real data.
136 static u_char *x11_fake_data = NULL;
137 static u_int x11_fake_data_len;
140 /* -- agent forwarding */
144 /* AF_UNSPEC or AF_INET or AF_INET6 */
145 static int IPv4or6 = AF_UNSPEC;
148 static void port_open_helper(Channel *c, char *rtype);
150 /* -- channel core */
153 channel_by_id(int id)
157 if (id < 0 || (u_int)id >= channels_alloc) {
158 logit("channel_by_id: %d: bad id", id);
163 logit("channel_by_id: %d: bad id: channel free", id);
170 * Returns the channel if it is allowed to receive protocol messages.
171 * Private channels, like listening sockets, may not receive messages.
174 channel_lookup(int id)
178 if ((c = channel_by_id(id)) == NULL)
182 case SSH_CHANNEL_X11_OPEN:
183 case SSH_CHANNEL_LARVAL:
184 case SSH_CHANNEL_CONNECTING:
185 case SSH_CHANNEL_DYNAMIC:
186 case SSH_CHANNEL_OPENING:
187 case SSH_CHANNEL_OPEN:
188 case SSH_CHANNEL_INPUT_DRAINING:
189 case SSH_CHANNEL_OUTPUT_DRAINING:
192 logit("Non-public channel %d, type %d.", id, c->type);
197 * Register filedescriptors for a channel, used when allocating a channel or
198 * when the channel consumer/producer is ready, e.g. shell exec'd
201 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
202 int extusage, int nonblock)
204 /* Update the maximum file descriptor value. */
205 channel_max_fd = MAX(channel_max_fd, rfd);
206 channel_max_fd = MAX(channel_max_fd, wfd);
207 channel_max_fd = MAX(channel_max_fd, efd);
209 /* XXX set close-on-exec -markus */
213 c->sock = (rfd == wfd) ? rfd : -1;
214 c->ctl_fd = -1; /* XXX: set elsewhere */
216 c->extended_usage = extusage;
218 /* XXX ugly hack: nonblock is only set by the server */
219 if (nonblock && isatty(c->rfd)) {
220 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
222 if (!isatty(c->wfd)) {
223 error("channel %d: wfd %d is not a tty?",
229 c->wfd_isatty = isatty(c->wfd);
231 /* enable nonblocking mode */
243 * Allocate a new channel object and set its type and socket. This will cause
244 * remote_name to be freed.
247 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
248 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
254 /* Do initial allocation if this is the first call. */
255 if (channels_alloc == 0) {
257 channels = xcalloc(channels_alloc, sizeof(Channel *));
258 for (i = 0; i < channels_alloc; i++)
261 /* Try to find a free slot where to put the new channel. */
262 for (found = -1, i = 0; i < channels_alloc; i++)
263 if (channels[i] == NULL) {
264 /* Found a free slot. */
269 /* There are no free slots. Take last+1 slot and expand the array. */
270 found = channels_alloc;
271 if (channels_alloc > 10000)
272 fatal("channel_new: internal error: channels_alloc %d "
273 "too big.", channels_alloc);
274 channels = xrealloc(channels, channels_alloc + 10,
276 channels_alloc += 10;
277 debug2("channel: expanding %d", channels_alloc);
278 for (i = found; i < channels_alloc; i++)
281 /* Initialize and return new channel. */
282 c = channels[found] = xcalloc(1, sizeof(Channel));
283 buffer_init(&c->input);
284 buffer_init(&c->output);
285 buffer_init(&c->extended);
286 c->ostate = CHAN_OUTPUT_OPEN;
287 c->istate = CHAN_INPUT_OPEN;
289 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
293 c->local_window = window;
294 c->local_window_max = window;
295 c->local_consumed = 0;
296 c->local_maxpacket = maxpack;
298 c->remote_name = xstrdup(remote_name);
299 c->remote_window = 0;
300 c->remote_maxpacket = 0;
302 c->single_connection = 0;
303 c->detach_user = NULL;
306 c->confirm_ctx = NULL;
307 c->input_filter = NULL;
308 c->output_filter = NULL;
309 debug("channel %d: new [%s]", found, remote_name);
314 channel_find_maxfd(void)
320 for (i = 0; i < channels_alloc; i++) {
323 max = MAX(max, c->rfd);
324 max = MAX(max, c->wfd);
325 max = MAX(max, c->efd);
332 channel_close_fd(int *fdp)
334 int ret = 0, fd = *fdp;
339 if (fd == channel_max_fd)
340 channel_max_fd = channel_find_maxfd();
345 /* Close all channel fd/socket. */
347 channel_close_fds(Channel *c)
349 debug3("channel %d: close_fds r %d w %d e %d c %d",
350 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
352 channel_close_fd(&c->sock);
353 channel_close_fd(&c->ctl_fd);
354 channel_close_fd(&c->rfd);
355 channel_close_fd(&c->wfd);
356 channel_close_fd(&c->efd);
359 /* Free the channel and close its fd/socket. */
361 channel_free(Channel *c)
366 for (n = 0, i = 0; i < channels_alloc; i++)
369 debug("channel %d: free: %s, nchannels %u", c->self,
370 c->remote_name ? c->remote_name : "???", n);
372 s = channel_open_message();
373 debug3("channel %d: status: %s", c->self, s);
377 shutdown(c->sock, SHUT_RDWR);
379 shutdown(c->ctl_fd, SHUT_RDWR);
380 channel_close_fds(c);
381 buffer_free(&c->input);
382 buffer_free(&c->output);
383 buffer_free(&c->extended);
384 if (c->remote_name) {
385 xfree(c->remote_name);
386 c->remote_name = NULL;
388 channels[c->self] = NULL;
393 channel_free_all(void)
397 for (i = 0; i < channels_alloc; i++)
398 if (channels[i] != NULL)
399 channel_free(channels[i]);
403 * Closes the sockets/fds of all channels. This is used to close extra file
404 * descriptors after a fork.
407 channel_close_all(void)
411 for (i = 0; i < channels_alloc; i++)
412 if (channels[i] != NULL)
413 channel_close_fds(channels[i]);
417 * Stop listening to channels.
420 channel_stop_listening(void)
425 for (i = 0; i < channels_alloc; i++) {
429 case SSH_CHANNEL_AUTH_SOCKET:
430 case SSH_CHANNEL_PORT_LISTENER:
431 case SSH_CHANNEL_RPORT_LISTENER:
432 case SSH_CHANNEL_X11_LISTENER:
433 channel_close_fd(&c->sock);
442 * Returns true if no channel has too much buffered data, and false if one or
443 * more channel is overfull.
446 channel_not_very_much_buffered_data(void)
451 for (i = 0; i < channels_alloc; i++) {
453 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
456 buffer_len(&c->input) > packet_get_maxsize()) {
457 debug2("channel %d: big input buffer %d",
458 c->self, buffer_len(&c->input));
462 if (buffer_len(&c->output) > packet_get_maxsize()) {
463 debug2("channel %d: big output buffer %u > %u",
464 c->self, buffer_len(&c->output),
465 packet_get_maxsize());
473 /* Returns true if any channel is still open. */
475 channel_still_open(void)
480 for (i = 0; i < channels_alloc; i++) {
485 case SSH_CHANNEL_X11_LISTENER:
486 case SSH_CHANNEL_PORT_LISTENER:
487 case SSH_CHANNEL_RPORT_LISTENER:
488 case SSH_CHANNEL_CLOSED:
489 case SSH_CHANNEL_AUTH_SOCKET:
490 case SSH_CHANNEL_DYNAMIC:
491 case SSH_CHANNEL_CONNECTING:
492 case SSH_CHANNEL_ZOMBIE:
494 case SSH_CHANNEL_LARVAL:
496 fatal("cannot happen: SSH_CHANNEL_LARVAL");
498 case SSH_CHANNEL_OPENING:
499 case SSH_CHANNEL_OPEN:
500 case SSH_CHANNEL_X11_OPEN:
502 case SSH_CHANNEL_INPUT_DRAINING:
503 case SSH_CHANNEL_OUTPUT_DRAINING:
505 fatal("cannot happen: OUT_DRAIN");
508 fatal("channel_still_open: bad channel type %d", c->type);
515 /* Returns the id of an open channel suitable for keepaliving */
517 channel_find_open(void)
522 for (i = 0; i < channels_alloc; i++) {
524 if (c == NULL || c->remote_id < 0)
527 case SSH_CHANNEL_CLOSED:
528 case SSH_CHANNEL_DYNAMIC:
529 case SSH_CHANNEL_X11_LISTENER:
530 case SSH_CHANNEL_PORT_LISTENER:
531 case SSH_CHANNEL_RPORT_LISTENER:
532 case SSH_CHANNEL_OPENING:
533 case SSH_CHANNEL_CONNECTING:
534 case SSH_CHANNEL_ZOMBIE:
536 case SSH_CHANNEL_LARVAL:
537 case SSH_CHANNEL_AUTH_SOCKET:
538 case SSH_CHANNEL_OPEN:
539 case SSH_CHANNEL_X11_OPEN:
541 case SSH_CHANNEL_INPUT_DRAINING:
542 case SSH_CHANNEL_OUTPUT_DRAINING:
544 fatal("cannot happen: OUT_DRAIN");
547 fatal("channel_find_open: bad channel type %d", c->type);
556 * Returns a message describing the currently open forwarded connections,
557 * suitable for sending to the client. The message contains crlf pairs for
561 channel_open_message(void)
568 buffer_init(&buffer);
569 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
570 buffer_append(&buffer, buf, strlen(buf));
571 for (i = 0; i < channels_alloc; i++) {
576 case SSH_CHANNEL_X11_LISTENER:
577 case SSH_CHANNEL_PORT_LISTENER:
578 case SSH_CHANNEL_RPORT_LISTENER:
579 case SSH_CHANNEL_CLOSED:
580 case SSH_CHANNEL_AUTH_SOCKET:
581 case SSH_CHANNEL_ZOMBIE:
583 case SSH_CHANNEL_LARVAL:
584 case SSH_CHANNEL_OPENING:
585 case SSH_CHANNEL_CONNECTING:
586 case SSH_CHANNEL_DYNAMIC:
587 case SSH_CHANNEL_OPEN:
588 case SSH_CHANNEL_X11_OPEN:
589 case SSH_CHANNEL_INPUT_DRAINING:
590 case SSH_CHANNEL_OUTPUT_DRAINING:
591 snprintf(buf, sizeof buf,
592 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
593 c->self, c->remote_name,
594 c->type, c->remote_id,
595 c->istate, buffer_len(&c->input),
596 c->ostate, buffer_len(&c->output),
597 c->rfd, c->wfd, c->ctl_fd);
598 buffer_append(&buffer, buf, strlen(buf));
601 fatal("channel_open_message: bad channel type %d", c->type);
605 buffer_append(&buffer, "\0", 1);
606 cp = xstrdup(buffer_ptr(&buffer));
607 buffer_free(&buffer);
612 channel_send_open(int id)
614 Channel *c = channel_lookup(id);
617 logit("channel_send_open: %d: bad id", id);
620 debug2("channel %d: send open", id);
621 packet_start(SSH2_MSG_CHANNEL_OPEN);
622 packet_put_cstring(c->ctype);
623 packet_put_int(c->self);
624 packet_put_int(c->local_window);
625 packet_put_int(c->local_maxpacket);
630 channel_request_start(int id, char *service, int wantconfirm)
632 Channel *c = channel_lookup(id);
635 logit("channel_request_start: %d: unknown channel id", id);
638 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
639 packet_start(SSH2_MSG_CHANNEL_REQUEST);
640 packet_put_int(c->remote_id);
641 packet_put_cstring(service);
642 packet_put_char(wantconfirm);
646 channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
648 Channel *c = channel_lookup(id);
651 logit("channel_register_comfirm: %d: bad id", id);
655 c->confirm_ctx = ctx;
659 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
661 Channel *c = channel_by_id(id);
664 logit("channel_register_cleanup: %d: bad id", id);
668 c->detach_close = do_close;
672 channel_cancel_cleanup(int id)
674 Channel *c = channel_by_id(id);
677 logit("channel_cancel_cleanup: %d: bad id", id);
680 c->detach_user = NULL;
685 channel_register_filter(int id, channel_infilter_fn *ifn,
686 channel_outfilter_fn *ofn)
688 Channel *c = channel_lookup(id);
691 logit("channel_register_filter: %d: bad id", id);
694 c->input_filter = ifn;
695 c->output_filter = ofn;
699 channel_set_fds(int id, int rfd, int wfd, int efd,
700 int extusage, int nonblock, u_int window_max)
702 Channel *c = channel_lookup(id);
704 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
705 fatal("channel_activate for non-larval channel %d.", id);
706 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
707 c->type = SSH_CHANNEL_OPEN;
708 c->local_window = c->local_window_max = window_max;
709 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
710 packet_put_int(c->remote_id);
711 packet_put_int(c->local_window);
716 * 'channel_pre*' are called just before select() to add any bits relevant to
717 * channels in the select bitmasks.
720 * 'channel_post*': perform any appropriate operations for channels which
721 * have events pending.
723 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
724 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
725 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
728 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
730 FD_SET(c->sock, readset);
734 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
736 debug3("channel %d: waiting for connection", c->self);
737 FD_SET(c->sock, writeset);
741 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
743 if (buffer_len(&c->input) < packet_get_maxsize())
744 FD_SET(c->sock, readset);
745 if (buffer_len(&c->output) > 0)
746 FD_SET(c->sock, writeset);
750 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
752 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
754 if (c->istate == CHAN_INPUT_OPEN &&
756 buffer_len(&c->input) < limit &&
757 buffer_check_alloc(&c->input, CHAN_RBUF))
758 FD_SET(c->rfd, readset);
759 if (c->ostate == CHAN_OUTPUT_OPEN ||
760 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
761 if (buffer_len(&c->output) > 0) {
762 FD_SET(c->wfd, writeset);
763 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
764 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
765 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
766 c->self, c->efd, buffer_len(&c->extended));
771 /** XXX check close conditions, too */
772 if (compat20 && c->efd != -1) {
773 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
774 buffer_len(&c->extended) > 0)
775 FD_SET(c->efd, writeset);
776 else if (!(c->flags & CHAN_EOF_SENT) &&
777 c->extended_usage == CHAN_EXTENDED_READ &&
778 buffer_len(&c->extended) < c->remote_window)
779 FD_SET(c->efd, readset);
781 /* XXX: What about efd? races? */
782 if (compat20 && c->ctl_fd != -1 &&
783 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
784 FD_SET(c->ctl_fd, readset);
788 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
790 if (buffer_len(&c->input) == 0) {
791 packet_start(SSH_MSG_CHANNEL_CLOSE);
792 packet_put_int(c->remote_id);
794 c->type = SSH_CHANNEL_CLOSED;
795 debug2("channel %d: closing after input drain.", c->self);
800 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
802 if (buffer_len(&c->output) == 0)
805 FD_SET(c->sock, writeset);
809 * This is a special state for X11 authentication spoofing. An opened X11
810 * connection (when authentication spoofing is being done) remains in this
811 * state until the first packet has been completely read. The authentication
812 * data in that packet is then substituted by the real data if it matches the
813 * fake data, and the channel is put into normal mode.
814 * XXX All this happens at the client side.
815 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
818 x11_open_helper(Buffer *b)
821 u_int proto_len, data_len;
823 /* Check if the fixed size part of the packet is in buffer. */
824 if (buffer_len(b) < 12)
827 /* Parse the lengths of variable-length fields. */
829 if (ucp[0] == 0x42) { /* Byte order MSB first. */
830 proto_len = 256 * ucp[6] + ucp[7];
831 data_len = 256 * ucp[8] + ucp[9];
832 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
833 proto_len = ucp[6] + 256 * ucp[7];
834 data_len = ucp[8] + 256 * ucp[9];
836 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
841 /* Check if the whole packet is in buffer. */
843 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
846 /* Check if authentication protocol matches. */
847 if (proto_len != strlen(x11_saved_proto) ||
848 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
849 debug2("X11 connection uses different authentication protocol.");
852 /* Check if authentication data matches our fake data. */
853 if (data_len != x11_fake_data_len ||
854 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
855 x11_fake_data, x11_fake_data_len) != 0) {
856 debug2("X11 auth data does not match fake data.");
859 /* Check fake data length */
860 if (x11_fake_data_len != x11_saved_data_len) {
861 error("X11 fake_data_len %d != saved_data_len %d",
862 x11_fake_data_len, x11_saved_data_len);
866 * Received authentication protocol and data match
867 * our fake data. Substitute the fake data with real
870 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
871 x11_saved_data, x11_saved_data_len);
876 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
878 int ret = x11_open_helper(&c->output);
881 /* Start normal processing for the channel. */
882 c->type = SSH_CHANNEL_OPEN;
883 channel_pre_open_13(c, readset, writeset);
884 } else if (ret == -1) {
886 * We have received an X11 connection that has bad
887 * authentication information.
889 logit("X11 connection rejected because of wrong authentication.");
890 buffer_clear(&c->input);
891 buffer_clear(&c->output);
892 channel_close_fd(&c->sock);
894 c->type = SSH_CHANNEL_CLOSED;
895 packet_start(SSH_MSG_CHANNEL_CLOSE);
896 packet_put_int(c->remote_id);
902 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
904 int ret = x11_open_helper(&c->output);
906 /* c->force_drain = 1; */
909 c->type = SSH_CHANNEL_OPEN;
910 channel_pre_open(c, readset, writeset);
911 } else if (ret == -1) {
912 logit("X11 connection rejected because of wrong authentication.");
913 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
915 buffer_clear(&c->input);
917 buffer_clear(&c->output);
918 /* for proto v1, the peer will send an IEOF */
920 chan_write_failed(c);
922 c->type = SSH_CHANNEL_OPEN;
923 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
927 /* try to decode a socks4 header */
929 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
932 u_int len, have, i, found;
938 struct in_addr dest_addr;
941 debug2("channel %d: decode socks4", c->self);
943 have = buffer_len(&c->input);
944 len = sizeof(s4_req);
947 p = buffer_ptr(&c->input);
948 for (found = 0, i = len; i < have; i++) {
954 /* the peer is probably sending garbage */
955 debug("channel %d: decode socks4: too long",
962 buffer_get(&c->input, (char *)&s4_req.version, 1);
963 buffer_get(&c->input, (char *)&s4_req.command, 1);
964 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
965 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
966 have = buffer_len(&c->input);
967 p = buffer_ptr(&c->input);
969 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
971 fatal("channel %d: decode socks4: len %d > have %d",
973 strlcpy(username, p, sizeof(username));
974 buffer_consume(&c->input, len);
975 buffer_consume(&c->input, 1); /* trailing '\0' */
977 host = inet_ntoa(s4_req.dest_addr);
978 strlcpy(c->path, host, sizeof(c->path));
979 c->host_port = ntohs(s4_req.dest_port);
981 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
982 c->self, host, c->host_port, s4_req.command);
984 if (s4_req.command != 1) {
985 debug("channel %d: cannot handle: socks4 cn %d",
986 c->self, s4_req.command);
989 s4_rsp.version = 0; /* vn: 0 for reply */
990 s4_rsp.command = 90; /* cd: req granted */
991 s4_rsp.dest_port = 0; /* ignored */
992 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
993 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
997 /* try to decode a socks5 header */
998 #define SSH_SOCKS5_AUTHDONE 0x1000
999 #define SSH_SOCKS5_NOAUTH 0x00
1000 #define SSH_SOCKS5_IPV4 0x01
1001 #define SSH_SOCKS5_DOMAIN 0x03
1002 #define SSH_SOCKS5_IPV6 0x04
1003 #define SSH_SOCKS5_CONNECT 0x01
1004 #define SSH_SOCKS5_SUCCESS 0x00
1007 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1015 u_int16_t dest_port;
1016 u_char *p, dest_addr[255+1];
1017 u_int have, need, i, found, nmethods, addrlen, af;
1019 debug2("channel %d: decode socks5", c->self);
1020 p = buffer_ptr(&c->input);
1023 have = buffer_len(&c->input);
1024 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1025 /* format: ver | nmethods | methods */
1029 if (have < nmethods + 2)
1031 /* look for method: "NO AUTHENTICATION REQUIRED" */
1032 for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1033 if (p[i] == SSH_SOCKS5_NOAUTH ) {
1039 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1043 buffer_consume(&c->input, nmethods + 2);
1044 buffer_put_char(&c->output, 0x05); /* version */
1045 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1046 FD_SET(c->sock, writeset);
1047 c->flags |= SSH_SOCKS5_AUTHDONE;
1048 debug2("channel %d: socks5 auth done", c->self);
1049 return 0; /* need more */
1051 debug2("channel %d: socks5 post auth", c->self);
1052 if (have < sizeof(s5_req)+1)
1053 return 0; /* need more */
1054 memcpy(&s5_req, p, sizeof(s5_req));
1055 if (s5_req.version != 0x05 ||
1056 s5_req.command != SSH_SOCKS5_CONNECT ||
1057 s5_req.reserved != 0x00) {
1058 debug2("channel %d: only socks5 connect supported", c->self);
1061 switch (s5_req.atyp){
1062 case SSH_SOCKS5_IPV4:
1066 case SSH_SOCKS5_DOMAIN:
1067 addrlen = p[sizeof(s5_req)];
1070 case SSH_SOCKS5_IPV6:
1075 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1078 need = sizeof(s5_req) + addrlen + 2;
1079 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1083 buffer_consume(&c->input, sizeof(s5_req));
1084 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1085 buffer_consume(&c->input, 1); /* host string length */
1086 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1087 buffer_get(&c->input, (char *)&dest_port, 2);
1088 dest_addr[addrlen] = '\0';
1089 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1090 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1091 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1093 c->host_port = ntohs(dest_port);
1095 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1096 c->self, c->path, c->host_port, s5_req.command);
1098 s5_rsp.version = 0x05;
1099 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1100 s5_rsp.reserved = 0; /* ignored */
1101 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1102 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1103 dest_port = 0; /* ignored */
1105 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1106 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1107 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1111 /* dynamic port forwarding */
1113 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1119 have = buffer_len(&c->input);
1121 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1122 /* buffer_dump(&c->input); */
1123 /* check if the fixed size part of the packet is in buffer. */
1126 FD_SET(c->sock, readset);
1129 /* try to guess the protocol */
1130 p = buffer_ptr(&c->input);
1133 ret = channel_decode_socks4(c, readset, writeset);
1136 ret = channel_decode_socks5(c, readset, writeset);
1144 } else if (ret == 0) {
1145 debug2("channel %d: pre_dynamic: need more", c->self);
1147 FD_SET(c->sock, readset);
1149 /* switch to the next state */
1150 c->type = SSH_CHANNEL_OPENING;
1151 port_open_helper(c, "direct-tcpip");
1155 /* This is our fake X11 server socket. */
1157 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1160 struct sockaddr addr;
1163 char buf[16384], *remote_ipaddr;
1166 if (FD_ISSET(c->sock, readset)) {
1167 debug("X11 connection requested.");
1168 addrlen = sizeof(addr);
1169 newsock = accept(c->sock, &addr, &addrlen);
1170 if (c->single_connection) {
1171 debug2("single_connection: closing X11 listener.");
1172 channel_close_fd(&c->sock);
1176 error("accept: %.100s", strerror(errno));
1179 set_nodelay(newsock);
1180 remote_ipaddr = get_peer_ipaddr(newsock);
1181 remote_port = get_peer_port(newsock);
1182 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1183 remote_ipaddr, remote_port);
1185 nc = channel_new("accepted x11 socket",
1186 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1187 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1189 packet_start(SSH2_MSG_CHANNEL_OPEN);
1190 packet_put_cstring("x11");
1191 packet_put_int(nc->self);
1192 packet_put_int(nc->local_window_max);
1193 packet_put_int(nc->local_maxpacket);
1194 /* originator ipaddr and port */
1195 packet_put_cstring(remote_ipaddr);
1196 if (datafellows & SSH_BUG_X11FWD) {
1197 debug2("ssh2 x11 bug compat mode");
1199 packet_put_int(remote_port);
1203 packet_start(SSH_SMSG_X11_OPEN);
1204 packet_put_int(nc->self);
1205 if (packet_get_protocol_flags() &
1206 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1207 packet_put_cstring(buf);
1210 xfree(remote_ipaddr);
1215 port_open_helper(Channel *c, char *rtype)
1219 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1220 int remote_port = get_peer_port(c->sock);
1222 direct = (strcmp(rtype, "direct-tcpip") == 0);
1224 snprintf(buf, sizeof buf,
1225 "%s: listening port %d for %.100s port %d, "
1226 "connect from %.200s port %d",
1227 rtype, c->listening_port, c->path, c->host_port,
1228 remote_ipaddr, remote_port);
1230 xfree(c->remote_name);
1231 c->remote_name = xstrdup(buf);
1234 packet_start(SSH2_MSG_CHANNEL_OPEN);
1235 packet_put_cstring(rtype);
1236 packet_put_int(c->self);
1237 packet_put_int(c->local_window_max);
1238 packet_put_int(c->local_maxpacket);
1240 /* target host, port */
1241 packet_put_cstring(c->path);
1242 packet_put_int(c->host_port);
1244 /* listen address, port */
1245 packet_put_cstring(c->path);
1246 packet_put_int(c->listening_port);
1248 /* originator host and port */
1249 packet_put_cstring(remote_ipaddr);
1250 packet_put_int((u_int)remote_port);
1253 packet_start(SSH_MSG_PORT_OPEN);
1254 packet_put_int(c->self);
1255 packet_put_cstring(c->path);
1256 packet_put_int(c->host_port);
1257 if (packet_get_protocol_flags() &
1258 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1259 packet_put_cstring(c->remote_name);
1262 xfree(remote_ipaddr);
1266 channel_set_reuseaddr(int fd)
1271 * Set socket options.
1272 * Allow local port reuse in TIME_WAIT.
1274 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1275 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1279 * This socket is listening for connections to a forwarded TCP/IP port.
1282 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1285 struct sockaddr addr;
1286 int newsock, nextstate;
1290 if (FD_ISSET(c->sock, readset)) {
1291 debug("Connection to port %d forwarding "
1292 "to %.100s port %d requested.",
1293 c->listening_port, c->path, c->host_port);
1295 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1296 nextstate = SSH_CHANNEL_OPENING;
1297 rtype = "forwarded-tcpip";
1299 if (c->host_port == 0) {
1300 nextstate = SSH_CHANNEL_DYNAMIC;
1301 rtype = "dynamic-tcpip";
1303 nextstate = SSH_CHANNEL_OPENING;
1304 rtype = "direct-tcpip";
1308 addrlen = sizeof(addr);
1309 newsock = accept(c->sock, &addr, &addrlen);
1311 error("accept: %.100s", strerror(errno));
1314 set_nodelay(newsock);
1315 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1316 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1317 nc->listening_port = c->listening_port;
1318 nc->host_port = c->host_port;
1319 strlcpy(nc->path, c->path, sizeof(nc->path));
1321 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1323 * do not call the channel_post handler until
1324 * this flag has been reset by a pre-handler.
1325 * otherwise the FD_ISSET calls might overflow
1329 port_open_helper(nc, rtype);
1335 * This is the authentication agent socket listening for connections from
1339 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1343 struct sockaddr addr;
1346 if (FD_ISSET(c->sock, readset)) {
1347 addrlen = sizeof(addr);
1348 newsock = accept(c->sock, &addr, &addrlen);
1350 error("accept from auth socket: %.100s", strerror(errno));
1353 nc = channel_new("accepted auth socket",
1354 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1355 c->local_window_max, c->local_maxpacket,
1356 0, "accepted auth socket", 1);
1358 packet_start(SSH2_MSG_CHANNEL_OPEN);
1359 packet_put_cstring("auth-agent@openssh.com");
1360 packet_put_int(nc->self);
1361 packet_put_int(c->local_window_max);
1362 packet_put_int(c->local_maxpacket);
1364 packet_start(SSH_SMSG_AGENT_OPEN);
1365 packet_put_int(nc->self);
1372 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1375 socklen_t sz = sizeof(err);
1377 if (FD_ISSET(c->sock, writeset)) {
1378 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1380 error("getsockopt SO_ERROR failed");
1383 debug("channel %d: connected", c->self);
1384 c->type = SSH_CHANNEL_OPEN;
1386 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1387 packet_put_int(c->remote_id);
1388 packet_put_int(c->self);
1389 packet_put_int(c->local_window);
1390 packet_put_int(c->local_maxpacket);
1392 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1393 packet_put_int(c->remote_id);
1394 packet_put_int(c->self);
1397 debug("channel %d: not connected: %s",
1398 c->self, strerror(err));
1400 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1401 packet_put_int(c->remote_id);
1402 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1403 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1404 packet_put_cstring(strerror(err));
1405 packet_put_cstring("");
1408 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1409 packet_put_int(c->remote_id);
1418 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1420 char buf[CHAN_RBUF];
1424 FD_ISSET(c->rfd, readset)) {
1426 len = read(c->rfd, buf, sizeof(buf));
1427 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1429 #ifndef PTY_ZEROREAD
1432 if ((!c->isatty && len <= 0) ||
1433 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1435 debug2("channel %d: read<=0 rfd %d len %d",
1436 c->self, c->rfd, len);
1437 if (c->type != SSH_CHANNEL_OPEN) {
1438 debug2("channel %d: not open", c->self);
1441 } else if (compat13) {
1442 buffer_clear(&c->output);
1443 c->type = SSH_CHANNEL_INPUT_DRAINING;
1444 debug2("channel %d: input draining.", c->self);
1446 chan_read_failed(c);
1450 if (c->input_filter != NULL) {
1451 if (c->input_filter(c, buf, len) == -1) {
1452 debug2("channel %d: filter stops", c->self);
1453 chan_read_failed(c);
1455 } else if (c->datagram) {
1456 buffer_put_string(&c->input, buf, len);
1458 buffer_append(&c->input, buf, len);
1465 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1468 u_char *data = NULL, *buf;
1472 /* Send buffered output data to the socket. */
1474 FD_ISSET(c->wfd, writeset) &&
1475 buffer_len(&c->output) > 0) {
1476 if (c->output_filter != NULL) {
1477 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1478 debug2("channel %d: filter stops", c->self);
1479 if (c->type != SSH_CHANNEL_OPEN)
1482 chan_write_failed(c);
1485 } else if (c->datagram) {
1486 buf = data = buffer_get_string(&c->output, &dlen);
1488 buf = data = buffer_ptr(&c->output);
1489 dlen = buffer_len(&c->output);
1493 /* ignore truncated writes, datagrams might get lost */
1494 c->local_consumed += dlen + 4;
1495 len = write(c->wfd, buf, dlen);
1497 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1500 if (c->type != SSH_CHANNEL_OPEN)
1503 chan_write_failed(c);
1509 /* XXX: Later AIX versions can't push as much data to tty */
1510 if (compat20 && c->wfd_isatty)
1511 dlen = MIN(dlen, 8*1024);
1514 len = write(c->wfd, buf, dlen);
1515 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1518 if (c->type != SSH_CHANNEL_OPEN) {
1519 debug2("channel %d: not open", c->self);
1522 } else if (compat13) {
1523 buffer_clear(&c->output);
1524 debug2("channel %d: input draining.", c->self);
1525 c->type = SSH_CHANNEL_INPUT_DRAINING;
1527 chan_write_failed(c);
1531 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1532 if (tcgetattr(c->wfd, &tio) == 0 &&
1533 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1535 * Simulate echo to reduce the impact of
1536 * traffic analysis. We need to match the
1537 * size of a SSH2_MSG_CHANNEL_DATA message
1538 * (4 byte channel id + buf)
1540 packet_send_ignore(4 + len);
1544 buffer_consume(&c->output, len);
1545 if (compat20 && len > 0) {
1546 c->local_consumed += len;
1553 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1555 char buf[CHAN_RBUF];
1558 /** XXX handle drain efd, too */
1560 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1561 FD_ISSET(c->efd, writeset) &&
1562 buffer_len(&c->extended) > 0) {
1563 len = write(c->efd, buffer_ptr(&c->extended),
1564 buffer_len(&c->extended));
1565 debug2("channel %d: written %d to efd %d",
1566 c->self, len, c->efd);
1567 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1570 debug2("channel %d: closing write-efd %d",
1572 channel_close_fd(&c->efd);
1574 buffer_consume(&c->extended, len);
1575 c->local_consumed += len;
1577 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1578 FD_ISSET(c->efd, readset)) {
1579 len = read(c->efd, buf, sizeof(buf));
1580 debug2("channel %d: read %d from efd %d",
1581 c->self, len, c->efd);
1582 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1585 debug2("channel %d: closing read-efd %d",
1587 channel_close_fd(&c->efd);
1589 buffer_append(&c->extended, buf, len);
1597 channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
1602 /* Monitor control fd to detect if the slave client exits */
1603 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1604 len = read(c->ctl_fd, buf, sizeof(buf));
1605 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1608 debug2("channel %d: ctl read<=0", c->self);
1609 if (c->type != SSH_CHANNEL_OPEN) {
1610 debug2("channel %d: not open", c->self);
1614 chan_read_failed(c);
1615 chan_write_failed(c);
1619 fatal("%s: unexpected data on ctl fd", __func__);
1625 channel_check_window(Channel *c)
1627 if (c->type == SSH_CHANNEL_OPEN &&
1628 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1629 c->local_window < c->local_window_max/2 &&
1630 c->local_consumed > 0) {
1631 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1632 packet_put_int(c->remote_id);
1633 packet_put_int(c->local_consumed);
1635 debug2("channel %d: window %d sent adjust %d",
1636 c->self, c->local_window,
1638 c->local_window += c->local_consumed;
1639 c->local_consumed = 0;
1645 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1649 channel_handle_rfd(c, readset, writeset);
1650 channel_handle_wfd(c, readset, writeset);
1653 channel_handle_efd(c, readset, writeset);
1654 channel_handle_ctl(c, readset, writeset);
1655 channel_check_window(c);
1659 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1663 /* Send buffered output data to the socket. */
1664 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1665 len = write(c->sock, buffer_ptr(&c->output),
1666 buffer_len(&c->output));
1668 buffer_clear(&c->output);
1670 buffer_consume(&c->output, len);
1675 channel_handler_init_20(void)
1677 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1678 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1679 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1680 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1681 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1682 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1683 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1684 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1686 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1687 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1688 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1689 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1690 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1691 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1692 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1696 channel_handler_init_13(void)
1698 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1699 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1700 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1701 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1702 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1703 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1704 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1705 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1706 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1708 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1709 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1710 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1711 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1712 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1713 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1714 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1718 channel_handler_init_15(void)
1720 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1721 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1722 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1723 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1724 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1725 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1726 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1728 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1729 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1730 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1731 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1732 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1733 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1737 channel_handler_init(void)
1741 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1742 channel_pre[i] = NULL;
1743 channel_post[i] = NULL;
1746 channel_handler_init_20();
1748 channel_handler_init_13();
1750 channel_handler_init_15();
1753 /* gc dead channels */
1755 channel_garbage_collect(Channel *c)
1759 if (c->detach_user != NULL) {
1760 if (!chan_is_dead(c, c->detach_close))
1762 debug2("channel %d: gc: notify user", c->self);
1763 c->detach_user(c->self, NULL);
1764 /* if we still have a callback */
1765 if (c->detach_user != NULL)
1767 debug2("channel %d: gc: user detached", c->self);
1769 if (!chan_is_dead(c, 1))
1771 debug2("channel %d: garbage collecting", c->self);
1776 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1778 static int did_init = 0;
1783 channel_handler_init();
1786 for (i = 0; i < channels_alloc; i++) {
1790 if (ftab[c->type] != NULL)
1791 (*ftab[c->type])(c, readset, writeset);
1792 channel_garbage_collect(c);
1797 * Allocate/update select bitmasks and add any bits relevant to channels in
1801 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1802 u_int *nallocp, int rekeying)
1804 u_int n, sz, nfdset;
1806 n = MAX(*maxfdp, channel_max_fd);
1808 nfdset = howmany(n+1, NFDBITS);
1809 /* Explicitly test here, because xrealloc isn't always called */
1810 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
1811 fatal("channel_prepare_select: max_fd (%d) is too large", n);
1812 sz = nfdset * sizeof(fd_mask);
1814 /* perhaps check sz < nalloc/2 and shrink? */
1815 if (*readsetp == NULL || sz > *nallocp) {
1816 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
1817 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1821 memset(*readsetp, 0, sz);
1822 memset(*writesetp, 0, sz);
1825 channel_handler(channel_pre, *readsetp, *writesetp);
1829 * After select, perform any appropriate operations for channels which have
1833 channel_after_select(fd_set *readset, fd_set *writeset)
1835 channel_handler(channel_post, readset, writeset);
1839 /* If there is data to send to the connection, enqueue some of it now. */
1841 channel_output_poll(void)
1846 for (i = 0; i < channels_alloc; i++) {
1852 * We are only interested in channels that can have buffered
1856 if (c->type != SSH_CHANNEL_OPEN &&
1857 c->type != SSH_CHANNEL_INPUT_DRAINING)
1860 if (c->type != SSH_CHANNEL_OPEN)
1864 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1865 /* XXX is this true? */
1866 debug3("channel %d: will not send data after close", c->self);
1870 /* Get the amount of buffered data for this channel. */
1871 if ((c->istate == CHAN_INPUT_OPEN ||
1872 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1873 (len = buffer_len(&c->input)) > 0) {
1879 data = buffer_get_string(&c->input,
1881 packet_start(SSH2_MSG_CHANNEL_DATA);
1882 packet_put_int(c->remote_id);
1883 packet_put_string(data, dlen);
1885 c->remote_window -= dlen + 4;
1891 * Send some data for the other side over the secure
1895 if (len > c->remote_window)
1896 len = c->remote_window;
1897 if (len > c->remote_maxpacket)
1898 len = c->remote_maxpacket;
1900 if (packet_is_interactive()) {
1904 /* Keep the packets at reasonable size. */
1905 if (len > packet_get_maxsize()/2)
1906 len = packet_get_maxsize()/2;
1910 packet_start(compat20 ?
1911 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1912 packet_put_int(c->remote_id);
1913 packet_put_string(buffer_ptr(&c->input), len);
1915 buffer_consume(&c->input, len);
1916 c->remote_window -= len;
1918 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1920 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1922 * input-buffer is empty and read-socket shutdown:
1923 * tell peer, that we will not send more data: send IEOF.
1924 * hack for extended data: delay EOF if EFD still in use.
1926 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1927 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1928 c->self, c->efd, buffer_len(&c->extended));
1932 /* Send extended data, i.e. stderr */
1934 !(c->flags & CHAN_EOF_SENT) &&
1935 c->remote_window > 0 &&
1936 (len = buffer_len(&c->extended)) > 0 &&
1937 c->extended_usage == CHAN_EXTENDED_READ) {
1938 debug2("channel %d: rwin %u elen %u euse %d",
1939 c->self, c->remote_window, buffer_len(&c->extended),
1941 if (len > c->remote_window)
1942 len = c->remote_window;
1943 if (len > c->remote_maxpacket)
1944 len = c->remote_maxpacket;
1945 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1946 packet_put_int(c->remote_id);
1947 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1948 packet_put_string(buffer_ptr(&c->extended), len);
1950 buffer_consume(&c->extended, len);
1951 c->remote_window -= len;
1952 debug2("channel %d: sent ext data %d", c->self, len);
1958 /* -- protocol input */
1962 channel_input_data(int type, u_int32_t seq, void *ctxt)
1969 /* Get the channel number and verify it. */
1970 id = packet_get_int();
1971 c = channel_lookup(id);
1973 packet_disconnect("Received data for nonexistent channel %d.", id);
1975 /* Ignore any data for non-open channels (might happen on close) */
1976 if (c->type != SSH_CHANNEL_OPEN &&
1977 c->type != SSH_CHANNEL_X11_OPEN)
1981 data = packet_get_string(&data_len);
1984 * Ignore data for protocol > 1.3 if output end is no longer open.
1985 * For protocol 2 the sending side is reducing its window as it sends
1986 * data, so we must 'fake' consumption of the data in order to ensure
1987 * that window updates are sent back. Otherwise the connection might
1990 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
1992 c->local_window -= data_len;
1993 c->local_consumed += data_len;
2000 if (data_len > c->local_maxpacket) {
2001 logit("channel %d: rcvd big packet %d, maxpack %d",
2002 c->self, data_len, c->local_maxpacket);
2004 if (data_len > c->local_window) {
2005 logit("channel %d: rcvd too much data %d, win %d",
2006 c->self, data_len, c->local_window);
2010 c->local_window -= data_len;
2014 buffer_put_string(&c->output, data, data_len);
2016 buffer_append(&c->output, data, data_len);
2022 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2026 u_int data_len, tcode;
2029 /* Get the channel number and verify it. */
2030 id = packet_get_int();
2031 c = channel_lookup(id);
2034 packet_disconnect("Received extended_data for bad channel %d.", id);
2035 if (c->type != SSH_CHANNEL_OPEN) {
2036 logit("channel %d: ext data for non open", id);
2039 if (c->flags & CHAN_EOF_RCVD) {
2040 if (datafellows & SSH_BUG_EXTEOF)
2041 debug("channel %d: accepting ext data after eof", id);
2043 packet_disconnect("Received extended_data after EOF "
2044 "on channel %d.", id);
2046 tcode = packet_get_int();
2048 c->extended_usage != CHAN_EXTENDED_WRITE ||
2049 tcode != SSH2_EXTENDED_DATA_STDERR) {
2050 logit("channel %d: bad ext data", c->self);
2053 data = packet_get_string(&data_len);
2055 if (data_len > c->local_window) {
2056 logit("channel %d: rcvd too much extended_data %d, win %d",
2057 c->self, data_len, c->local_window);
2061 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2062 c->local_window -= data_len;
2063 buffer_append(&c->extended, data, data_len);
2069 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2074 id = packet_get_int();
2076 c = channel_lookup(id);
2078 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2081 /* XXX force input close */
2082 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2083 debug("channel %d: FORCE input drain", c->self);
2084 c->istate = CHAN_INPUT_WAIT_DRAIN;
2085 if (buffer_len(&c->input) == 0)
2093 channel_input_close(int type, u_int32_t seq, void *ctxt)
2098 id = packet_get_int();
2100 c = channel_lookup(id);
2102 packet_disconnect("Received close for nonexistent channel %d.", id);
2105 * Send a confirmation that we have closed the channel and no more
2106 * data is coming for it.
2108 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2109 packet_put_int(c->remote_id);
2113 * If the channel is in closed state, we have sent a close request,
2114 * and the other side will eventually respond with a confirmation.
2115 * Thus, we cannot free the channel here, because then there would be
2116 * no-one to receive the confirmation. The channel gets freed when
2117 * the confirmation arrives.
2119 if (c->type != SSH_CHANNEL_CLOSED) {
2121 * Not a closed channel - mark it as draining, which will
2122 * cause it to be freed later.
2124 buffer_clear(&c->input);
2125 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2129 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2132 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2134 int id = packet_get_int();
2135 Channel *c = channel_lookup(id);
2139 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2140 chan_rcvd_oclose(c);
2145 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2147 int id = packet_get_int();
2148 Channel *c = channel_lookup(id);
2152 packet_disconnect("Received close confirmation for "
2153 "out-of-range channel %d.", id);
2154 if (c->type != SSH_CHANNEL_CLOSED)
2155 packet_disconnect("Received close confirmation for "
2156 "non-closed channel %d (type %d).", id, c->type);
2162 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2167 id = packet_get_int();
2168 c = channel_lookup(id);
2170 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2171 packet_disconnect("Received open confirmation for "
2172 "non-opening channel %d.", id);
2173 remote_id = packet_get_int();
2174 /* Record the remote channel number and mark that the channel is now open. */
2175 c->remote_id = remote_id;
2176 c->type = SSH_CHANNEL_OPEN;
2179 c->remote_window = packet_get_int();
2180 c->remote_maxpacket = packet_get_int();
2182 debug2("callback start");
2183 c->confirm(c->self, c->confirm_ctx);
2184 debug2("callback done");
2186 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2187 c->remote_window, c->remote_maxpacket);
2193 reason2txt(int reason)
2196 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2197 return "administratively prohibited";
2198 case SSH2_OPEN_CONNECT_FAILED:
2199 return "connect failed";
2200 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2201 return "unknown channel type";
2202 case SSH2_OPEN_RESOURCE_SHORTAGE:
2203 return "resource shortage";
2205 return "unknown reason";
2210 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2213 char *msg = NULL, *lang = NULL;
2216 id = packet_get_int();
2217 c = channel_lookup(id);
2219 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2220 packet_disconnect("Received open failure for "
2221 "non-opening channel %d.", id);
2223 reason = packet_get_int();
2224 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2225 msg = packet_get_string(NULL);
2226 lang = packet_get_string(NULL);
2228 logit("channel %d: open failed: %s%s%s", id,
2229 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2236 /* Free the channel. This will also close the socket. */
2242 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2251 /* Get the channel number and verify it. */
2252 id = packet_get_int();
2253 c = channel_lookup(id);
2256 logit("Received window adjust for non-open channel %d.", id);
2259 adjust = packet_get_int();
2261 debug2("channel %d: rcvd adjust %u", id, adjust);
2262 c->remote_window += adjust;
2267 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2271 char *host, *originator_string;
2272 int remote_id, sock = -1;
2274 remote_id = packet_get_int();
2275 host = packet_get_string(NULL);
2276 host_port = packet_get_int();
2278 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2279 originator_string = packet_get_string(NULL);
2281 originator_string = xstrdup("unknown (remote did not supply name)");
2284 sock = channel_connect_to(host, host_port);
2286 c = channel_new("connected socket",
2287 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2288 originator_string, 1);
2289 c->remote_id = remote_id;
2291 xfree(originator_string);
2293 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2294 packet_put_int(remote_id);
2301 /* -- tcp forwarding */
2304 channel_set_af(int af)
2310 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2311 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2314 int sock, r, success = 0, wildcard = 0, is_client;
2315 struct addrinfo hints, *ai, *aitop;
2316 const char *host, *addr;
2317 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2319 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2320 listen_addr : host_to_connect;
2321 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2324 error("No forward host name.");
2327 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2328 error("Forward host name too long.");
2333 * Determine whether or not a port forward listens to loopback,
2334 * specified address or wildcard. On the client, a specified bind
2335 * address will always override gateway_ports. On the server, a
2336 * gateway_ports of 1 (``yes'') will override the client's
2337 * specification and force a wildcard bind, whereas a value of 2
2338 * (``clientspecified'') will bind to whatever address the client
2341 * Special-case listen_addrs are:
2343 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2344 * "" (empty string), "*" -> wildcard v4/v6
2345 * "localhost" -> loopback v4/v6
2348 if (listen_addr == NULL) {
2349 /* No address specified: default to gateway_ports setting */
2352 } else if (gateway_ports || is_client) {
2353 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2354 strcmp(listen_addr, "0.0.0.0") == 0) ||
2355 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2356 (!is_client && gateway_ports == 1))
2358 else if (strcmp(listen_addr, "localhost") != 0)
2362 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2363 type, wildcard, (addr == NULL) ? "NULL" : addr);
2366 * getaddrinfo returns a loopback address if the hostname is
2367 * set to NULL and hints.ai_flags is not AI_PASSIVE
2369 memset(&hints, 0, sizeof(hints));
2370 hints.ai_family = IPv4or6;
2371 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2372 hints.ai_socktype = SOCK_STREAM;
2373 snprintf(strport, sizeof strport, "%d", listen_port);
2374 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2376 /* This really shouldn't happen */
2377 packet_disconnect("getaddrinfo: fatal error: %s",
2380 error("channel_setup_fwd_listener: "
2381 "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
2386 for (ai = aitop; ai; ai = ai->ai_next) {
2387 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2389 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2390 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2391 error("channel_setup_fwd_listener: getnameinfo failed");
2394 /* Create a port to listen for the host. */
2395 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2397 /* this is no error since kernel may not support ipv6 */
2398 verbose("socket: %.100s", strerror(errno));
2402 channel_set_reuseaddr(sock);
2404 debug("Local forwarding listening on %s port %s.", ntop, strport);
2406 /* Bind the socket to the address. */
2407 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2408 /* address can be in use ipv6 address is already bound */
2410 error("bind: %.100s", strerror(errno));
2412 verbose("bind: %.100s", strerror(errno));
2417 /* Start listening for connections on the socket. */
2418 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2419 error("listen: %.100s", strerror(errno));
2423 /* Allocate a channel number for the socket. */
2424 c = channel_new("port listener", type, sock, sock, -1,
2425 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2426 0, "port listener", 1);
2427 strlcpy(c->path, host, sizeof(c->path));
2428 c->host_port = port_to_connect;
2429 c->listening_port = listen_port;
2433 error("channel_setup_fwd_listener: cannot listen to port: %d",
2435 freeaddrinfo(aitop);
2440 channel_cancel_rport_listener(const char *host, u_short port)
2445 for (i = 0; i < channels_alloc; i++) {
2446 Channel *c = channels[i];
2448 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2449 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2450 c->listening_port == port) {
2451 debug2("%s: close channel %d", __func__, i);
2460 /* protocol local port fwd, used by ssh (and sshd in v1) */
2462 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2463 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2465 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2466 listen_host, listen_port, host_to_connect, port_to_connect,
2470 /* protocol v2 remote port fwd, used by sshd */
2472 channel_setup_remote_fwd_listener(const char *listen_address,
2473 u_short listen_port, int gateway_ports)
2475 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2476 listen_address, listen_port, NULL, 0, gateway_ports);
2480 * Initiate forwarding of connections to port "port" on remote host through
2481 * the secure channel to host:port from local side.
2485 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2486 const char *host_to_connect, u_short port_to_connect)
2488 int type, success = 0;
2490 /* Record locally that connection to this host/port is permitted. */
2491 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2492 fatal("channel_request_remote_forwarding: too many forwards");
2494 /* Send the forward request to the remote side. */
2496 const char *address_to_bind;
2497 if (listen_host == NULL)
2498 address_to_bind = "localhost";
2499 else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
2500 address_to_bind = "";
2502 address_to_bind = listen_host;
2504 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2505 packet_put_cstring("tcpip-forward");
2506 packet_put_char(1); /* boolean: want reply */
2507 packet_put_cstring(address_to_bind);
2508 packet_put_int(listen_port);
2510 packet_write_wait();
2511 /* Assume that server accepts the request */
2514 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2515 packet_put_int(listen_port);
2516 packet_put_cstring(host_to_connect);
2517 packet_put_int(port_to_connect);
2519 packet_write_wait();
2521 /* Wait for response from the remote side. */
2522 type = packet_read();
2524 case SSH_SMSG_SUCCESS:
2527 case SSH_SMSG_FAILURE:
2528 logit("Warning: Server denied remote port forwarding.");
2531 /* Unknown packet */
2532 packet_disconnect("Protocol error for port forward request:"
2533 "received packet type %d.", type);
2537 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2538 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2539 permitted_opens[num_permitted_opens].listen_port = listen_port;
2540 num_permitted_opens++;
2545 * Request cancellation of remote forwarding of connection host:port from
2549 channel_request_rforward_cancel(const char *host, u_short port)
2556 for (i = 0; i < num_permitted_opens; i++) {
2557 if (permitted_opens[i].host_to_connect != NULL &&
2558 permitted_opens[i].listen_port == port)
2561 if (i >= num_permitted_opens) {
2562 debug("%s: requested forward not found", __func__);
2565 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2566 packet_put_cstring("cancel-tcpip-forward");
2568 packet_put_cstring(host == NULL ? "" : host);
2569 packet_put_int(port);
2572 permitted_opens[i].listen_port = 0;
2573 permitted_opens[i].port_to_connect = 0;
2574 xfree(permitted_opens[i].host_to_connect);
2575 permitted_opens[i].host_to_connect = NULL;
2579 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2580 * listening for the port, and sends back a success reply (or disconnect
2581 * message if there was an error). This never returns if there was an error.
2584 channel_input_port_forward_request(int is_root, int gateway_ports)
2586 u_short port, host_port;
2589 /* Get arguments from the packet. */
2590 port = packet_get_int();
2591 hostname = packet_get_string(NULL);
2592 host_port = packet_get_int();
2596 * Check that an unprivileged user is not trying to forward a
2599 if (port < IPPORT_RESERVED && !is_root)
2601 "Requested forwarding of port %d but user is not root.",
2604 packet_disconnect("Dynamic forwarding denied.");
2607 /* Initiate forwarding */
2608 channel_setup_local_fwd_listener(NULL, port, hostname,
2609 host_port, gateway_ports);
2611 /* Free the argument string. */
2616 * Permits opening to any host/port if permitted_opens[] is empty. This is
2617 * usually called by the server, because the user could connect to any port
2618 * anyway, and the server has no way to know but to trust the client anyway.
2621 channel_permit_all_opens(void)
2623 if (num_permitted_opens == 0)
2624 all_opens_permitted = 1;
2628 channel_add_permitted_opens(char *host, int port)
2630 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2631 fatal("channel_request_remote_forwarding: too many forwards");
2632 debug("allow port forwarding to host %s port %d", host, port);
2634 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2635 permitted_opens[num_permitted_opens].port_to_connect = port;
2636 num_permitted_opens++;
2638 all_opens_permitted = 0;
2642 channel_clear_permitted_opens(void)
2646 for (i = 0; i < num_permitted_opens; i++)
2647 if (permitted_opens[i].host_to_connect != NULL)
2648 xfree(permitted_opens[i].host_to_connect);
2649 num_permitted_opens = 0;
2653 /* return socket to remote host, port */
2655 connect_to(const char *host, u_short port)
2657 struct addrinfo hints, *ai, *aitop;
2658 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2662 memset(&hints, 0, sizeof(hints));
2663 hints.ai_family = IPv4or6;
2664 hints.ai_socktype = SOCK_STREAM;
2665 snprintf(strport, sizeof strport, "%d", port);
2666 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2667 error("connect_to %.100s: unknown host (%s)", host,
2668 gai_strerror(gaierr));
2671 for (ai = aitop; ai; ai = ai->ai_next) {
2672 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2674 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2675 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2676 error("connect_to: getnameinfo failed");
2679 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2681 if (ai->ai_next == NULL)
2682 error("socket: %.100s", strerror(errno));
2684 verbose("socket: %.100s", strerror(errno));
2687 if (set_nonblock(sock) == -1)
2688 fatal("%s: set_nonblock(%d)", __func__, sock);
2689 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2690 errno != EINPROGRESS) {
2691 error("connect_to %.100s port %s: %.100s", ntop, strport,
2694 continue; /* fail -- try next */
2696 break; /* success */
2699 freeaddrinfo(aitop);
2701 error("connect_to %.100s port %d: failed.", host, port);
2710 channel_connect_by_listen_address(u_short listen_port)
2714 for (i = 0; i < num_permitted_opens; i++)
2715 if (permitted_opens[i].host_to_connect != NULL &&
2716 permitted_opens[i].listen_port == listen_port)
2718 permitted_opens[i].host_to_connect,
2719 permitted_opens[i].port_to_connect);
2720 error("WARNING: Server requests forwarding for unknown listen_port %d",
2725 /* Check if connecting to that port is permitted and connect. */
2727 channel_connect_to(const char *host, u_short port)
2731 permit = all_opens_permitted;
2733 for (i = 0; i < num_permitted_opens; i++)
2734 if (permitted_opens[i].host_to_connect != NULL &&
2735 permitted_opens[i].port_to_connect == port &&
2736 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2741 logit("Received request to connect to host %.100s port %d, "
2742 "but the request was denied.", host, port);
2745 return connect_to(host, port);
2749 channel_send_window_changes(void)
2754 for (i = 0; i < channels_alloc; i++) {
2755 if (channels[i] == NULL || !channels[i]->client_tty ||
2756 channels[i]->type != SSH_CHANNEL_OPEN)
2758 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2760 channel_request_start(i, "window-change", 0);
2761 packet_put_int((u_int)ws.ws_col);
2762 packet_put_int((u_int)ws.ws_row);
2763 packet_put_int((u_int)ws.ws_xpixel);
2764 packet_put_int((u_int)ws.ws_ypixel);
2769 /* -- X11 forwarding */
2772 * Creates an internet domain socket for listening for X11 connections.
2773 * Returns 0 and a suitable display number for the DISPLAY variable
2774 * stored in display_numberp , or -1 if an error occurs.
2777 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2778 int single_connection, u_int *display_numberp, int **chanids)
2781 int display_number, sock;
2783 struct addrinfo hints, *ai, *aitop;
2784 char strport[NI_MAXSERV];
2785 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2787 if (chanids == NULL)
2790 for (display_number = x11_display_offset;
2791 display_number < MAX_DISPLAYS;
2793 port = 6000 + display_number;
2794 memset(&hints, 0, sizeof(hints));
2795 hints.ai_family = IPv4or6;
2796 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2797 hints.ai_socktype = SOCK_STREAM;
2798 snprintf(strport, sizeof strport, "%d", port);
2799 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2800 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2803 for (ai = aitop; ai; ai = ai->ai_next) {
2804 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2806 sock = socket(ai->ai_family, ai->ai_socktype,
2809 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2810 error("socket: %.100s", strerror(errno));
2811 freeaddrinfo(aitop);
2814 debug("x11_create_display_inet: Socket family %d not supported",
2820 if (ai->ai_family == AF_INET6) {
2822 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2823 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2826 channel_set_reuseaddr(sock);
2827 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2828 debug2("bind port %d: %.100s", port, strerror(errno));
2834 for (n = 0; n < num_socks; n++) {
2840 socks[num_socks++] = sock;
2841 #ifndef DONT_TRY_OTHER_AF
2842 if (num_socks == NUM_SOCKS)
2845 if (x11_use_localhost) {
2846 if (num_socks == NUM_SOCKS)
2853 freeaddrinfo(aitop);
2857 if (display_number >= MAX_DISPLAYS) {
2858 error("Failed to allocate internet-domain X11 display socket.");
2861 /* Start listening for connections on the socket. */
2862 for (n = 0; n < num_socks; n++) {
2864 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2865 error("listen: %.100s", strerror(errno));
2871 /* Allocate a channel for each socket. */
2872 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
2873 for (n = 0; n < num_socks; n++) {
2875 nc = channel_new("x11 listener",
2876 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2877 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2878 0, "X11 inet listener", 1);
2879 nc->single_connection = single_connection;
2880 (*chanids)[n] = nc->self;
2884 /* Return the display number for the DISPLAY environment variable. */
2885 *display_numberp = display_number;
2890 connect_local_xsocket(u_int dnr)
2893 struct sockaddr_un addr;
2895 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2897 error("socket: %.100s", strerror(errno));
2898 memset(&addr, 0, sizeof(addr));
2899 addr.sun_family = AF_UNIX;
2900 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2901 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
2904 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2909 x11_connect_display(void)
2911 u_int display_number;
2912 const char *display;
2913 char buf[1024], *cp;
2914 struct addrinfo hints, *ai, *aitop;
2915 char strport[NI_MAXSERV];
2916 int gaierr, sock = 0;
2918 /* Try to open a socket for the local X server. */
2919 display = getenv("DISPLAY");
2921 error("DISPLAY not set.");
2925 * Now we decode the value of the DISPLAY variable and make a
2926 * connection to the real X server.
2930 * Check if it is a unix domain socket. Unix domain displays are in
2931 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2933 if (strncmp(display, "unix:", 5) == 0 ||
2934 display[0] == ':') {
2935 /* Connect to the unix domain socket. */
2936 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
2937 error("Could not parse display number from DISPLAY: %.100s",
2941 /* Create a socket. */
2942 sock = connect_local_xsocket(display_number);
2946 /* OK, we now have a connection to the display. */
2950 * Connect to an inet socket. The DISPLAY value is supposedly
2951 * hostname:d[.s], where hostname may also be numeric IP address.
2953 strlcpy(buf, display, sizeof(buf));
2954 cp = strchr(buf, ':');
2956 error("Could not find ':' in DISPLAY: %.100s", display);
2960 /* buf now contains the host name. But first we parse the display number. */
2961 if (sscanf(cp + 1, "%u", &display_number) != 1) {
2962 error("Could not parse display number from DISPLAY: %.100s",
2967 /* Look up the host address */
2968 memset(&hints, 0, sizeof(hints));
2969 hints.ai_family = IPv4or6;
2970 hints.ai_socktype = SOCK_STREAM;
2971 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
2972 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
2973 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
2976 for (ai = aitop; ai; ai = ai->ai_next) {
2977 /* Create a socket. */
2978 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2980 debug2("socket: %.100s", strerror(errno));
2983 /* Connect it to the display. */
2984 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2985 debug2("connect %.100s port %u: %.100s", buf,
2986 6000 + display_number, strerror(errno));
2993 freeaddrinfo(aitop);
2995 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3004 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3005 * the remote channel number. We should do whatever we want, and respond
3006 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3010 x11_input_open(int type, u_int32_t seq, void *ctxt)
3013 int remote_id, sock = 0;
3016 debug("Received X11 open request.");
3018 remote_id = packet_get_int();
3020 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3021 remote_host = packet_get_string(NULL);
3023 remote_host = xstrdup("unknown (remote did not supply name)");
3027 /* Obtain a connection to the real X display. */
3028 sock = x11_connect_display();
3030 /* Allocate a channel for this connection. */
3031 c = channel_new("connected x11 socket",
3032 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3034 c->remote_id = remote_id;
3039 /* Send refusal to the remote host. */
3040 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3041 packet_put_int(remote_id);
3043 /* Send a confirmation to the remote host. */
3044 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3045 packet_put_int(remote_id);
3046 packet_put_int(c->self);
3051 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3053 deny_input_open(int type, u_int32_t seq, void *ctxt)
3055 int rchan = packet_get_int();
3058 case SSH_SMSG_AGENT_OPEN:
3059 error("Warning: ssh server tried agent forwarding.");
3061 case SSH_SMSG_X11_OPEN:
3062 error("Warning: ssh server tried X11 forwarding.");
3065 error("deny_input_open: type %d", type);
3068 error("Warning: this is probably a break-in attempt by a malicious server.");
3069 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3070 packet_put_int(rchan);
3075 * Requests forwarding of X11 connections, generates fake authentication
3076 * data, and enables authentication spoofing.
3077 * This should be called in the client only.
3080 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3081 const char *proto, const char *data)
3083 u_int data_len = (u_int) strlen(data) / 2;
3090 if (x11_saved_display == NULL)
3091 x11_saved_display = xstrdup(disp);
3092 else if (strcmp(disp, x11_saved_display) != 0) {
3093 error("x11_request_forwarding_with_spoofing: different "
3094 "$DISPLAY already forwarded");
3100 cp = strchr(disp, ':');
3102 cp = strchr(cp, '.');
3104 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3108 if (x11_saved_proto == NULL) {
3109 /* Save protocol name. */
3110 x11_saved_proto = xstrdup(proto);
3112 * Extract real authentication data and generate fake data
3113 * of the same length.
3115 x11_saved_data = xmalloc(data_len);
3116 x11_fake_data = xmalloc(data_len);
3117 for (i = 0; i < data_len; i++) {
3118 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3119 fatal("x11_request_forwarding: bad "
3120 "authentication data: %.100s", data);
3123 x11_saved_data[i] = value;
3124 x11_fake_data[i] = rnd & 0xff;
3127 x11_saved_data_len = data_len;
3128 x11_fake_data_len = data_len;
3131 /* Convert the fake data into hex. */
3132 new_data = tohex(x11_fake_data, data_len);
3134 /* Send the request packet. */
3136 channel_request_start(client_session_id, "x11-req", 0);
3137 packet_put_char(0); /* XXX bool single connection */
3139 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3141 packet_put_cstring(proto);
3142 packet_put_cstring(new_data);
3143 packet_put_int(screen_number);
3145 packet_write_wait();
3150 /* -- agent forwarding */
3152 /* Sends a message to the server to request authentication fd forwarding. */
3155 auth_request_forwarding(void)
3157 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3159 packet_write_wait();