1 /* $OpenBSD: channels.c,v 1.263 2006/08/01 23:22:47 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>
75 #include "pathnames.h"
81 * Pointer to an array containing all allocated channels. The array is
82 * dynamically extended as needed.
84 static Channel **channels = NULL;
87 * Size of the channel array. All slots of the array must always be
88 * initialized (at least the type field); unused slots set to NULL
90 static u_int channels_alloc = 0;
93 * Maximum file descriptor value used in any of the channels. This is
94 * updated in channel_new.
96 static int channel_max_fd = 0;
99 /* -- tcp forwarding */
102 * Data structure for storing which hosts are permitted for forward requests.
103 * The local sides of any remote forwards are stored in this array to prevent
104 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
105 * network (which might be behind a firewall).
108 char *host_to_connect; /* Connect to 'host'. */
109 u_short port_to_connect; /* Connect to 'port'. */
110 u_short listen_port; /* Remote side should listen port number. */
113 /* List of all permitted host/port pairs to connect by the user. */
114 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
116 /* List of all permitted host/port pairs to connect by the admin. */
117 static ForwardPermission permitted_adm_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
119 /* Number of permitted host/port pairs in the array permitted by the user. */
120 static int num_permitted_opens = 0;
122 /* Number of permitted host/port pair in the array permitted by the admin. */
123 static int num_adm_permitted_opens = 0;
126 * If this is true, all opens are permitted. This is the case on the server
127 * on which we have to trust the client anyway, and the user could do
128 * anything after logging in anyway.
130 static int all_opens_permitted = 0;
133 /* -- X11 forwarding */
135 /* Maximum number of fake X11 displays to try. */
136 #define MAX_DISPLAYS 1000
138 /* Saved X11 local (client) display. */
139 static char *x11_saved_display = NULL;
141 /* Saved X11 authentication protocol name. */
142 static char *x11_saved_proto = NULL;
144 /* Saved X11 authentication data. This is the real data. */
145 static char *x11_saved_data = NULL;
146 static u_int x11_saved_data_len = 0;
149 * Fake X11 authentication data. This is what the server will be sending us;
150 * we should replace any occurrences of this by the real data.
152 static u_char *x11_fake_data = NULL;
153 static u_int x11_fake_data_len;
156 /* -- agent forwarding */
160 /* AF_UNSPEC or AF_INET or AF_INET6 */
161 static int IPv4or6 = AF_UNSPEC;
164 static void port_open_helper(Channel *c, char *rtype);
166 /* -- channel core */
169 channel_by_id(int id)
173 if (id < 0 || (u_int)id >= channels_alloc) {
174 logit("channel_by_id: %d: bad id", id);
179 logit("channel_by_id: %d: bad id: channel free", id);
186 * Returns the channel if it is allowed to receive protocol messages.
187 * Private channels, like listening sockets, may not receive messages.
190 channel_lookup(int id)
194 if ((c = channel_by_id(id)) == NULL)
198 case SSH_CHANNEL_X11_OPEN:
199 case SSH_CHANNEL_LARVAL:
200 case SSH_CHANNEL_CONNECTING:
201 case SSH_CHANNEL_DYNAMIC:
202 case SSH_CHANNEL_OPENING:
203 case SSH_CHANNEL_OPEN:
204 case SSH_CHANNEL_INPUT_DRAINING:
205 case SSH_CHANNEL_OUTPUT_DRAINING:
208 logit("Non-public channel %d, type %d.", id, c->type);
213 * Register filedescriptors for a channel, used when allocating a channel or
214 * when the channel consumer/producer is ready, e.g. shell exec'd
217 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
218 int extusage, int nonblock)
220 /* Update the maximum file descriptor value. */
221 channel_max_fd = MAX(channel_max_fd, rfd);
222 channel_max_fd = MAX(channel_max_fd, wfd);
223 channel_max_fd = MAX(channel_max_fd, efd);
225 /* XXX set close-on-exec -markus */
229 c->sock = (rfd == wfd) ? rfd : -1;
230 c->ctl_fd = -1; /* XXX: set elsewhere */
232 c->extended_usage = extusage;
234 /* XXX ugly hack: nonblock is only set by the server */
235 if (nonblock && isatty(c->rfd)) {
236 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
238 if (!isatty(c->wfd)) {
239 error("channel %d: wfd %d is not a tty?",
245 c->wfd_isatty = isatty(c->wfd);
247 /* enable nonblocking mode */
259 * Allocate a new channel object and set its type and socket. This will cause
260 * remote_name to be freed.
263 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
264 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
270 /* Do initial allocation if this is the first call. */
271 if (channels_alloc == 0) {
273 channels = xcalloc(channels_alloc, sizeof(Channel *));
274 for (i = 0; i < channels_alloc; i++)
277 /* Try to find a free slot where to put the new channel. */
278 for (found = -1, i = 0; i < channels_alloc; i++)
279 if (channels[i] == NULL) {
280 /* Found a free slot. */
285 /* There are no free slots. Take last+1 slot and expand the array. */
286 found = channels_alloc;
287 if (channels_alloc > 10000)
288 fatal("channel_new: internal error: channels_alloc %d "
289 "too big.", channels_alloc);
290 channels = xrealloc(channels, channels_alloc + 10,
292 channels_alloc += 10;
293 debug2("channel: expanding %d", channels_alloc);
294 for (i = found; i < channels_alloc; i++)
297 /* Initialize and return new channel. */
298 c = channels[found] = xcalloc(1, sizeof(Channel));
299 buffer_init(&c->input);
300 buffer_init(&c->output);
301 buffer_init(&c->extended);
302 c->ostate = CHAN_OUTPUT_OPEN;
303 c->istate = CHAN_INPUT_OPEN;
305 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
309 c->local_window = window;
310 c->local_window_max = window;
311 c->local_consumed = 0;
312 c->local_maxpacket = maxpack;
314 c->remote_name = xstrdup(remote_name);
315 c->remote_window = 0;
316 c->remote_maxpacket = 0;
318 c->single_connection = 0;
319 c->detach_user = NULL;
322 c->confirm_ctx = NULL;
323 c->input_filter = NULL;
324 c->output_filter = NULL;
325 debug("channel %d: new [%s]", found, remote_name);
330 channel_find_maxfd(void)
336 for (i = 0; i < channels_alloc; i++) {
339 max = MAX(max, c->rfd);
340 max = MAX(max, c->wfd);
341 max = MAX(max, c->efd);
348 channel_close_fd(int *fdp)
350 int ret = 0, fd = *fdp;
355 if (fd == channel_max_fd)
356 channel_max_fd = channel_find_maxfd();
361 /* Close all channel fd/socket. */
363 channel_close_fds(Channel *c)
365 debug3("channel %d: close_fds r %d w %d e %d c %d",
366 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
368 channel_close_fd(&c->sock);
369 channel_close_fd(&c->ctl_fd);
370 channel_close_fd(&c->rfd);
371 channel_close_fd(&c->wfd);
372 channel_close_fd(&c->efd);
375 /* Free the channel and close its fd/socket. */
377 channel_free(Channel *c)
382 for (n = 0, i = 0; i < channels_alloc; i++)
385 debug("channel %d: free: %s, nchannels %u", c->self,
386 c->remote_name ? c->remote_name : "???", n);
388 s = channel_open_message();
389 debug3("channel %d: status: %s", c->self, s);
393 shutdown(c->sock, SHUT_RDWR);
395 shutdown(c->ctl_fd, SHUT_RDWR);
396 channel_close_fds(c);
397 buffer_free(&c->input);
398 buffer_free(&c->output);
399 buffer_free(&c->extended);
400 if (c->remote_name) {
401 xfree(c->remote_name);
402 c->remote_name = NULL;
404 channels[c->self] = NULL;
409 channel_free_all(void)
413 for (i = 0; i < channels_alloc; i++)
414 if (channels[i] != NULL)
415 channel_free(channels[i]);
419 * Closes the sockets/fds of all channels. This is used to close extra file
420 * descriptors after a fork.
423 channel_close_all(void)
427 for (i = 0; i < channels_alloc; i++)
428 if (channels[i] != NULL)
429 channel_close_fds(channels[i]);
433 * Stop listening to channels.
436 channel_stop_listening(void)
441 for (i = 0; i < channels_alloc; i++) {
445 case SSH_CHANNEL_AUTH_SOCKET:
446 case SSH_CHANNEL_PORT_LISTENER:
447 case SSH_CHANNEL_RPORT_LISTENER:
448 case SSH_CHANNEL_X11_LISTENER:
449 channel_close_fd(&c->sock);
458 * Returns true if no channel has too much buffered data, and false if one or
459 * more channel is overfull.
462 channel_not_very_much_buffered_data(void)
467 for (i = 0; i < channels_alloc; i++) {
469 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
472 buffer_len(&c->input) > packet_get_maxsize()) {
473 debug2("channel %d: big input buffer %d",
474 c->self, buffer_len(&c->input));
478 if (buffer_len(&c->output) > packet_get_maxsize()) {
479 debug2("channel %d: big output buffer %u > %u",
480 c->self, buffer_len(&c->output),
481 packet_get_maxsize());
489 /* Returns true if any channel is still open. */
491 channel_still_open(void)
496 for (i = 0; i < channels_alloc; i++) {
501 case SSH_CHANNEL_X11_LISTENER:
502 case SSH_CHANNEL_PORT_LISTENER:
503 case SSH_CHANNEL_RPORT_LISTENER:
504 case SSH_CHANNEL_CLOSED:
505 case SSH_CHANNEL_AUTH_SOCKET:
506 case SSH_CHANNEL_DYNAMIC:
507 case SSH_CHANNEL_CONNECTING:
508 case SSH_CHANNEL_ZOMBIE:
510 case SSH_CHANNEL_LARVAL:
512 fatal("cannot happen: SSH_CHANNEL_LARVAL");
514 case SSH_CHANNEL_OPENING:
515 case SSH_CHANNEL_OPEN:
516 case SSH_CHANNEL_X11_OPEN:
518 case SSH_CHANNEL_INPUT_DRAINING:
519 case SSH_CHANNEL_OUTPUT_DRAINING:
521 fatal("cannot happen: OUT_DRAIN");
524 fatal("channel_still_open: bad channel type %d", c->type);
531 /* Returns the id of an open channel suitable for keepaliving */
533 channel_find_open(void)
538 for (i = 0; i < channels_alloc; i++) {
540 if (c == NULL || c->remote_id < 0)
543 case SSH_CHANNEL_CLOSED:
544 case SSH_CHANNEL_DYNAMIC:
545 case SSH_CHANNEL_X11_LISTENER:
546 case SSH_CHANNEL_PORT_LISTENER:
547 case SSH_CHANNEL_RPORT_LISTENER:
548 case SSH_CHANNEL_OPENING:
549 case SSH_CHANNEL_CONNECTING:
550 case SSH_CHANNEL_ZOMBIE:
552 case SSH_CHANNEL_LARVAL:
553 case SSH_CHANNEL_AUTH_SOCKET:
554 case SSH_CHANNEL_OPEN:
555 case SSH_CHANNEL_X11_OPEN:
557 case SSH_CHANNEL_INPUT_DRAINING:
558 case SSH_CHANNEL_OUTPUT_DRAINING:
560 fatal("cannot happen: OUT_DRAIN");
563 fatal("channel_find_open: bad channel type %d", c->type);
572 * Returns a message describing the currently open forwarded connections,
573 * suitable for sending to the client. The message contains crlf pairs for
577 channel_open_message(void)
584 buffer_init(&buffer);
585 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
586 buffer_append(&buffer, buf, strlen(buf));
587 for (i = 0; i < channels_alloc; i++) {
592 case SSH_CHANNEL_X11_LISTENER:
593 case SSH_CHANNEL_PORT_LISTENER:
594 case SSH_CHANNEL_RPORT_LISTENER:
595 case SSH_CHANNEL_CLOSED:
596 case SSH_CHANNEL_AUTH_SOCKET:
597 case SSH_CHANNEL_ZOMBIE:
599 case SSH_CHANNEL_LARVAL:
600 case SSH_CHANNEL_OPENING:
601 case SSH_CHANNEL_CONNECTING:
602 case SSH_CHANNEL_DYNAMIC:
603 case SSH_CHANNEL_OPEN:
604 case SSH_CHANNEL_X11_OPEN:
605 case SSH_CHANNEL_INPUT_DRAINING:
606 case SSH_CHANNEL_OUTPUT_DRAINING:
607 snprintf(buf, sizeof buf,
608 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
609 c->self, c->remote_name,
610 c->type, c->remote_id,
611 c->istate, buffer_len(&c->input),
612 c->ostate, buffer_len(&c->output),
613 c->rfd, c->wfd, c->ctl_fd);
614 buffer_append(&buffer, buf, strlen(buf));
617 fatal("channel_open_message: bad channel type %d", c->type);
621 buffer_append(&buffer, "\0", 1);
622 cp = xstrdup(buffer_ptr(&buffer));
623 buffer_free(&buffer);
628 channel_send_open(int id)
630 Channel *c = channel_lookup(id);
633 logit("channel_send_open: %d: bad id", id);
636 debug2("channel %d: send open", id);
637 packet_start(SSH2_MSG_CHANNEL_OPEN);
638 packet_put_cstring(c->ctype);
639 packet_put_int(c->self);
640 packet_put_int(c->local_window);
641 packet_put_int(c->local_maxpacket);
646 channel_request_start(int id, char *service, int wantconfirm)
648 Channel *c = channel_lookup(id);
651 logit("channel_request_start: %d: unknown channel id", id);
654 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
655 packet_start(SSH2_MSG_CHANNEL_REQUEST);
656 packet_put_int(c->remote_id);
657 packet_put_cstring(service);
658 packet_put_char(wantconfirm);
662 channel_register_confirm(int id, channel_callback_fn *fn, void *ctx)
664 Channel *c = channel_lookup(id);
667 logit("channel_register_comfirm: %d: bad id", id);
671 c->confirm_ctx = ctx;
675 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
677 Channel *c = channel_by_id(id);
680 logit("channel_register_cleanup: %d: bad id", id);
684 c->detach_close = do_close;
688 channel_cancel_cleanup(int id)
690 Channel *c = channel_by_id(id);
693 logit("channel_cancel_cleanup: %d: bad id", id);
696 c->detach_user = NULL;
701 channel_register_filter(int id, channel_infilter_fn *ifn,
702 channel_outfilter_fn *ofn)
704 Channel *c = channel_lookup(id);
707 logit("channel_register_filter: %d: bad id", id);
710 c->input_filter = ifn;
711 c->output_filter = ofn;
715 channel_set_fds(int id, int rfd, int wfd, int efd,
716 int extusage, int nonblock, u_int window_max)
718 Channel *c = channel_lookup(id);
720 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
721 fatal("channel_activate for non-larval channel %d.", id);
722 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
723 c->type = SSH_CHANNEL_OPEN;
724 c->local_window = c->local_window_max = window_max;
725 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
726 packet_put_int(c->remote_id);
727 packet_put_int(c->local_window);
732 * 'channel_pre*' are called just before select() to add any bits relevant to
733 * channels in the select bitmasks.
736 * 'channel_post*': perform any appropriate operations for channels which
737 * have events pending.
739 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
740 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
741 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
745 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
747 FD_SET(c->sock, readset);
752 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
754 debug3("channel %d: waiting for connection", c->self);
755 FD_SET(c->sock, writeset);
759 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
761 if (buffer_len(&c->input) < packet_get_maxsize())
762 FD_SET(c->sock, readset);
763 if (buffer_len(&c->output) > 0)
764 FD_SET(c->sock, writeset);
768 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
770 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
772 if (c->istate == CHAN_INPUT_OPEN &&
774 buffer_len(&c->input) < limit &&
775 buffer_check_alloc(&c->input, CHAN_RBUF))
776 FD_SET(c->rfd, readset);
777 if (c->ostate == CHAN_OUTPUT_OPEN ||
778 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
779 if (buffer_len(&c->output) > 0) {
780 FD_SET(c->wfd, writeset);
781 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
782 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
783 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
784 c->self, c->efd, buffer_len(&c->extended));
789 /** XXX check close conditions, too */
790 if (compat20 && c->efd != -1) {
791 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
792 buffer_len(&c->extended) > 0)
793 FD_SET(c->efd, writeset);
794 else if (!(c->flags & CHAN_EOF_SENT) &&
795 c->extended_usage == CHAN_EXTENDED_READ &&
796 buffer_len(&c->extended) < c->remote_window)
797 FD_SET(c->efd, readset);
799 /* XXX: What about efd? races? */
800 if (compat20 && c->ctl_fd != -1 &&
801 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
802 FD_SET(c->ctl_fd, readset);
807 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
809 if (buffer_len(&c->input) == 0) {
810 packet_start(SSH_MSG_CHANNEL_CLOSE);
811 packet_put_int(c->remote_id);
813 c->type = SSH_CHANNEL_CLOSED;
814 debug2("channel %d: closing after input drain.", c->self);
820 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
822 if (buffer_len(&c->output) == 0)
825 FD_SET(c->sock, writeset);
829 * This is a special state for X11 authentication spoofing. An opened X11
830 * connection (when authentication spoofing is being done) remains in this
831 * state until the first packet has been completely read. The authentication
832 * data in that packet is then substituted by the real data if it matches the
833 * fake data, and the channel is put into normal mode.
834 * XXX All this happens at the client side.
835 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
838 x11_open_helper(Buffer *b)
841 u_int proto_len, data_len;
843 /* Check if the fixed size part of the packet is in buffer. */
844 if (buffer_len(b) < 12)
847 /* Parse the lengths of variable-length fields. */
849 if (ucp[0] == 0x42) { /* Byte order MSB first. */
850 proto_len = 256 * ucp[6] + ucp[7];
851 data_len = 256 * ucp[8] + ucp[9];
852 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
853 proto_len = ucp[6] + 256 * ucp[7];
854 data_len = ucp[8] + 256 * ucp[9];
856 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
861 /* Check if the whole packet is in buffer. */
863 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
866 /* Check if authentication protocol matches. */
867 if (proto_len != strlen(x11_saved_proto) ||
868 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
869 debug2("X11 connection uses different authentication protocol.");
872 /* Check if authentication data matches our fake data. */
873 if (data_len != x11_fake_data_len ||
874 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
875 x11_fake_data, x11_fake_data_len) != 0) {
876 debug2("X11 auth data does not match fake data.");
879 /* Check fake data length */
880 if (x11_fake_data_len != x11_saved_data_len) {
881 error("X11 fake_data_len %d != saved_data_len %d",
882 x11_fake_data_len, x11_saved_data_len);
886 * Received authentication protocol and data match
887 * our fake data. Substitute the fake data with real
890 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
891 x11_saved_data, x11_saved_data_len);
896 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
898 int ret = x11_open_helper(&c->output);
901 /* Start normal processing for the channel. */
902 c->type = SSH_CHANNEL_OPEN;
903 channel_pre_open_13(c, readset, writeset);
904 } else if (ret == -1) {
906 * We have received an X11 connection that has bad
907 * authentication information.
909 logit("X11 connection rejected because of wrong authentication.");
910 buffer_clear(&c->input);
911 buffer_clear(&c->output);
912 channel_close_fd(&c->sock);
914 c->type = SSH_CHANNEL_CLOSED;
915 packet_start(SSH_MSG_CHANNEL_CLOSE);
916 packet_put_int(c->remote_id);
922 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
924 int ret = x11_open_helper(&c->output);
926 /* c->force_drain = 1; */
929 c->type = SSH_CHANNEL_OPEN;
930 channel_pre_open(c, readset, writeset);
931 } else if (ret == -1) {
932 logit("X11 connection rejected because of wrong authentication.");
933 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
935 buffer_clear(&c->input);
937 buffer_clear(&c->output);
938 /* for proto v1, the peer will send an IEOF */
940 chan_write_failed(c);
942 c->type = SSH_CHANNEL_OPEN;
943 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
947 /* try to decode a socks4 header */
950 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
953 u_int len, have, i, found;
959 struct in_addr dest_addr;
962 debug2("channel %d: decode socks4", c->self);
964 have = buffer_len(&c->input);
965 len = sizeof(s4_req);
968 p = buffer_ptr(&c->input);
969 for (found = 0, i = len; i < have; i++) {
975 /* the peer is probably sending garbage */
976 debug("channel %d: decode socks4: too long",
983 buffer_get(&c->input, (char *)&s4_req.version, 1);
984 buffer_get(&c->input, (char *)&s4_req.command, 1);
985 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
986 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
987 have = buffer_len(&c->input);
988 p = buffer_ptr(&c->input);
990 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
992 fatal("channel %d: decode socks4: len %d > have %d",
994 strlcpy(username, p, sizeof(username));
995 buffer_consume(&c->input, len);
996 buffer_consume(&c->input, 1); /* trailing '\0' */
998 host = inet_ntoa(s4_req.dest_addr);
999 strlcpy(c->path, host, sizeof(c->path));
1000 c->host_port = ntohs(s4_req.dest_port);
1002 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1003 c->self, host, c->host_port, s4_req.command);
1005 if (s4_req.command != 1) {
1006 debug("channel %d: cannot handle: socks4 cn %d",
1007 c->self, s4_req.command);
1010 s4_rsp.version = 0; /* vn: 0 for reply */
1011 s4_rsp.command = 90; /* cd: req granted */
1012 s4_rsp.dest_port = 0; /* ignored */
1013 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1014 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1018 /* try to decode a socks5 header */
1019 #define SSH_SOCKS5_AUTHDONE 0x1000
1020 #define SSH_SOCKS5_NOAUTH 0x00
1021 #define SSH_SOCKS5_IPV4 0x01
1022 #define SSH_SOCKS5_DOMAIN 0x03
1023 #define SSH_SOCKS5_IPV6 0x04
1024 #define SSH_SOCKS5_CONNECT 0x01
1025 #define SSH_SOCKS5_SUCCESS 0x00
1029 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1037 u_int16_t dest_port;
1038 u_char *p, dest_addr[255+1];
1039 u_int have, need, i, found, nmethods, addrlen, af;
1041 debug2("channel %d: decode socks5", c->self);
1042 p = buffer_ptr(&c->input);
1045 have = buffer_len(&c->input);
1046 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1047 /* format: ver | nmethods | methods */
1051 if (have < nmethods + 2)
1053 /* look for method: "NO AUTHENTICATION REQUIRED" */
1054 for (found = 0, i = 2 ; i < nmethods + 2; i++) {
1055 if (p[i] == SSH_SOCKS5_NOAUTH ) {
1061 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1065 buffer_consume(&c->input, nmethods + 2);
1066 buffer_put_char(&c->output, 0x05); /* version */
1067 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1068 FD_SET(c->sock, writeset);
1069 c->flags |= SSH_SOCKS5_AUTHDONE;
1070 debug2("channel %d: socks5 auth done", c->self);
1071 return 0; /* need more */
1073 debug2("channel %d: socks5 post auth", c->self);
1074 if (have < sizeof(s5_req)+1)
1075 return 0; /* need more */
1076 memcpy(&s5_req, p, sizeof(s5_req));
1077 if (s5_req.version != 0x05 ||
1078 s5_req.command != SSH_SOCKS5_CONNECT ||
1079 s5_req.reserved != 0x00) {
1080 debug2("channel %d: only socks5 connect supported", c->self);
1083 switch (s5_req.atyp){
1084 case SSH_SOCKS5_IPV4:
1088 case SSH_SOCKS5_DOMAIN:
1089 addrlen = p[sizeof(s5_req)];
1092 case SSH_SOCKS5_IPV6:
1097 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1100 need = sizeof(s5_req) + addrlen + 2;
1101 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1105 buffer_consume(&c->input, sizeof(s5_req));
1106 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1107 buffer_consume(&c->input, 1); /* host string length */
1108 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1109 buffer_get(&c->input, (char *)&dest_port, 2);
1110 dest_addr[addrlen] = '\0';
1111 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1112 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1113 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1115 c->host_port = ntohs(dest_port);
1117 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1118 c->self, c->path, c->host_port, s5_req.command);
1120 s5_rsp.version = 0x05;
1121 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1122 s5_rsp.reserved = 0; /* ignored */
1123 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1124 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1125 dest_port = 0; /* ignored */
1127 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1128 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1129 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1133 /* dynamic port forwarding */
1135 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1141 have = buffer_len(&c->input);
1143 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1144 /* buffer_dump(&c->input); */
1145 /* check if the fixed size part of the packet is in buffer. */
1148 FD_SET(c->sock, readset);
1151 /* try to guess the protocol */
1152 p = buffer_ptr(&c->input);
1155 ret = channel_decode_socks4(c, readset, writeset);
1158 ret = channel_decode_socks5(c, readset, writeset);
1166 } else if (ret == 0) {
1167 debug2("channel %d: pre_dynamic: need more", c->self);
1169 FD_SET(c->sock, readset);
1171 /* switch to the next state */
1172 c->type = SSH_CHANNEL_OPENING;
1173 port_open_helper(c, "direct-tcpip");
1177 /* This is our fake X11 server socket. */
1180 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1183 struct sockaddr addr;
1186 char buf[16384], *remote_ipaddr;
1189 if (FD_ISSET(c->sock, readset)) {
1190 debug("X11 connection requested.");
1191 addrlen = sizeof(addr);
1192 newsock = accept(c->sock, &addr, &addrlen);
1193 if (c->single_connection) {
1194 debug2("single_connection: closing X11 listener.");
1195 channel_close_fd(&c->sock);
1199 error("accept: %.100s", strerror(errno));
1202 set_nodelay(newsock);
1203 remote_ipaddr = get_peer_ipaddr(newsock);
1204 remote_port = get_peer_port(newsock);
1205 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1206 remote_ipaddr, remote_port);
1208 nc = channel_new("accepted x11 socket",
1209 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1210 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1212 packet_start(SSH2_MSG_CHANNEL_OPEN);
1213 packet_put_cstring("x11");
1214 packet_put_int(nc->self);
1215 packet_put_int(nc->local_window_max);
1216 packet_put_int(nc->local_maxpacket);
1217 /* originator ipaddr and port */
1218 packet_put_cstring(remote_ipaddr);
1219 if (datafellows & SSH_BUG_X11FWD) {
1220 debug2("ssh2 x11 bug compat mode");
1222 packet_put_int(remote_port);
1226 packet_start(SSH_SMSG_X11_OPEN);
1227 packet_put_int(nc->self);
1228 if (packet_get_protocol_flags() &
1229 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1230 packet_put_cstring(buf);
1233 xfree(remote_ipaddr);
1238 port_open_helper(Channel *c, char *rtype)
1242 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1243 int remote_port = get_peer_port(c->sock);
1245 direct = (strcmp(rtype, "direct-tcpip") == 0);
1247 snprintf(buf, sizeof buf,
1248 "%s: listening port %d for %.100s port %d, "
1249 "connect from %.200s port %d",
1250 rtype, c->listening_port, c->path, c->host_port,
1251 remote_ipaddr, remote_port);
1253 xfree(c->remote_name);
1254 c->remote_name = xstrdup(buf);
1257 packet_start(SSH2_MSG_CHANNEL_OPEN);
1258 packet_put_cstring(rtype);
1259 packet_put_int(c->self);
1260 packet_put_int(c->local_window_max);
1261 packet_put_int(c->local_maxpacket);
1263 /* target host, port */
1264 packet_put_cstring(c->path);
1265 packet_put_int(c->host_port);
1267 /* listen address, port */
1268 packet_put_cstring(c->path);
1269 packet_put_int(c->listening_port);
1271 /* originator host and port */
1272 packet_put_cstring(remote_ipaddr);
1273 packet_put_int((u_int)remote_port);
1276 packet_start(SSH_MSG_PORT_OPEN);
1277 packet_put_int(c->self);
1278 packet_put_cstring(c->path);
1279 packet_put_int(c->host_port);
1280 if (packet_get_protocol_flags() &
1281 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1282 packet_put_cstring(c->remote_name);
1285 xfree(remote_ipaddr);
1289 channel_set_reuseaddr(int fd)
1294 * Set socket options.
1295 * Allow local port reuse in TIME_WAIT.
1297 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1298 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1302 * This socket is listening for connections to a forwarded TCP/IP port.
1306 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1309 struct sockaddr addr;
1310 int newsock, nextstate;
1314 if (FD_ISSET(c->sock, readset)) {
1315 debug("Connection to port %d forwarding "
1316 "to %.100s port %d requested.",
1317 c->listening_port, c->path, c->host_port);
1319 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1320 nextstate = SSH_CHANNEL_OPENING;
1321 rtype = "forwarded-tcpip";
1323 if (c->host_port == 0) {
1324 nextstate = SSH_CHANNEL_DYNAMIC;
1325 rtype = "dynamic-tcpip";
1327 nextstate = SSH_CHANNEL_OPENING;
1328 rtype = "direct-tcpip";
1332 addrlen = sizeof(addr);
1333 newsock = accept(c->sock, &addr, &addrlen);
1335 error("accept: %.100s", strerror(errno));
1338 set_nodelay(newsock);
1339 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1340 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1341 nc->listening_port = c->listening_port;
1342 nc->host_port = c->host_port;
1343 strlcpy(nc->path, c->path, sizeof(nc->path));
1345 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1347 * do not call the channel_post handler until
1348 * this flag has been reset by a pre-handler.
1349 * otherwise the FD_ISSET calls might overflow
1353 port_open_helper(nc, rtype);
1359 * This is the authentication agent socket listening for connections from
1364 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1368 struct sockaddr addr;
1371 if (FD_ISSET(c->sock, readset)) {
1372 addrlen = sizeof(addr);
1373 newsock = accept(c->sock, &addr, &addrlen);
1375 error("accept from auth socket: %.100s", strerror(errno));
1378 nc = channel_new("accepted auth socket",
1379 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1380 c->local_window_max, c->local_maxpacket,
1381 0, "accepted auth socket", 1);
1383 packet_start(SSH2_MSG_CHANNEL_OPEN);
1384 packet_put_cstring("auth-agent@openssh.com");
1385 packet_put_int(nc->self);
1386 packet_put_int(c->local_window_max);
1387 packet_put_int(c->local_maxpacket);
1389 packet_start(SSH_SMSG_AGENT_OPEN);
1390 packet_put_int(nc->self);
1398 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1401 socklen_t sz = sizeof(err);
1403 if (FD_ISSET(c->sock, writeset)) {
1404 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1406 error("getsockopt SO_ERROR failed");
1409 debug("channel %d: connected", c->self);
1410 c->type = SSH_CHANNEL_OPEN;
1412 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1413 packet_put_int(c->remote_id);
1414 packet_put_int(c->self);
1415 packet_put_int(c->local_window);
1416 packet_put_int(c->local_maxpacket);
1418 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1419 packet_put_int(c->remote_id);
1420 packet_put_int(c->self);
1423 debug("channel %d: not connected: %s",
1424 c->self, strerror(err));
1426 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1427 packet_put_int(c->remote_id);
1428 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1429 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1430 packet_put_cstring(strerror(err));
1431 packet_put_cstring("");
1434 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1435 packet_put_int(c->remote_id);
1445 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1447 char buf[CHAN_RBUF];
1451 FD_ISSET(c->rfd, readset)) {
1453 len = read(c->rfd, buf, sizeof(buf));
1454 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1456 #ifndef PTY_ZEROREAD
1459 if ((!c->isatty && len <= 0) ||
1460 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1462 debug2("channel %d: read<=0 rfd %d len %d",
1463 c->self, c->rfd, len);
1464 if (c->type != SSH_CHANNEL_OPEN) {
1465 debug2("channel %d: not open", c->self);
1468 } else if (compat13) {
1469 buffer_clear(&c->output);
1470 c->type = SSH_CHANNEL_INPUT_DRAINING;
1471 debug2("channel %d: input draining.", c->self);
1473 chan_read_failed(c);
1477 if (c->input_filter != NULL) {
1478 if (c->input_filter(c, buf, len) == -1) {
1479 debug2("channel %d: filter stops", c->self);
1480 chan_read_failed(c);
1482 } else if (c->datagram) {
1483 buffer_put_string(&c->input, buf, len);
1485 buffer_append(&c->input, buf, len);
1493 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1496 u_char *data = NULL, *buf;
1500 /* Send buffered output data to the socket. */
1502 FD_ISSET(c->wfd, writeset) &&
1503 buffer_len(&c->output) > 0) {
1504 if (c->output_filter != NULL) {
1505 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1506 debug2("channel %d: filter stops", c->self);
1507 if (c->type != SSH_CHANNEL_OPEN)
1510 chan_write_failed(c);
1513 } else if (c->datagram) {
1514 buf = data = buffer_get_string(&c->output, &dlen);
1516 buf = data = buffer_ptr(&c->output);
1517 dlen = buffer_len(&c->output);
1521 /* ignore truncated writes, datagrams might get lost */
1522 c->local_consumed += dlen + 4;
1523 len = write(c->wfd, buf, dlen);
1525 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1528 if (c->type != SSH_CHANNEL_OPEN)
1531 chan_write_failed(c);
1537 /* XXX: Later AIX versions can't push as much data to tty */
1538 if (compat20 && c->wfd_isatty)
1539 dlen = MIN(dlen, 8*1024);
1542 len = write(c->wfd, buf, dlen);
1543 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1546 if (c->type != SSH_CHANNEL_OPEN) {
1547 debug2("channel %d: not open", c->self);
1550 } else if (compat13) {
1551 buffer_clear(&c->output);
1552 debug2("channel %d: input draining.", c->self);
1553 c->type = SSH_CHANNEL_INPUT_DRAINING;
1555 chan_write_failed(c);
1559 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1560 if (tcgetattr(c->wfd, &tio) == 0 &&
1561 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1563 * Simulate echo to reduce the impact of
1564 * traffic analysis. We need to match the
1565 * size of a SSH2_MSG_CHANNEL_DATA message
1566 * (4 byte channel id + buf)
1568 packet_send_ignore(4 + len);
1572 buffer_consume(&c->output, len);
1573 if (compat20 && len > 0) {
1574 c->local_consumed += len;
1581 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1583 char buf[CHAN_RBUF];
1586 /** XXX handle drain efd, too */
1588 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1589 FD_ISSET(c->efd, writeset) &&
1590 buffer_len(&c->extended) > 0) {
1591 len = write(c->efd, buffer_ptr(&c->extended),
1592 buffer_len(&c->extended));
1593 debug2("channel %d: written %d to efd %d",
1594 c->self, len, c->efd);
1595 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1598 debug2("channel %d: closing write-efd %d",
1600 channel_close_fd(&c->efd);
1602 buffer_consume(&c->extended, len);
1603 c->local_consumed += len;
1605 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1606 FD_ISSET(c->efd, readset)) {
1607 len = read(c->efd, buf, sizeof(buf));
1608 debug2("channel %d: read %d from efd %d",
1609 c->self, len, c->efd);
1610 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1613 debug2("channel %d: closing read-efd %d",
1615 channel_close_fd(&c->efd);
1617 buffer_append(&c->extended, buf, len);
1626 channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
1631 /* Monitor control fd to detect if the slave client exits */
1632 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1633 len = read(c->ctl_fd, buf, sizeof(buf));
1634 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1637 debug2("channel %d: ctl read<=0", c->self);
1638 if (c->type != SSH_CHANNEL_OPEN) {
1639 debug2("channel %d: not open", c->self);
1643 chan_read_failed(c);
1644 chan_write_failed(c);
1648 fatal("%s: unexpected data on ctl fd", __func__);
1654 channel_check_window(Channel *c)
1656 if (c->type == SSH_CHANNEL_OPEN &&
1657 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1658 c->local_window < c->local_window_max/2 &&
1659 c->local_consumed > 0) {
1660 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1661 packet_put_int(c->remote_id);
1662 packet_put_int(c->local_consumed);
1664 debug2("channel %d: window %d sent adjust %d",
1665 c->self, c->local_window,
1667 c->local_window += c->local_consumed;
1668 c->local_consumed = 0;
1674 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1678 channel_handle_rfd(c, readset, writeset);
1679 channel_handle_wfd(c, readset, writeset);
1682 channel_handle_efd(c, readset, writeset);
1683 channel_handle_ctl(c, readset, writeset);
1684 channel_check_window(c);
1689 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1693 /* Send buffered output data to the socket. */
1694 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1695 len = write(c->sock, buffer_ptr(&c->output),
1696 buffer_len(&c->output));
1698 buffer_clear(&c->output);
1700 buffer_consume(&c->output, len);
1705 channel_handler_init_20(void)
1707 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1708 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1709 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1710 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1711 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1712 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1713 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1714 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1716 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1717 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1718 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1719 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1720 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1721 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1722 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1726 channel_handler_init_13(void)
1728 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1729 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1730 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1731 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1732 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1733 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1734 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1735 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1736 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1738 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1739 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1740 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1741 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1742 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1743 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1744 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1748 channel_handler_init_15(void)
1750 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1751 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1752 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1753 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1754 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1755 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1756 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1758 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1759 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1760 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1761 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1762 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1763 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1767 channel_handler_init(void)
1771 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1772 channel_pre[i] = NULL;
1773 channel_post[i] = NULL;
1776 channel_handler_init_20();
1778 channel_handler_init_13();
1780 channel_handler_init_15();
1783 /* gc dead channels */
1785 channel_garbage_collect(Channel *c)
1789 if (c->detach_user != NULL) {
1790 if (!chan_is_dead(c, c->detach_close))
1792 debug2("channel %d: gc: notify user", c->self);
1793 c->detach_user(c->self, NULL);
1794 /* if we still have a callback */
1795 if (c->detach_user != NULL)
1797 debug2("channel %d: gc: user detached", c->self);
1799 if (!chan_is_dead(c, 1))
1801 debug2("channel %d: garbage collecting", c->self);
1806 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1808 static int did_init = 0;
1813 channel_handler_init();
1816 for (i = 0; i < channels_alloc; i++) {
1820 if (ftab[c->type] != NULL)
1821 (*ftab[c->type])(c, readset, writeset);
1822 channel_garbage_collect(c);
1827 * Allocate/update select bitmasks and add any bits relevant to channels in
1831 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1832 u_int *nallocp, int rekeying)
1834 u_int n, sz, nfdset;
1836 n = MAX(*maxfdp, channel_max_fd);
1838 nfdset = howmany(n+1, NFDBITS);
1839 /* Explicitly test here, because xrealloc isn't always called */
1840 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
1841 fatal("channel_prepare_select: max_fd (%d) is too large", n);
1842 sz = nfdset * sizeof(fd_mask);
1844 /* perhaps check sz < nalloc/2 and shrink? */
1845 if (*readsetp == NULL || sz > *nallocp) {
1846 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
1847 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1851 memset(*readsetp, 0, sz);
1852 memset(*writesetp, 0, sz);
1855 channel_handler(channel_pre, *readsetp, *writesetp);
1859 * After select, perform any appropriate operations for channels which have
1863 channel_after_select(fd_set *readset, fd_set *writeset)
1865 channel_handler(channel_post, readset, writeset);
1869 /* If there is data to send to the connection, enqueue some of it now. */
1871 channel_output_poll(void)
1876 for (i = 0; i < channels_alloc; i++) {
1882 * We are only interested in channels that can have buffered
1886 if (c->type != SSH_CHANNEL_OPEN &&
1887 c->type != SSH_CHANNEL_INPUT_DRAINING)
1890 if (c->type != SSH_CHANNEL_OPEN)
1894 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1895 /* XXX is this true? */
1896 debug3("channel %d: will not send data after close", c->self);
1900 /* Get the amount of buffered data for this channel. */
1901 if ((c->istate == CHAN_INPUT_OPEN ||
1902 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1903 (len = buffer_len(&c->input)) > 0) {
1909 data = buffer_get_string(&c->input,
1911 packet_start(SSH2_MSG_CHANNEL_DATA);
1912 packet_put_int(c->remote_id);
1913 packet_put_string(data, dlen);
1915 c->remote_window -= dlen + 4;
1921 * Send some data for the other side over the secure
1925 if (len > c->remote_window)
1926 len = c->remote_window;
1927 if (len > c->remote_maxpacket)
1928 len = c->remote_maxpacket;
1930 if (packet_is_interactive()) {
1934 /* Keep the packets at reasonable size. */
1935 if (len > packet_get_maxsize()/2)
1936 len = packet_get_maxsize()/2;
1940 packet_start(compat20 ?
1941 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1942 packet_put_int(c->remote_id);
1943 packet_put_string(buffer_ptr(&c->input), len);
1945 buffer_consume(&c->input, len);
1946 c->remote_window -= len;
1948 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1950 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1952 * input-buffer is empty and read-socket shutdown:
1953 * tell peer, that we will not send more data: send IEOF.
1954 * hack for extended data: delay EOF if EFD still in use.
1956 if (CHANNEL_EFD_INPUT_ACTIVE(c))
1957 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1958 c->self, c->efd, buffer_len(&c->extended));
1962 /* Send extended data, i.e. stderr */
1964 !(c->flags & CHAN_EOF_SENT) &&
1965 c->remote_window > 0 &&
1966 (len = buffer_len(&c->extended)) > 0 &&
1967 c->extended_usage == CHAN_EXTENDED_READ) {
1968 debug2("channel %d: rwin %u elen %u euse %d",
1969 c->self, c->remote_window, buffer_len(&c->extended),
1971 if (len > c->remote_window)
1972 len = c->remote_window;
1973 if (len > c->remote_maxpacket)
1974 len = c->remote_maxpacket;
1975 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
1976 packet_put_int(c->remote_id);
1977 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
1978 packet_put_string(buffer_ptr(&c->extended), len);
1980 buffer_consume(&c->extended, len);
1981 c->remote_window -= len;
1982 debug2("channel %d: sent ext data %d", c->self, len);
1988 /* -- protocol input */
1992 channel_input_data(int type, u_int32_t seq, void *ctxt)
1999 /* Get the channel number and verify it. */
2000 id = packet_get_int();
2001 c = channel_lookup(id);
2003 packet_disconnect("Received data for nonexistent channel %d.", id);
2005 /* Ignore any data for non-open channels (might happen on close) */
2006 if (c->type != SSH_CHANNEL_OPEN &&
2007 c->type != SSH_CHANNEL_X11_OPEN)
2011 data = packet_get_string(&data_len);
2014 * Ignore data for protocol > 1.3 if output end is no longer open.
2015 * For protocol 2 the sending side is reducing its window as it sends
2016 * data, so we must 'fake' consumption of the data in order to ensure
2017 * that window updates are sent back. Otherwise the connection might
2020 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2022 c->local_window -= data_len;
2023 c->local_consumed += data_len;
2030 if (data_len > c->local_maxpacket) {
2031 logit("channel %d: rcvd big packet %d, maxpack %d",
2032 c->self, data_len, c->local_maxpacket);
2034 if (data_len > c->local_window) {
2035 logit("channel %d: rcvd too much data %d, win %d",
2036 c->self, data_len, c->local_window);
2040 c->local_window -= data_len;
2044 buffer_put_string(&c->output, data, data_len);
2046 buffer_append(&c->output, data, data_len);
2052 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2056 u_int data_len, tcode;
2059 /* Get the channel number and verify it. */
2060 id = packet_get_int();
2061 c = channel_lookup(id);
2064 packet_disconnect("Received extended_data for bad channel %d.", id);
2065 if (c->type != SSH_CHANNEL_OPEN) {
2066 logit("channel %d: ext data for non open", id);
2069 if (c->flags & CHAN_EOF_RCVD) {
2070 if (datafellows & SSH_BUG_EXTEOF)
2071 debug("channel %d: accepting ext data after eof", id);
2073 packet_disconnect("Received extended_data after EOF "
2074 "on channel %d.", id);
2076 tcode = packet_get_int();
2078 c->extended_usage != CHAN_EXTENDED_WRITE ||
2079 tcode != SSH2_EXTENDED_DATA_STDERR) {
2080 logit("channel %d: bad ext data", c->self);
2083 data = packet_get_string(&data_len);
2085 if (data_len > c->local_window) {
2086 logit("channel %d: rcvd too much extended_data %d, win %d",
2087 c->self, data_len, c->local_window);
2091 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2092 c->local_window -= data_len;
2093 buffer_append(&c->extended, data, data_len);
2099 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2104 id = packet_get_int();
2106 c = channel_lookup(id);
2108 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2111 /* XXX force input close */
2112 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2113 debug("channel %d: FORCE input drain", c->self);
2114 c->istate = CHAN_INPUT_WAIT_DRAIN;
2115 if (buffer_len(&c->input) == 0)
2123 channel_input_close(int type, u_int32_t seq, void *ctxt)
2128 id = packet_get_int();
2130 c = channel_lookup(id);
2132 packet_disconnect("Received close for nonexistent channel %d.", id);
2135 * Send a confirmation that we have closed the channel and no more
2136 * data is coming for it.
2138 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2139 packet_put_int(c->remote_id);
2143 * If the channel is in closed state, we have sent a close request,
2144 * and the other side will eventually respond with a confirmation.
2145 * Thus, we cannot free the channel here, because then there would be
2146 * no-one to receive the confirmation. The channel gets freed when
2147 * the confirmation arrives.
2149 if (c->type != SSH_CHANNEL_CLOSED) {
2151 * Not a closed channel - mark it as draining, which will
2152 * cause it to be freed later.
2154 buffer_clear(&c->input);
2155 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2159 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2162 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2164 int id = packet_get_int();
2165 Channel *c = channel_lookup(id);
2169 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2170 chan_rcvd_oclose(c);
2175 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2177 int id = packet_get_int();
2178 Channel *c = channel_lookup(id);
2182 packet_disconnect("Received close confirmation for "
2183 "out-of-range channel %d.", id);
2184 if (c->type != SSH_CHANNEL_CLOSED)
2185 packet_disconnect("Received close confirmation for "
2186 "non-closed channel %d (type %d).", id, c->type);
2192 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2197 id = packet_get_int();
2198 c = channel_lookup(id);
2200 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2201 packet_disconnect("Received open confirmation for "
2202 "non-opening channel %d.", id);
2203 remote_id = packet_get_int();
2204 /* Record the remote channel number and mark that the channel is now open. */
2205 c->remote_id = remote_id;
2206 c->type = SSH_CHANNEL_OPEN;
2209 c->remote_window = packet_get_int();
2210 c->remote_maxpacket = packet_get_int();
2212 debug2("callback start");
2213 c->confirm(c->self, c->confirm_ctx);
2214 debug2("callback done");
2216 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2217 c->remote_window, c->remote_maxpacket);
2223 reason2txt(int reason)
2226 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2227 return "administratively prohibited";
2228 case SSH2_OPEN_CONNECT_FAILED:
2229 return "connect failed";
2230 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2231 return "unknown channel type";
2232 case SSH2_OPEN_RESOURCE_SHORTAGE:
2233 return "resource shortage";
2235 return "unknown reason";
2240 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2243 char *msg = NULL, *lang = NULL;
2246 id = packet_get_int();
2247 c = channel_lookup(id);
2249 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2250 packet_disconnect("Received open failure for "
2251 "non-opening channel %d.", id);
2253 reason = packet_get_int();
2254 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2255 msg = packet_get_string(NULL);
2256 lang = packet_get_string(NULL);
2258 logit("channel %d: open failed: %s%s%s", id,
2259 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2266 /* Free the channel. This will also close the socket. */
2272 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2281 /* Get the channel number and verify it. */
2282 id = packet_get_int();
2283 c = channel_lookup(id);
2286 logit("Received window adjust for non-open channel %d.", id);
2289 adjust = packet_get_int();
2291 debug2("channel %d: rcvd adjust %u", id, adjust);
2292 c->remote_window += adjust;
2297 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2301 char *host, *originator_string;
2302 int remote_id, sock = -1;
2304 remote_id = packet_get_int();
2305 host = packet_get_string(NULL);
2306 host_port = packet_get_int();
2308 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2309 originator_string = packet_get_string(NULL);
2311 originator_string = xstrdup("unknown (remote did not supply name)");
2314 sock = channel_connect_to(host, host_port);
2316 c = channel_new("connected socket",
2317 SSH_CHANNEL_CONNECTING, sock, sock, -1, 0, 0, 0,
2318 originator_string, 1);
2319 c->remote_id = remote_id;
2321 xfree(originator_string);
2323 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2324 packet_put_int(remote_id);
2331 /* -- tcp forwarding */
2334 channel_set_af(int af)
2340 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2341 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2344 int sock, r, success = 0, wildcard = 0, is_client;
2345 struct addrinfo hints, *ai, *aitop;
2346 const char *host, *addr;
2347 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2349 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2350 listen_addr : host_to_connect;
2351 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2354 error("No forward host name.");
2357 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2358 error("Forward host name too long.");
2363 * Determine whether or not a port forward listens to loopback,
2364 * specified address or wildcard. On the client, a specified bind
2365 * address will always override gateway_ports. On the server, a
2366 * gateway_ports of 1 (``yes'') will override the client's
2367 * specification and force a wildcard bind, whereas a value of 2
2368 * (``clientspecified'') will bind to whatever address the client
2371 * Special-case listen_addrs are:
2373 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2374 * "" (empty string), "*" -> wildcard v4/v6
2375 * "localhost" -> loopback v4/v6
2378 if (listen_addr == NULL) {
2379 /* No address specified: default to gateway_ports setting */
2382 } else if (gateway_ports || is_client) {
2383 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2384 strcmp(listen_addr, "0.0.0.0") == 0) ||
2385 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2386 (!is_client && gateway_ports == 1))
2388 else if (strcmp(listen_addr, "localhost") != 0)
2392 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2393 type, wildcard, (addr == NULL) ? "NULL" : addr);
2396 * getaddrinfo returns a loopback address if the hostname is
2397 * set to NULL and hints.ai_flags is not AI_PASSIVE
2399 memset(&hints, 0, sizeof(hints));
2400 hints.ai_family = IPv4or6;
2401 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2402 hints.ai_socktype = SOCK_STREAM;
2403 snprintf(strport, sizeof strport, "%d", listen_port);
2404 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2406 /* This really shouldn't happen */
2407 packet_disconnect("getaddrinfo: fatal error: %s",
2410 error("channel_setup_fwd_listener: "
2411 "getaddrinfo(%.64s): %s", addr, gai_strerror(r));
2416 for (ai = aitop; ai; ai = ai->ai_next) {
2417 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2419 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2420 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2421 error("channel_setup_fwd_listener: getnameinfo failed");
2424 /* Create a port to listen for the host. */
2425 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2427 /* this is no error since kernel may not support ipv6 */
2428 verbose("socket: %.100s", strerror(errno));
2432 channel_set_reuseaddr(sock);
2434 debug("Local forwarding listening on %s port %s.", ntop, strport);
2436 /* Bind the socket to the address. */
2437 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2438 /* address can be in use ipv6 address is already bound */
2440 error("bind: %.100s", strerror(errno));
2442 verbose("bind: %.100s", strerror(errno));
2447 /* Start listening for connections on the socket. */
2448 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2449 error("listen: %.100s", strerror(errno));
2453 /* Allocate a channel number for the socket. */
2454 c = channel_new("port listener", type, sock, sock, -1,
2455 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2456 0, "port listener", 1);
2457 strlcpy(c->path, host, sizeof(c->path));
2458 c->host_port = port_to_connect;
2459 c->listening_port = listen_port;
2463 error("channel_setup_fwd_listener: cannot listen to port: %d",
2465 freeaddrinfo(aitop);
2470 channel_cancel_rport_listener(const char *host, u_short port)
2475 for (i = 0; i < channels_alloc; i++) {
2476 Channel *c = channels[i];
2478 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2479 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2480 c->listening_port == port) {
2481 debug2("%s: close channel %d", __func__, i);
2490 /* protocol local port fwd, used by ssh (and sshd in v1) */
2492 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2493 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2495 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2496 listen_host, listen_port, host_to_connect, port_to_connect,
2500 /* protocol v2 remote port fwd, used by sshd */
2502 channel_setup_remote_fwd_listener(const char *listen_address,
2503 u_short listen_port, int gateway_ports)
2505 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2506 listen_address, listen_port, NULL, 0, gateway_ports);
2510 * Initiate forwarding of connections to port "port" on remote host through
2511 * the secure channel to host:port from local side.
2515 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2516 const char *host_to_connect, u_short port_to_connect)
2518 int type, success = 0;
2520 /* Record locally that connection to this host/port is permitted. */
2521 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2522 fatal("channel_request_remote_forwarding: too many forwards");
2524 /* Send the forward request to the remote side. */
2526 const char *address_to_bind;
2527 if (listen_host == NULL)
2528 address_to_bind = "localhost";
2529 else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0)
2530 address_to_bind = "";
2532 address_to_bind = listen_host;
2534 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2535 packet_put_cstring("tcpip-forward");
2536 packet_put_char(1); /* boolean: want reply */
2537 packet_put_cstring(address_to_bind);
2538 packet_put_int(listen_port);
2540 packet_write_wait();
2541 /* Assume that server accepts the request */
2544 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2545 packet_put_int(listen_port);
2546 packet_put_cstring(host_to_connect);
2547 packet_put_int(port_to_connect);
2549 packet_write_wait();
2551 /* Wait for response from the remote side. */
2552 type = packet_read();
2554 case SSH_SMSG_SUCCESS:
2557 case SSH_SMSG_FAILURE:
2560 /* Unknown packet */
2561 packet_disconnect("Protocol error for port forward request:"
2562 "received packet type %d.", type);
2566 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2567 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2568 permitted_opens[num_permitted_opens].listen_port = listen_port;
2569 num_permitted_opens++;
2571 return (success ? 0 : -1);
2575 * Request cancellation of remote forwarding of connection host:port from
2579 channel_request_rforward_cancel(const char *host, u_short port)
2586 for (i = 0; i < num_permitted_opens; i++) {
2587 if (permitted_opens[i].host_to_connect != NULL &&
2588 permitted_opens[i].listen_port == port)
2591 if (i >= num_permitted_opens) {
2592 debug("%s: requested forward not found", __func__);
2595 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2596 packet_put_cstring("cancel-tcpip-forward");
2598 packet_put_cstring(host == NULL ? "" : host);
2599 packet_put_int(port);
2602 permitted_opens[i].listen_port = 0;
2603 permitted_opens[i].port_to_connect = 0;
2604 xfree(permitted_opens[i].host_to_connect);
2605 permitted_opens[i].host_to_connect = NULL;
2609 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2610 * listening for the port, and sends back a success reply (or disconnect
2611 * message if there was an error).
2614 channel_input_port_forward_request(int is_root, int gateway_ports)
2616 u_short port, host_port;
2620 /* Get arguments from the packet. */
2621 port = packet_get_int();
2622 hostname = packet_get_string(NULL);
2623 host_port = packet_get_int();
2627 * Check that an unprivileged user is not trying to forward a
2630 if (port < IPPORT_RESERVED && !is_root)
2632 "Requested forwarding of port %d but user is not root.",
2635 packet_disconnect("Dynamic forwarding denied.");
2638 /* Initiate forwarding */
2639 success = channel_setup_local_fwd_listener(NULL, port, hostname,
2640 host_port, gateway_ports);
2642 /* Free the argument string. */
2645 return (success ? 0 : -1);
2649 * Permits opening to any host/port if permitted_opens[] is empty. This is
2650 * usually called by the server, because the user could connect to any port
2651 * anyway, and the server has no way to know but to trust the client anyway.
2654 channel_permit_all_opens(void)
2656 if (num_permitted_opens == 0)
2657 all_opens_permitted = 1;
2661 channel_add_permitted_opens(char *host, int port)
2663 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2664 fatal("channel_add_permitted_opens: too many forwards");
2665 debug("allow port forwarding to host %s port %d", host, port);
2667 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2668 permitted_opens[num_permitted_opens].port_to_connect = port;
2669 num_permitted_opens++;
2671 all_opens_permitted = 0;
2675 channel_add_adm_permitted_opens(char *host, int port)
2677 if (num_adm_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2678 fatal("channel_add_adm_permitted_opens: too many forwards");
2679 debug("config allows port forwarding to host %s port %d", host, port);
2681 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
2683 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
2684 return ++num_adm_permitted_opens;
2688 channel_clear_permitted_opens(void)
2692 for (i = 0; i < num_permitted_opens; i++)
2693 if (permitted_opens[i].host_to_connect != NULL)
2694 xfree(permitted_opens[i].host_to_connect);
2695 num_permitted_opens = 0;
2699 channel_clear_adm_permitted_opens(void)
2703 for (i = 0; i < num_adm_permitted_opens; i++)
2704 if (permitted_adm_opens[i].host_to_connect != NULL)
2705 xfree(permitted_adm_opens[i].host_to_connect);
2706 num_adm_permitted_opens = 0;
2709 /* return socket to remote host, port */
2711 connect_to(const char *host, u_short port)
2713 struct addrinfo hints, *ai, *aitop;
2714 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2718 memset(&hints, 0, sizeof(hints));
2719 hints.ai_family = IPv4or6;
2720 hints.ai_socktype = SOCK_STREAM;
2721 snprintf(strport, sizeof strport, "%d", port);
2722 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
2723 error("connect_to %.100s: unknown host (%s)", host,
2724 gai_strerror(gaierr));
2727 for (ai = aitop; ai; ai = ai->ai_next) {
2728 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2730 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2731 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2732 error("connect_to: getnameinfo failed");
2735 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2737 if (ai->ai_next == NULL)
2738 error("socket: %.100s", strerror(errno));
2740 verbose("socket: %.100s", strerror(errno));
2743 if (set_nonblock(sock) == -1)
2744 fatal("%s: set_nonblock(%d)", __func__, sock);
2745 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0 &&
2746 errno != EINPROGRESS) {
2747 error("connect_to %.100s port %s: %.100s", ntop, strport,
2750 continue; /* fail -- try next */
2752 break; /* success */
2755 freeaddrinfo(aitop);
2757 error("connect_to %.100s port %d: failed.", host, port);
2766 channel_connect_by_listen_address(u_short listen_port)
2770 for (i = 0; i < num_permitted_opens; i++)
2771 if (permitted_opens[i].host_to_connect != NULL &&
2772 permitted_opens[i].listen_port == listen_port)
2774 permitted_opens[i].host_to_connect,
2775 permitted_opens[i].port_to_connect);
2776 error("WARNING: Server requests forwarding for unknown listen_port %d",
2781 /* Check if connecting to that port is permitted and connect. */
2783 channel_connect_to(const char *host, u_short port)
2785 int i, permit, permit_adm = 1;
2787 permit = all_opens_permitted;
2789 for (i = 0; i < num_permitted_opens; i++)
2790 if (permitted_opens[i].host_to_connect != NULL &&
2791 permitted_opens[i].port_to_connect == port &&
2792 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2796 if (num_adm_permitted_opens > 0) {
2798 for (i = 0; i < num_adm_permitted_opens; i++)
2799 if (permitted_adm_opens[i].host_to_connect != NULL &&
2800 permitted_adm_opens[i].port_to_connect == port &&
2801 strcmp(permitted_adm_opens[i].host_to_connect, host)
2806 if (!permit || !permit_adm) {
2807 logit("Received request to connect to host %.100s port %d, "
2808 "but the request was denied.", host, port);
2811 return connect_to(host, port);
2815 channel_send_window_changes(void)
2820 for (i = 0; i < channels_alloc; i++) {
2821 if (channels[i] == NULL || !channels[i]->client_tty ||
2822 channels[i]->type != SSH_CHANNEL_OPEN)
2824 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2826 channel_request_start(i, "window-change", 0);
2827 packet_put_int((u_int)ws.ws_col);
2828 packet_put_int((u_int)ws.ws_row);
2829 packet_put_int((u_int)ws.ws_xpixel);
2830 packet_put_int((u_int)ws.ws_ypixel);
2835 /* -- X11 forwarding */
2838 * Creates an internet domain socket for listening for X11 connections.
2839 * Returns 0 and a suitable display number for the DISPLAY variable
2840 * stored in display_numberp , or -1 if an error occurs.
2843 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2844 int single_connection, u_int *display_numberp, int **chanids)
2847 int display_number, sock;
2849 struct addrinfo hints, *ai, *aitop;
2850 char strport[NI_MAXSERV];
2851 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2853 if (chanids == NULL)
2856 for (display_number = x11_display_offset;
2857 display_number < MAX_DISPLAYS;
2859 port = 6000 + display_number;
2860 memset(&hints, 0, sizeof(hints));
2861 hints.ai_family = IPv4or6;
2862 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2863 hints.ai_socktype = SOCK_STREAM;
2864 snprintf(strport, sizeof strport, "%d", port);
2865 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
2866 error("getaddrinfo: %.100s", gai_strerror(gaierr));
2869 for (ai = aitop; ai; ai = ai->ai_next) {
2870 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2872 sock = socket(ai->ai_family, ai->ai_socktype,
2875 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
2876 error("socket: %.100s", strerror(errno));
2877 freeaddrinfo(aitop);
2880 debug("x11_create_display_inet: Socket family %d not supported",
2886 if (ai->ai_family == AF_INET6) {
2888 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
2889 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
2892 channel_set_reuseaddr(sock);
2893 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2894 debug2("bind port %d: %.100s", port, strerror(errno));
2900 for (n = 0; n < num_socks; n++) {
2906 socks[num_socks++] = sock;
2907 #ifndef DONT_TRY_OTHER_AF
2908 if (num_socks == NUM_SOCKS)
2911 if (x11_use_localhost) {
2912 if (num_socks == NUM_SOCKS)
2919 freeaddrinfo(aitop);
2923 if (display_number >= MAX_DISPLAYS) {
2924 error("Failed to allocate internet-domain X11 display socket.");
2927 /* Start listening for connections on the socket. */
2928 for (n = 0; n < num_socks; n++) {
2930 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2931 error("listen: %.100s", strerror(errno));
2937 /* Allocate a channel for each socket. */
2938 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
2939 for (n = 0; n < num_socks; n++) {
2941 nc = channel_new("x11 listener",
2942 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
2943 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
2944 0, "X11 inet listener", 1);
2945 nc->single_connection = single_connection;
2946 (*chanids)[n] = nc->self;
2950 /* Return the display number for the DISPLAY environment variable. */
2951 *display_numberp = display_number;
2956 connect_local_xsocket(u_int dnr)
2959 struct sockaddr_un addr;
2961 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2963 error("socket: %.100s", strerror(errno));
2964 memset(&addr, 0, sizeof(addr));
2965 addr.sun_family = AF_UNIX;
2966 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
2967 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
2970 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
2975 x11_connect_display(void)
2977 u_int display_number;
2978 const char *display;
2979 char buf[1024], *cp;
2980 struct addrinfo hints, *ai, *aitop;
2981 char strport[NI_MAXSERV];
2982 int gaierr, sock = 0;
2984 /* Try to open a socket for the local X server. */
2985 display = getenv("DISPLAY");
2987 error("DISPLAY not set.");
2991 * Now we decode the value of the DISPLAY variable and make a
2992 * connection to the real X server.
2996 * Check if it is a unix domain socket. Unix domain displays are in
2997 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2999 if (strncmp(display, "unix:", 5) == 0 ||
3000 display[0] == ':') {
3001 /* Connect to the unix domain socket. */
3002 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
3003 error("Could not parse display number from DISPLAY: %.100s",
3007 /* Create a socket. */
3008 sock = connect_local_xsocket(display_number);
3012 /* OK, we now have a connection to the display. */
3016 * Connect to an inet socket. The DISPLAY value is supposedly
3017 * hostname:d[.s], where hostname may also be numeric IP address.
3019 strlcpy(buf, display, sizeof(buf));
3020 cp = strchr(buf, ':');
3022 error("Could not find ':' in DISPLAY: %.100s", display);
3026 /* buf now contains the host name. But first we parse the display number. */
3027 if (sscanf(cp + 1, "%u", &display_number) != 1) {
3028 error("Could not parse display number from DISPLAY: %.100s",
3033 /* Look up the host address */
3034 memset(&hints, 0, sizeof(hints));
3035 hints.ai_family = IPv4or6;
3036 hints.ai_socktype = SOCK_STREAM;
3037 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
3038 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
3039 error("%.100s: unknown host. (%s)", buf, gai_strerror(gaierr));
3042 for (ai = aitop; ai; ai = ai->ai_next) {
3043 /* Create a socket. */
3044 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3046 debug2("socket: %.100s", strerror(errno));
3049 /* Connect it to the display. */
3050 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3051 debug2("connect %.100s port %u: %.100s", buf,
3052 6000 + display_number, strerror(errno));
3059 freeaddrinfo(aitop);
3061 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3070 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3071 * the remote channel number. We should do whatever we want, and respond
3072 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3077 x11_input_open(int type, u_int32_t seq, void *ctxt)
3080 int remote_id, sock = 0;
3083 debug("Received X11 open request.");
3085 remote_id = packet_get_int();
3087 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3088 remote_host = packet_get_string(NULL);
3090 remote_host = xstrdup("unknown (remote did not supply name)");
3094 /* Obtain a connection to the real X display. */
3095 sock = x11_connect_display();
3097 /* Allocate a channel for this connection. */
3098 c = channel_new("connected x11 socket",
3099 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3101 c->remote_id = remote_id;
3106 /* Send refusal to the remote host. */
3107 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3108 packet_put_int(remote_id);
3110 /* Send a confirmation to the remote host. */
3111 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3112 packet_put_int(remote_id);
3113 packet_put_int(c->self);
3118 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3121 deny_input_open(int type, u_int32_t seq, void *ctxt)
3123 int rchan = packet_get_int();
3126 case SSH_SMSG_AGENT_OPEN:
3127 error("Warning: ssh server tried agent forwarding.");
3129 case SSH_SMSG_X11_OPEN:
3130 error("Warning: ssh server tried X11 forwarding.");
3133 error("deny_input_open: type %d", type);
3136 error("Warning: this is probably a break-in attempt by a malicious server.");
3137 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3138 packet_put_int(rchan);
3143 * Requests forwarding of X11 connections, generates fake authentication
3144 * data, and enables authentication spoofing.
3145 * This should be called in the client only.
3148 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3149 const char *proto, const char *data)
3151 u_int data_len = (u_int) strlen(data) / 2;
3158 if (x11_saved_display == NULL)
3159 x11_saved_display = xstrdup(disp);
3160 else if (strcmp(disp, x11_saved_display) != 0) {
3161 error("x11_request_forwarding_with_spoofing: different "
3162 "$DISPLAY already forwarded");
3168 cp = strchr(disp, ':');
3170 cp = strchr(cp, '.');
3172 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3176 if (x11_saved_proto == NULL) {
3177 /* Save protocol name. */
3178 x11_saved_proto = xstrdup(proto);
3180 * Extract real authentication data and generate fake data
3181 * of the same length.
3183 x11_saved_data = xmalloc(data_len);
3184 x11_fake_data = xmalloc(data_len);
3185 for (i = 0; i < data_len; i++) {
3186 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3187 fatal("x11_request_forwarding: bad "
3188 "authentication data: %.100s", data);
3191 x11_saved_data[i] = value;
3192 x11_fake_data[i] = rnd & 0xff;
3195 x11_saved_data_len = data_len;
3196 x11_fake_data_len = data_len;
3199 /* Convert the fake data into hex. */
3200 new_data = tohex(x11_fake_data, data_len);
3202 /* Send the request packet. */
3204 channel_request_start(client_session_id, "x11-req", 0);
3205 packet_put_char(0); /* XXX bool single connection */
3207 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3209 packet_put_cstring(proto);
3210 packet_put_cstring(new_data);
3211 packet_put_int(screen_number);
3213 packet_write_wait();
3218 /* -- agent forwarding */
3220 /* Sends a message to the server to request authentication fd forwarding. */
3223 auth_request_forwarding(void)
3225 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3227 packet_write_wait();