1 /* $OpenBSD: channels.c,v 1.280 2008/06/12 15:19:17 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/types.h>
45 #include <sys/ioctl.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>
64 #include "openbsd-compat/sys-queue.h"
78 #include "pathnames.h"
83 * Pointer to an array containing all allocated channels. The array is
84 * dynamically extended as needed.
86 static Channel **channels = NULL;
89 * Size of the channel array. All slots of the array must always be
90 * initialized (at least the type field); unused slots set to NULL
92 static u_int channels_alloc = 0;
95 * Maximum file descriptor value used in any of the channels. This is
96 * updated in channel_new.
98 static int channel_max_fd = 0;
101 /* -- tcp forwarding */
104 * Data structure for storing which hosts are permitted for forward requests.
105 * The local sides of any remote forwards are stored in this array to prevent
106 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
107 * network (which might be behind a firewall).
110 char *host_to_connect; /* Connect to 'host'. */
111 u_short port_to_connect; /* Connect to 'port'. */
112 u_short listen_port; /* Remote side should listen port number. */
115 /* List of all permitted host/port pairs to connect by the user. */
116 static ForwardPermission permitted_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
118 /* List of all permitted host/port pairs to connect by the admin. */
119 static ForwardPermission permitted_adm_opens[SSH_MAX_FORWARDS_PER_DIRECTION];
121 /* Number of permitted host/port pairs in the array permitted by the user. */
122 static int num_permitted_opens = 0;
124 /* Number of permitted host/port pair in the array permitted by the admin. */
125 static int num_adm_permitted_opens = 0;
128 * If this is true, all opens are permitted. This is the case on the server
129 * on which we have to trust the client anyway, and the user could do
130 * anything after logging in anyway.
132 static int all_opens_permitted = 0;
135 /* -- X11 forwarding */
137 /* Maximum number of fake X11 displays to try. */
138 #define MAX_DISPLAYS 1000
140 /* Saved X11 local (client) display. */
141 static char *x11_saved_display = NULL;
143 /* Saved X11 authentication protocol name. */
144 static char *x11_saved_proto = NULL;
146 /* Saved X11 authentication data. This is the real data. */
147 static char *x11_saved_data = NULL;
148 static u_int x11_saved_data_len = 0;
151 * Fake X11 authentication data. This is what the server will be sending us;
152 * we should replace any occurrences of this by the real data.
154 static u_char *x11_fake_data = NULL;
155 static u_int x11_fake_data_len;
158 /* -- agent forwarding */
162 /* AF_UNSPEC or AF_INET or AF_INET6 */
163 static int IPv4or6 = AF_UNSPEC;
166 static void port_open_helper(Channel *c, char *rtype);
168 /* non-blocking connect helpers */
169 static int connect_next(struct channel_connect *);
170 static void channel_connect_ctx_free(struct channel_connect *);
172 /* -- channel core */
175 channel_by_id(int id)
179 if (id < 0 || (u_int)id >= channels_alloc) {
180 logit("channel_by_id: %d: bad id", id);
185 logit("channel_by_id: %d: bad id: channel free", id);
192 * Returns the channel if it is allowed to receive protocol messages.
193 * Private channels, like listening sockets, may not receive messages.
196 channel_lookup(int id)
200 if ((c = channel_by_id(id)) == NULL)
204 case SSH_CHANNEL_X11_OPEN:
205 case SSH_CHANNEL_LARVAL:
206 case SSH_CHANNEL_CONNECTING:
207 case SSH_CHANNEL_DYNAMIC:
208 case SSH_CHANNEL_OPENING:
209 case SSH_CHANNEL_OPEN:
210 case SSH_CHANNEL_INPUT_DRAINING:
211 case SSH_CHANNEL_OUTPUT_DRAINING:
214 logit("Non-public channel %d, type %d.", id, c->type);
219 * Register filedescriptors for a channel, used when allocating a channel or
220 * when the channel consumer/producer is ready, e.g. shell exec'd
223 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
224 int extusage, int nonblock)
226 /* Update the maximum file descriptor value. */
227 channel_max_fd = MAX(channel_max_fd, rfd);
228 channel_max_fd = MAX(channel_max_fd, wfd);
229 channel_max_fd = MAX(channel_max_fd, efd);
231 /* XXX set close-on-exec -markus */
235 c->sock = (rfd == wfd) ? rfd : -1;
236 c->ctl_fd = -1; /* XXX: set elsewhere */
238 c->extended_usage = extusage;
240 /* XXX ugly hack: nonblock is only set by the server */
241 if (nonblock && isatty(c->rfd)) {
242 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
244 if (!isatty(c->wfd)) {
245 error("channel %d: wfd %d is not a tty?",
251 c->wfd_isatty = isatty(c->wfd);
253 /* enable nonblocking mode */
265 * Allocate a new channel object and set its type and socket. This will cause
266 * remote_name to be freed.
269 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
270 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
276 /* Do initial allocation if this is the first call. */
277 if (channels_alloc == 0) {
279 channels = xcalloc(channels_alloc, sizeof(Channel *));
280 for (i = 0; i < channels_alloc; i++)
283 /* Try to find a free slot where to put the new channel. */
284 for (found = -1, i = 0; i < channels_alloc; i++)
285 if (channels[i] == NULL) {
286 /* Found a free slot. */
291 /* There are no free slots. Take last+1 slot and expand the array. */
292 found = channels_alloc;
293 if (channels_alloc > 10000)
294 fatal("channel_new: internal error: channels_alloc %d "
295 "too big.", channels_alloc);
296 channels = xrealloc(channels, channels_alloc + 10,
298 channels_alloc += 10;
299 debug2("channel: expanding %d", channels_alloc);
300 for (i = found; i < channels_alloc; i++)
303 /* Initialize and return new channel. */
304 c = channels[found] = xcalloc(1, sizeof(Channel));
305 buffer_init(&c->input);
306 buffer_init(&c->output);
307 buffer_init(&c->extended);
308 c->ostate = CHAN_OUTPUT_OPEN;
309 c->istate = CHAN_INPUT_OPEN;
311 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
315 c->local_window = window;
316 c->local_window_max = window;
317 c->local_consumed = 0;
318 c->local_maxpacket = maxpack;
320 c->remote_name = xstrdup(remote_name);
321 c->remote_window = 0;
322 c->remote_maxpacket = 0;
324 c->single_connection = 0;
325 c->detach_user = NULL;
327 c->open_confirm = NULL;
328 c->open_confirm_ctx = NULL;
329 c->input_filter = NULL;
330 c->output_filter = NULL;
331 c->filter_ctx = NULL;
332 c->filter_cleanup = NULL;
333 TAILQ_INIT(&c->status_confirms);
334 debug("channel %d: new [%s]", found, remote_name);
339 channel_find_maxfd(void)
345 for (i = 0; i < channels_alloc; i++) {
348 max = MAX(max, c->rfd);
349 max = MAX(max, c->wfd);
350 max = MAX(max, c->efd);
357 channel_close_fd(int *fdp)
359 int ret = 0, fd = *fdp;
364 if (fd == channel_max_fd)
365 channel_max_fd = channel_find_maxfd();
370 /* Close all channel fd/socket. */
372 channel_close_fds(Channel *c)
374 debug3("channel %d: close_fds r %d w %d e %d c %d",
375 c->self, c->rfd, c->wfd, c->efd, c->ctl_fd);
377 channel_close_fd(&c->sock);
378 channel_close_fd(&c->ctl_fd);
379 channel_close_fd(&c->rfd);
380 channel_close_fd(&c->wfd);
381 channel_close_fd(&c->efd);
384 /* Free the channel and close its fd/socket. */
386 channel_free(Channel *c)
390 struct channel_confirm *cc;
392 for (n = 0, i = 0; i < channels_alloc; i++)
395 debug("channel %d: free: %s, nchannels %u", c->self,
396 c->remote_name ? c->remote_name : "???", n);
398 s = channel_open_message();
399 debug3("channel %d: status: %s", c->self, s);
403 shutdown(c->sock, SHUT_RDWR);
405 shutdown(c->ctl_fd, SHUT_RDWR);
406 channel_close_fds(c);
407 buffer_free(&c->input);
408 buffer_free(&c->output);
409 buffer_free(&c->extended);
410 if (c->remote_name) {
411 xfree(c->remote_name);
412 c->remote_name = NULL;
414 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
415 if (cc->abandon_cb != NULL)
416 cc->abandon_cb(c, cc->ctx);
417 TAILQ_REMOVE(&c->status_confirms, cc, entry);
418 bzero(cc, sizeof(*cc));
421 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
422 c->filter_cleanup(c->self, c->filter_ctx);
423 channels[c->self] = NULL;
428 channel_free_all(void)
432 for (i = 0; i < channels_alloc; i++)
433 if (channels[i] != NULL)
434 channel_free(channels[i]);
438 * Closes the sockets/fds of all channels. This is used to close extra file
439 * descriptors after a fork.
442 channel_close_all(void)
446 for (i = 0; i < channels_alloc; i++)
447 if (channels[i] != NULL)
448 channel_close_fds(channels[i]);
452 * Stop listening to channels.
455 channel_stop_listening(void)
460 for (i = 0; i < channels_alloc; i++) {
464 case SSH_CHANNEL_AUTH_SOCKET:
465 case SSH_CHANNEL_PORT_LISTENER:
466 case SSH_CHANNEL_RPORT_LISTENER:
467 case SSH_CHANNEL_X11_LISTENER:
468 channel_close_fd(&c->sock);
477 * Returns true if no channel has too much buffered data, and false if one or
478 * more channel is overfull.
481 channel_not_very_much_buffered_data(void)
486 for (i = 0; i < channels_alloc; i++) {
488 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
491 buffer_len(&c->input) > packet_get_maxsize()) {
492 debug2("channel %d: big input buffer %d",
493 c->self, buffer_len(&c->input));
497 if (buffer_len(&c->output) > packet_get_maxsize()) {
498 debug2("channel %d: big output buffer %u > %u",
499 c->self, buffer_len(&c->output),
500 packet_get_maxsize());
508 /* Returns true if any channel is still open. */
510 channel_still_open(void)
515 for (i = 0; i < channels_alloc; i++) {
520 case SSH_CHANNEL_X11_LISTENER:
521 case SSH_CHANNEL_PORT_LISTENER:
522 case SSH_CHANNEL_RPORT_LISTENER:
523 case SSH_CHANNEL_CLOSED:
524 case SSH_CHANNEL_AUTH_SOCKET:
525 case SSH_CHANNEL_DYNAMIC:
526 case SSH_CHANNEL_CONNECTING:
527 case SSH_CHANNEL_ZOMBIE:
529 case SSH_CHANNEL_LARVAL:
531 fatal("cannot happen: SSH_CHANNEL_LARVAL");
533 case SSH_CHANNEL_OPENING:
534 case SSH_CHANNEL_OPEN:
535 case SSH_CHANNEL_X11_OPEN:
537 case SSH_CHANNEL_INPUT_DRAINING:
538 case SSH_CHANNEL_OUTPUT_DRAINING:
540 fatal("cannot happen: OUT_DRAIN");
543 fatal("channel_still_open: bad channel type %d", c->type);
550 /* Returns the id of an open channel suitable for keepaliving */
552 channel_find_open(void)
557 for (i = 0; i < channels_alloc; i++) {
559 if (c == NULL || c->remote_id < 0)
562 case SSH_CHANNEL_CLOSED:
563 case SSH_CHANNEL_DYNAMIC:
564 case SSH_CHANNEL_X11_LISTENER:
565 case SSH_CHANNEL_PORT_LISTENER:
566 case SSH_CHANNEL_RPORT_LISTENER:
567 case SSH_CHANNEL_OPENING:
568 case SSH_CHANNEL_CONNECTING:
569 case SSH_CHANNEL_ZOMBIE:
571 case SSH_CHANNEL_LARVAL:
572 case SSH_CHANNEL_AUTH_SOCKET:
573 case SSH_CHANNEL_OPEN:
574 case SSH_CHANNEL_X11_OPEN:
576 case SSH_CHANNEL_INPUT_DRAINING:
577 case SSH_CHANNEL_OUTPUT_DRAINING:
579 fatal("cannot happen: OUT_DRAIN");
582 fatal("channel_find_open: bad channel type %d", c->type);
591 * Returns a message describing the currently open forwarded connections,
592 * suitable for sending to the client. The message contains crlf pairs for
596 channel_open_message(void)
603 buffer_init(&buffer);
604 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
605 buffer_append(&buffer, buf, strlen(buf));
606 for (i = 0; i < channels_alloc; i++) {
611 case SSH_CHANNEL_X11_LISTENER:
612 case SSH_CHANNEL_PORT_LISTENER:
613 case SSH_CHANNEL_RPORT_LISTENER:
614 case SSH_CHANNEL_CLOSED:
615 case SSH_CHANNEL_AUTH_SOCKET:
616 case SSH_CHANNEL_ZOMBIE:
618 case SSH_CHANNEL_LARVAL:
619 case SSH_CHANNEL_OPENING:
620 case SSH_CHANNEL_CONNECTING:
621 case SSH_CHANNEL_DYNAMIC:
622 case SSH_CHANNEL_OPEN:
623 case SSH_CHANNEL_X11_OPEN:
624 case SSH_CHANNEL_INPUT_DRAINING:
625 case SSH_CHANNEL_OUTPUT_DRAINING:
626 snprintf(buf, sizeof buf,
627 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
628 c->self, c->remote_name,
629 c->type, c->remote_id,
630 c->istate, buffer_len(&c->input),
631 c->ostate, buffer_len(&c->output),
632 c->rfd, c->wfd, c->ctl_fd);
633 buffer_append(&buffer, buf, strlen(buf));
636 fatal("channel_open_message: bad channel type %d", c->type);
640 buffer_append(&buffer, "\0", 1);
641 cp = xstrdup(buffer_ptr(&buffer));
642 buffer_free(&buffer);
647 channel_send_open(int id)
649 Channel *c = channel_lookup(id);
652 logit("channel_send_open: %d: bad id", id);
655 debug2("channel %d: send open", id);
656 packet_start(SSH2_MSG_CHANNEL_OPEN);
657 packet_put_cstring(c->ctype);
658 packet_put_int(c->self);
659 packet_put_int(c->local_window);
660 packet_put_int(c->local_maxpacket);
665 channel_request_start(int id, char *service, int wantconfirm)
667 Channel *c = channel_lookup(id);
670 logit("channel_request_start: %d: unknown channel id", id);
673 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
674 packet_start(SSH2_MSG_CHANNEL_REQUEST);
675 packet_put_int(c->remote_id);
676 packet_put_cstring(service);
677 packet_put_char(wantconfirm);
681 channel_register_status_confirm(int id, channel_confirm_cb *cb,
682 channel_confirm_abandon_cb *abandon_cb, void *ctx)
684 struct channel_confirm *cc;
687 if ((c = channel_lookup(id)) == NULL)
688 fatal("channel_register_expect: %d: bad id", id);
690 cc = xmalloc(sizeof(*cc));
692 cc->abandon_cb = abandon_cb;
694 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
698 channel_register_open_confirm(int id, channel_callback_fn *fn, void *ctx)
700 Channel *c = channel_lookup(id);
703 logit("channel_register_open_comfirm: %d: bad id", id);
706 c->open_confirm = fn;
707 c->open_confirm_ctx = ctx;
711 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
713 Channel *c = channel_by_id(id);
716 logit("channel_register_cleanup: %d: bad id", id);
720 c->detach_close = do_close;
724 channel_cancel_cleanup(int id)
726 Channel *c = channel_by_id(id);
729 logit("channel_cancel_cleanup: %d: bad id", id);
732 c->detach_user = NULL;
737 channel_register_filter(int id, channel_infilter_fn *ifn,
738 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
740 Channel *c = channel_lookup(id);
743 logit("channel_register_filter: %d: bad id", id);
746 c->input_filter = ifn;
747 c->output_filter = ofn;
749 c->filter_cleanup = cfn;
753 channel_set_fds(int id, int rfd, int wfd, int efd,
754 int extusage, int nonblock, u_int window_max)
756 Channel *c = channel_lookup(id);
758 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
759 fatal("channel_activate for non-larval channel %d.", id);
760 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock);
761 c->type = SSH_CHANNEL_OPEN;
762 c->local_window = c->local_window_max = window_max;
763 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
764 packet_put_int(c->remote_id);
765 packet_put_int(c->local_window);
770 * 'channel_pre*' are called just before select() to add any bits relevant to
771 * channels in the select bitmasks.
774 * 'channel_post*': perform any appropriate operations for channels which
775 * have events pending.
777 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
778 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
779 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
783 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
785 FD_SET(c->sock, readset);
790 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
792 debug3("channel %d: waiting for connection", c->self);
793 FD_SET(c->sock, writeset);
797 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
799 if (buffer_len(&c->input) < packet_get_maxsize())
800 FD_SET(c->sock, readset);
801 if (buffer_len(&c->output) > 0)
802 FD_SET(c->sock, writeset);
806 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
808 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
810 if (c->istate == CHAN_INPUT_OPEN &&
812 buffer_len(&c->input) < limit &&
813 buffer_check_alloc(&c->input, CHAN_RBUF))
814 FD_SET(c->rfd, readset);
815 if (c->ostate == CHAN_OUTPUT_OPEN ||
816 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
817 if (buffer_len(&c->output) > 0) {
818 FD_SET(c->wfd, writeset);
819 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
820 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
821 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
822 c->self, c->efd, buffer_len(&c->extended));
827 /** XXX check close conditions, too */
828 if (compat20 && c->efd != -1 &&
829 !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
830 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
831 buffer_len(&c->extended) > 0)
832 FD_SET(c->efd, writeset);
833 else if (!(c->flags & CHAN_EOF_SENT) &&
834 c->extended_usage == CHAN_EXTENDED_READ &&
835 buffer_len(&c->extended) < c->remote_window)
836 FD_SET(c->efd, readset);
838 /* XXX: What about efd? races? */
839 if (compat20 && c->ctl_fd != -1 &&
840 c->istate == CHAN_INPUT_OPEN && c->ostate == CHAN_OUTPUT_OPEN)
841 FD_SET(c->ctl_fd, readset);
846 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
848 if (buffer_len(&c->input) == 0) {
849 packet_start(SSH_MSG_CHANNEL_CLOSE);
850 packet_put_int(c->remote_id);
852 c->type = SSH_CHANNEL_CLOSED;
853 debug2("channel %d: closing after input drain.", c->self);
859 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
861 if (buffer_len(&c->output) == 0)
864 FD_SET(c->sock, writeset);
868 * This is a special state for X11 authentication spoofing. An opened X11
869 * connection (when authentication spoofing is being done) remains in this
870 * state until the first packet has been completely read. The authentication
871 * data in that packet is then substituted by the real data if it matches the
872 * fake data, and the channel is put into normal mode.
873 * XXX All this happens at the client side.
874 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
877 x11_open_helper(Buffer *b)
880 u_int proto_len, data_len;
882 /* Check if the fixed size part of the packet is in buffer. */
883 if (buffer_len(b) < 12)
886 /* Parse the lengths of variable-length fields. */
888 if (ucp[0] == 0x42) { /* Byte order MSB first. */
889 proto_len = 256 * ucp[6] + ucp[7];
890 data_len = 256 * ucp[8] + ucp[9];
891 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
892 proto_len = ucp[6] + 256 * ucp[7];
893 data_len = ucp[8] + 256 * ucp[9];
895 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
900 /* Check if the whole packet is in buffer. */
902 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
905 /* Check if authentication protocol matches. */
906 if (proto_len != strlen(x11_saved_proto) ||
907 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
908 debug2("X11 connection uses different authentication protocol.");
911 /* Check if authentication data matches our fake data. */
912 if (data_len != x11_fake_data_len ||
913 memcmp(ucp + 12 + ((proto_len + 3) & ~3),
914 x11_fake_data, x11_fake_data_len) != 0) {
915 debug2("X11 auth data does not match fake data.");
918 /* Check fake data length */
919 if (x11_fake_data_len != x11_saved_data_len) {
920 error("X11 fake_data_len %d != saved_data_len %d",
921 x11_fake_data_len, x11_saved_data_len);
925 * Received authentication protocol and data match
926 * our fake data. Substitute the fake data with real
929 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
930 x11_saved_data, x11_saved_data_len);
935 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
937 int ret = x11_open_helper(&c->output);
940 /* Start normal processing for the channel. */
941 c->type = SSH_CHANNEL_OPEN;
942 channel_pre_open_13(c, readset, writeset);
943 } else if (ret == -1) {
945 * We have received an X11 connection that has bad
946 * authentication information.
948 logit("X11 connection rejected because of wrong authentication.");
949 buffer_clear(&c->input);
950 buffer_clear(&c->output);
951 channel_close_fd(&c->sock);
953 c->type = SSH_CHANNEL_CLOSED;
954 packet_start(SSH_MSG_CHANNEL_CLOSE);
955 packet_put_int(c->remote_id);
961 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
963 int ret = x11_open_helper(&c->output);
965 /* c->force_drain = 1; */
968 c->type = SSH_CHANNEL_OPEN;
969 channel_pre_open(c, readset, writeset);
970 } else if (ret == -1) {
971 logit("X11 connection rejected because of wrong authentication.");
972 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
974 buffer_clear(&c->input);
976 buffer_clear(&c->output);
977 /* for proto v1, the peer will send an IEOF */
979 chan_write_failed(c);
981 c->type = SSH_CHANNEL_OPEN;
982 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
986 /* try to decode a socks4 header */
989 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
992 u_int len, have, i, found;
998 struct in_addr dest_addr;
1001 debug2("channel %d: decode socks4", c->self);
1003 have = buffer_len(&c->input);
1004 len = sizeof(s4_req);
1007 p = buffer_ptr(&c->input);
1008 for (found = 0, i = len; i < have; i++) {
1014 /* the peer is probably sending garbage */
1015 debug("channel %d: decode socks4: too long",
1022 buffer_get(&c->input, (char *)&s4_req.version, 1);
1023 buffer_get(&c->input, (char *)&s4_req.command, 1);
1024 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1025 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1026 have = buffer_len(&c->input);
1027 p = buffer_ptr(&c->input);
1029 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1031 fatal("channel %d: decode socks4: len %d > have %d",
1032 c->self, len, have);
1033 strlcpy(username, p, sizeof(username));
1034 buffer_consume(&c->input, len);
1035 buffer_consume(&c->input, 1); /* trailing '\0' */
1037 host = inet_ntoa(s4_req.dest_addr);
1038 strlcpy(c->path, host, sizeof(c->path));
1039 c->host_port = ntohs(s4_req.dest_port);
1041 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1042 c->self, host, c->host_port, s4_req.command);
1044 if (s4_req.command != 1) {
1045 debug("channel %d: cannot handle: socks4 cn %d",
1046 c->self, s4_req.command);
1049 s4_rsp.version = 0; /* vn: 0 for reply */
1050 s4_rsp.command = 90; /* cd: req granted */
1051 s4_rsp.dest_port = 0; /* ignored */
1052 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1053 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1057 /* try to decode a socks5 header */
1058 #define SSH_SOCKS5_AUTHDONE 0x1000
1059 #define SSH_SOCKS5_NOAUTH 0x00
1060 #define SSH_SOCKS5_IPV4 0x01
1061 #define SSH_SOCKS5_DOMAIN 0x03
1062 #define SSH_SOCKS5_IPV6 0x04
1063 #define SSH_SOCKS5_CONNECT 0x01
1064 #define SSH_SOCKS5_SUCCESS 0x00
1068 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1076 u_int16_t dest_port;
1077 u_char *p, dest_addr[255+1];
1078 u_int have, need, i, found, nmethods, addrlen, af;
1080 debug2("channel %d: decode socks5", c->self);
1081 p = buffer_ptr(&c->input);
1084 have = buffer_len(&c->input);
1085 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1086 /* format: ver | nmethods | methods */
1090 if (have < nmethods + 2)
1092 /* look for method: "NO AUTHENTICATION REQUIRED" */
1093 for (found = 0, i = 2; i < nmethods + 2; i++) {
1094 if (p[i] == SSH_SOCKS5_NOAUTH) {
1100 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1104 buffer_consume(&c->input, nmethods + 2);
1105 buffer_put_char(&c->output, 0x05); /* version */
1106 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1107 FD_SET(c->sock, writeset);
1108 c->flags |= SSH_SOCKS5_AUTHDONE;
1109 debug2("channel %d: socks5 auth done", c->self);
1110 return 0; /* need more */
1112 debug2("channel %d: socks5 post auth", c->self);
1113 if (have < sizeof(s5_req)+1)
1114 return 0; /* need more */
1115 memcpy(&s5_req, p, sizeof(s5_req));
1116 if (s5_req.version != 0x05 ||
1117 s5_req.command != SSH_SOCKS5_CONNECT ||
1118 s5_req.reserved != 0x00) {
1119 debug2("channel %d: only socks5 connect supported", c->self);
1122 switch (s5_req.atyp){
1123 case SSH_SOCKS5_IPV4:
1127 case SSH_SOCKS5_DOMAIN:
1128 addrlen = p[sizeof(s5_req)];
1131 case SSH_SOCKS5_IPV6:
1136 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1139 need = sizeof(s5_req) + addrlen + 2;
1140 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1144 buffer_consume(&c->input, sizeof(s5_req));
1145 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1146 buffer_consume(&c->input, 1); /* host string length */
1147 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1148 buffer_get(&c->input, (char *)&dest_port, 2);
1149 dest_addr[addrlen] = '\0';
1150 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1151 strlcpy(c->path, (char *)dest_addr, sizeof(c->path));
1152 else if (inet_ntop(af, dest_addr, c->path, sizeof(c->path)) == NULL)
1154 c->host_port = ntohs(dest_port);
1156 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1157 c->self, c->path, c->host_port, s5_req.command);
1159 s5_rsp.version = 0x05;
1160 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1161 s5_rsp.reserved = 0; /* ignored */
1162 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1163 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1164 dest_port = 0; /* ignored */
1166 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1167 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1168 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1172 /* dynamic port forwarding */
1174 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1180 have = buffer_len(&c->input);
1182 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1183 /* buffer_dump(&c->input); */
1184 /* check if the fixed size part of the packet is in buffer. */
1187 FD_SET(c->sock, readset);
1190 /* try to guess the protocol */
1191 p = buffer_ptr(&c->input);
1194 ret = channel_decode_socks4(c, readset, writeset);
1197 ret = channel_decode_socks5(c, readset, writeset);
1205 } else if (ret == 0) {
1206 debug2("channel %d: pre_dynamic: need more", c->self);
1208 FD_SET(c->sock, readset);
1210 /* switch to the next state */
1211 c->type = SSH_CHANNEL_OPENING;
1212 port_open_helper(c, "direct-tcpip");
1216 /* This is our fake X11 server socket. */
1219 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1222 struct sockaddr addr;
1225 char buf[16384], *remote_ipaddr;
1228 if (FD_ISSET(c->sock, readset)) {
1229 debug("X11 connection requested.");
1230 addrlen = sizeof(addr);
1231 newsock = accept(c->sock, &addr, &addrlen);
1232 if (c->single_connection) {
1233 debug2("single_connection: closing X11 listener.");
1234 channel_close_fd(&c->sock);
1238 error("accept: %.100s", strerror(errno));
1241 set_nodelay(newsock);
1242 remote_ipaddr = get_peer_ipaddr(newsock);
1243 remote_port = get_peer_port(newsock);
1244 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1245 remote_ipaddr, remote_port);
1247 nc = channel_new("accepted x11 socket",
1248 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1249 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1251 packet_start(SSH2_MSG_CHANNEL_OPEN);
1252 packet_put_cstring("x11");
1253 packet_put_int(nc->self);
1254 packet_put_int(nc->local_window_max);
1255 packet_put_int(nc->local_maxpacket);
1256 /* originator ipaddr and port */
1257 packet_put_cstring(remote_ipaddr);
1258 if (datafellows & SSH_BUG_X11FWD) {
1259 debug2("ssh2 x11 bug compat mode");
1261 packet_put_int(remote_port);
1265 packet_start(SSH_SMSG_X11_OPEN);
1266 packet_put_int(nc->self);
1267 if (packet_get_protocol_flags() &
1268 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1269 packet_put_cstring(buf);
1272 xfree(remote_ipaddr);
1277 port_open_helper(Channel *c, char *rtype)
1281 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1282 int remote_port = get_peer_port(c->sock);
1284 direct = (strcmp(rtype, "direct-tcpip") == 0);
1286 snprintf(buf, sizeof buf,
1287 "%s: listening port %d for %.100s port %d, "
1288 "connect from %.200s port %d",
1289 rtype, c->listening_port, c->path, c->host_port,
1290 remote_ipaddr, remote_port);
1292 xfree(c->remote_name);
1293 c->remote_name = xstrdup(buf);
1296 packet_start(SSH2_MSG_CHANNEL_OPEN);
1297 packet_put_cstring(rtype);
1298 packet_put_int(c->self);
1299 packet_put_int(c->local_window_max);
1300 packet_put_int(c->local_maxpacket);
1302 /* target host, port */
1303 packet_put_cstring(c->path);
1304 packet_put_int(c->host_port);
1306 /* listen address, port */
1307 packet_put_cstring(c->path);
1308 packet_put_int(c->listening_port);
1310 /* originator host and port */
1311 packet_put_cstring(remote_ipaddr);
1312 packet_put_int((u_int)remote_port);
1315 packet_start(SSH_MSG_PORT_OPEN);
1316 packet_put_int(c->self);
1317 packet_put_cstring(c->path);
1318 packet_put_int(c->host_port);
1319 if (packet_get_protocol_flags() &
1320 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1321 packet_put_cstring(c->remote_name);
1324 xfree(remote_ipaddr);
1328 channel_set_reuseaddr(int fd)
1333 * Set socket options.
1334 * Allow local port reuse in TIME_WAIT.
1336 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1337 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1341 * This socket is listening for connections to a forwarded TCP/IP port.
1345 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1348 struct sockaddr addr;
1349 int newsock, nextstate;
1353 if (FD_ISSET(c->sock, readset)) {
1354 debug("Connection to port %d forwarding "
1355 "to %.100s port %d requested.",
1356 c->listening_port, c->path, c->host_port);
1358 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1359 nextstate = SSH_CHANNEL_OPENING;
1360 rtype = "forwarded-tcpip";
1362 if (c->host_port == 0) {
1363 nextstate = SSH_CHANNEL_DYNAMIC;
1364 rtype = "dynamic-tcpip";
1366 nextstate = SSH_CHANNEL_OPENING;
1367 rtype = "direct-tcpip";
1371 addrlen = sizeof(addr);
1372 newsock = accept(c->sock, &addr, &addrlen);
1374 error("accept: %.100s", strerror(errno));
1377 set_nodelay(newsock);
1378 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1379 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1380 nc->listening_port = c->listening_port;
1381 nc->host_port = c->host_port;
1382 strlcpy(nc->path, c->path, sizeof(nc->path));
1384 if (nextstate == SSH_CHANNEL_DYNAMIC) {
1386 * do not call the channel_post handler until
1387 * this flag has been reset by a pre-handler.
1388 * otherwise the FD_ISSET calls might overflow
1392 port_open_helper(nc, rtype);
1398 * This is the authentication agent socket listening for connections from
1403 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1407 struct sockaddr addr;
1410 if (FD_ISSET(c->sock, readset)) {
1411 addrlen = sizeof(addr);
1412 newsock = accept(c->sock, &addr, &addrlen);
1414 error("accept from auth socket: %.100s", strerror(errno));
1417 nc = channel_new("accepted auth socket",
1418 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1419 c->local_window_max, c->local_maxpacket,
1420 0, "accepted auth socket", 1);
1422 packet_start(SSH2_MSG_CHANNEL_OPEN);
1423 packet_put_cstring("auth-agent@openssh.com");
1424 packet_put_int(nc->self);
1425 packet_put_int(c->local_window_max);
1426 packet_put_int(c->local_maxpacket);
1428 packet_start(SSH_SMSG_AGENT_OPEN);
1429 packet_put_int(nc->self);
1437 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1440 socklen_t sz = sizeof(err);
1442 if (FD_ISSET(c->sock, writeset)) {
1443 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1445 error("getsockopt SO_ERROR failed");
1448 debug("channel %d: connected to %s port %d",
1449 c->self, c->connect_ctx.host, c->connect_ctx.port);
1450 channel_connect_ctx_free(&c->connect_ctx);
1451 c->type = SSH_CHANNEL_OPEN;
1453 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1454 packet_put_int(c->remote_id);
1455 packet_put_int(c->self);
1456 packet_put_int(c->local_window);
1457 packet_put_int(c->local_maxpacket);
1459 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1460 packet_put_int(c->remote_id);
1461 packet_put_int(c->self);
1464 debug("channel %d: connection failed: %s",
1465 c->self, strerror(err));
1466 /* Try next address, if any */
1467 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1469 c->sock = c->rfd = c->wfd = sock;
1470 channel_max_fd = channel_find_maxfd();
1473 /* Exhausted all addresses */
1474 error("connect_to %.100s port %d: failed.",
1475 c->connect_ctx.host, c->connect_ctx.port);
1476 channel_connect_ctx_free(&c->connect_ctx);
1478 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1479 packet_put_int(c->remote_id);
1480 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1481 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1482 packet_put_cstring(strerror(err));
1483 packet_put_cstring("");
1486 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1487 packet_put_int(c->remote_id);
1497 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1499 char buf[CHAN_RBUF];
1502 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1503 if (c->rfd != -1 && (force || FD_ISSET(c->rfd, readset))) {
1505 len = read(c->rfd, buf, sizeof(buf));
1506 if (len < 0 && (errno == EINTR || (errno == EAGAIN && !force)))
1508 #ifndef PTY_ZEROREAD
1511 if ((!c->isatty && len <= 0) ||
1512 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1514 debug2("channel %d: read<=0 rfd %d len %d",
1515 c->self, c->rfd, len);
1516 if (c->type != SSH_CHANNEL_OPEN) {
1517 debug2("channel %d: not open", c->self);
1520 } else if (compat13) {
1521 buffer_clear(&c->output);
1522 c->type = SSH_CHANNEL_INPUT_DRAINING;
1523 debug2("channel %d: input draining.", c->self);
1525 chan_read_failed(c);
1529 if (c->input_filter != NULL) {
1530 if (c->input_filter(c, buf, len) == -1) {
1531 debug2("channel %d: filter stops", c->self);
1532 chan_read_failed(c);
1534 } else if (c->datagram) {
1535 buffer_put_string(&c->input, buf, len);
1537 buffer_append(&c->input, buf, len);
1545 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1548 u_char *data = NULL, *buf;
1552 /* Send buffered output data to the socket. */
1554 FD_ISSET(c->wfd, writeset) &&
1555 buffer_len(&c->output) > 0) {
1556 if (c->output_filter != NULL) {
1557 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1558 debug2("channel %d: filter stops", c->self);
1559 if (c->type != SSH_CHANNEL_OPEN)
1562 chan_write_failed(c);
1565 } else if (c->datagram) {
1566 buf = data = buffer_get_string(&c->output, &dlen);
1568 buf = data = buffer_ptr(&c->output);
1569 dlen = buffer_len(&c->output);
1573 /* ignore truncated writes, datagrams might get lost */
1574 c->local_consumed += dlen + 4;
1575 len = write(c->wfd, buf, dlen);
1577 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1580 if (c->type != SSH_CHANNEL_OPEN)
1583 chan_write_failed(c);
1589 /* XXX: Later AIX versions can't push as much data to tty */
1590 if (compat20 && c->wfd_isatty)
1591 dlen = MIN(dlen, 8*1024);
1594 len = write(c->wfd, buf, dlen);
1595 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1598 if (c->type != SSH_CHANNEL_OPEN) {
1599 debug2("channel %d: not open", c->self);
1602 } else if (compat13) {
1603 buffer_clear(&c->output);
1604 debug2("channel %d: input draining.", c->self);
1605 c->type = SSH_CHANNEL_INPUT_DRAINING;
1607 chan_write_failed(c);
1611 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1612 if (tcgetattr(c->wfd, &tio) == 0 &&
1613 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1615 * Simulate echo to reduce the impact of
1616 * traffic analysis. We need to match the
1617 * size of a SSH2_MSG_CHANNEL_DATA message
1618 * (4 byte channel id + buf)
1620 packet_send_ignore(4 + len);
1624 buffer_consume(&c->output, len);
1625 if (compat20 && len > 0) {
1626 c->local_consumed += len;
1633 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1635 char buf[CHAN_RBUF];
1638 /** XXX handle drain efd, too */
1640 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1641 FD_ISSET(c->efd, writeset) &&
1642 buffer_len(&c->extended) > 0) {
1643 len = write(c->efd, buffer_ptr(&c->extended),
1644 buffer_len(&c->extended));
1645 debug2("channel %d: written %d to efd %d",
1646 c->self, len, c->efd);
1647 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1650 debug2("channel %d: closing write-efd %d",
1652 channel_close_fd(&c->efd);
1654 buffer_consume(&c->extended, len);
1655 c->local_consumed += len;
1657 } else if (c->extended_usage == CHAN_EXTENDED_READ &&
1658 (c->detach_close || FD_ISSET(c->efd, readset))) {
1659 len = read(c->efd, buf, sizeof(buf));
1660 debug2("channel %d: read %d from efd %d",
1661 c->self, len, c->efd);
1662 if (len < 0 && (errno == EINTR ||
1663 (errno == EAGAIN && !c->detach_close)))
1666 debug2("channel %d: closing read-efd %d",
1668 channel_close_fd(&c->efd);
1670 buffer_append(&c->extended, buf, len);
1679 channel_handle_ctl(Channel *c, fd_set *readset, fd_set *writeset)
1684 /* Monitor control fd to detect if the slave client exits */
1685 if (c->ctl_fd != -1 && FD_ISSET(c->ctl_fd, readset)) {
1686 len = read(c->ctl_fd, buf, sizeof(buf));
1687 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1690 debug2("channel %d: ctl read<=0", c->self);
1691 if (c->type != SSH_CHANNEL_OPEN) {
1692 debug2("channel %d: not open", c->self);
1696 chan_read_failed(c);
1697 chan_write_failed(c);
1701 fatal("%s: unexpected data on ctl fd", __func__);
1707 channel_check_window(Channel *c)
1709 if (c->type == SSH_CHANNEL_OPEN &&
1710 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1711 ((c->local_window_max - c->local_window >
1712 c->local_maxpacket*3) ||
1713 c->local_window < c->local_window_max/2) &&
1714 c->local_consumed > 0) {
1715 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1716 packet_put_int(c->remote_id);
1717 packet_put_int(c->local_consumed);
1719 debug2("channel %d: window %d sent adjust %d",
1720 c->self, c->local_window,
1722 c->local_window += c->local_consumed;
1723 c->local_consumed = 0;
1729 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1733 channel_handle_rfd(c, readset, writeset);
1734 channel_handle_wfd(c, readset, writeset);
1737 channel_handle_efd(c, readset, writeset);
1738 channel_handle_ctl(c, readset, writeset);
1739 channel_check_window(c);
1744 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
1748 /* Send buffered output data to the socket. */
1749 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
1750 len = write(c->sock, buffer_ptr(&c->output),
1751 buffer_len(&c->output));
1753 buffer_clear(&c->output);
1755 buffer_consume(&c->output, len);
1760 channel_handler_init_20(void)
1762 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1763 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1764 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1765 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
1766 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1767 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1768 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1769 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1771 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1772 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1773 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
1774 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1775 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1776 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1777 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1781 channel_handler_init_13(void)
1783 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
1784 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
1785 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1786 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1787 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1788 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
1789 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
1790 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1791 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1793 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1794 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1795 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1796 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1797 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
1798 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1799 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1803 channel_handler_init_15(void)
1805 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
1806 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
1807 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
1808 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
1809 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
1810 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
1811 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
1813 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
1814 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
1815 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
1816 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
1817 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
1818 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
1822 channel_handler_init(void)
1826 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
1827 channel_pre[i] = NULL;
1828 channel_post[i] = NULL;
1831 channel_handler_init_20();
1833 channel_handler_init_13();
1835 channel_handler_init_15();
1838 /* gc dead channels */
1840 channel_garbage_collect(Channel *c)
1844 if (c->detach_user != NULL) {
1845 if (!chan_is_dead(c, c->detach_close))
1847 debug2("channel %d: gc: notify user", c->self);
1848 c->detach_user(c->self, NULL);
1849 /* if we still have a callback */
1850 if (c->detach_user != NULL)
1852 debug2("channel %d: gc: user detached", c->self);
1854 if (!chan_is_dead(c, 1))
1856 debug2("channel %d: garbage collecting", c->self);
1861 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset)
1863 static int did_init = 0;
1868 channel_handler_init();
1871 for (i = 0; i < channels_alloc; i++) {
1875 if (ftab[c->type] != NULL)
1876 (*ftab[c->type])(c, readset, writeset);
1877 channel_garbage_collect(c);
1882 * Allocate/update select bitmasks and add any bits relevant to channels in
1886 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
1887 u_int *nallocp, int rekeying)
1889 u_int n, sz, nfdset;
1891 n = MAX(*maxfdp, channel_max_fd);
1893 nfdset = howmany(n+1, NFDBITS);
1894 /* Explicitly test here, because xrealloc isn't always called */
1895 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
1896 fatal("channel_prepare_select: max_fd (%d) is too large", n);
1897 sz = nfdset * sizeof(fd_mask);
1899 /* perhaps check sz < nalloc/2 and shrink? */
1900 if (*readsetp == NULL || sz > *nallocp) {
1901 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
1902 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
1906 memset(*readsetp, 0, sz);
1907 memset(*writesetp, 0, sz);
1910 channel_handler(channel_pre, *readsetp, *writesetp);
1914 * After select, perform any appropriate operations for channels which have
1918 channel_after_select(fd_set *readset, fd_set *writeset)
1920 channel_handler(channel_post, readset, writeset);
1924 /* If there is data to send to the connection, enqueue some of it now. */
1926 channel_output_poll(void)
1931 for (i = 0; i < channels_alloc; i++) {
1937 * We are only interested in channels that can have buffered
1941 if (c->type != SSH_CHANNEL_OPEN &&
1942 c->type != SSH_CHANNEL_INPUT_DRAINING)
1945 if (c->type != SSH_CHANNEL_OPEN)
1949 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
1950 /* XXX is this true? */
1951 debug3("channel %d: will not send data after close", c->self);
1955 /* Get the amount of buffered data for this channel. */
1956 if ((c->istate == CHAN_INPUT_OPEN ||
1957 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
1958 (len = buffer_len(&c->input)) > 0) {
1964 data = buffer_get_string(&c->input,
1966 packet_start(SSH2_MSG_CHANNEL_DATA);
1967 packet_put_int(c->remote_id);
1968 packet_put_string(data, dlen);
1970 c->remote_window -= dlen + 4;
1976 * Send some data for the other side over the secure
1980 if (len > c->remote_window)
1981 len = c->remote_window;
1982 if (len > c->remote_maxpacket)
1983 len = c->remote_maxpacket;
1985 if (packet_is_interactive()) {
1989 /* Keep the packets at reasonable size. */
1990 if (len > packet_get_maxsize()/2)
1991 len = packet_get_maxsize()/2;
1995 packet_start(compat20 ?
1996 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
1997 packet_put_int(c->remote_id);
1998 packet_put_string(buffer_ptr(&c->input), len);
2000 buffer_consume(&c->input, len);
2001 c->remote_window -= len;
2003 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2005 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2007 * input-buffer is empty and read-socket shutdown:
2008 * tell peer, that we will not send more data: send IEOF.
2009 * hack for extended data: delay EOF if EFD still in use.
2011 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2012 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2013 c->self, c->efd, buffer_len(&c->extended));
2017 /* Send extended data, i.e. stderr */
2019 !(c->flags & CHAN_EOF_SENT) &&
2020 c->remote_window > 0 &&
2021 (len = buffer_len(&c->extended)) > 0 &&
2022 c->extended_usage == CHAN_EXTENDED_READ) {
2023 debug2("channel %d: rwin %u elen %u euse %d",
2024 c->self, c->remote_window, buffer_len(&c->extended),
2026 if (len > c->remote_window)
2027 len = c->remote_window;
2028 if (len > c->remote_maxpacket)
2029 len = c->remote_maxpacket;
2030 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
2031 packet_put_int(c->remote_id);
2032 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
2033 packet_put_string(buffer_ptr(&c->extended), len);
2035 buffer_consume(&c->extended, len);
2036 c->remote_window -= len;
2037 debug2("channel %d: sent ext data %d", c->self, len);
2043 /* -- protocol input */
2047 channel_input_data(int type, u_int32_t seq, void *ctxt)
2054 /* Get the channel number and verify it. */
2055 id = packet_get_int();
2056 c = channel_lookup(id);
2058 packet_disconnect("Received data for nonexistent channel %d.", id);
2060 /* Ignore any data for non-open channels (might happen on close) */
2061 if (c->type != SSH_CHANNEL_OPEN &&
2062 c->type != SSH_CHANNEL_X11_OPEN)
2066 data = packet_get_string_ptr(&data_len);
2069 * Ignore data for protocol > 1.3 if output end is no longer open.
2070 * For protocol 2 the sending side is reducing its window as it sends
2071 * data, so we must 'fake' consumption of the data in order to ensure
2072 * that window updates are sent back. Otherwise the connection might
2075 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2077 c->local_window -= data_len;
2078 c->local_consumed += data_len;
2084 if (data_len > c->local_maxpacket) {
2085 logit("channel %d: rcvd big packet %d, maxpack %d",
2086 c->self, data_len, c->local_maxpacket);
2088 if (data_len > c->local_window) {
2089 logit("channel %d: rcvd too much data %d, win %d",
2090 c->self, data_len, c->local_window);
2093 c->local_window -= data_len;
2096 buffer_put_string(&c->output, data, data_len);
2098 buffer_append(&c->output, data, data_len);
2104 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2108 u_int data_len, tcode;
2111 /* Get the channel number and verify it. */
2112 id = packet_get_int();
2113 c = channel_lookup(id);
2116 packet_disconnect("Received extended_data for bad channel %d.", id);
2117 if (c->type != SSH_CHANNEL_OPEN) {
2118 logit("channel %d: ext data for non open", id);
2121 if (c->flags & CHAN_EOF_RCVD) {
2122 if (datafellows & SSH_BUG_EXTEOF)
2123 debug("channel %d: accepting ext data after eof", id);
2125 packet_disconnect("Received extended_data after EOF "
2126 "on channel %d.", id);
2128 tcode = packet_get_int();
2130 c->extended_usage != CHAN_EXTENDED_WRITE ||
2131 tcode != SSH2_EXTENDED_DATA_STDERR) {
2132 logit("channel %d: bad ext data", c->self);
2135 data = packet_get_string(&data_len);
2137 if (data_len > c->local_window) {
2138 logit("channel %d: rcvd too much extended_data %d, win %d",
2139 c->self, data_len, c->local_window);
2143 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2144 c->local_window -= data_len;
2145 buffer_append(&c->extended, data, data_len);
2151 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2156 id = packet_get_int();
2158 c = channel_lookup(id);
2160 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2163 /* XXX force input close */
2164 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2165 debug("channel %d: FORCE input drain", c->self);
2166 c->istate = CHAN_INPUT_WAIT_DRAIN;
2167 if (buffer_len(&c->input) == 0)
2175 channel_input_close(int type, u_int32_t seq, void *ctxt)
2180 id = packet_get_int();
2182 c = channel_lookup(id);
2184 packet_disconnect("Received close for nonexistent channel %d.", id);
2187 * Send a confirmation that we have closed the channel and no more
2188 * data is coming for it.
2190 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2191 packet_put_int(c->remote_id);
2195 * If the channel is in closed state, we have sent a close request,
2196 * and the other side will eventually respond with a confirmation.
2197 * Thus, we cannot free the channel here, because then there would be
2198 * no-one to receive the confirmation. The channel gets freed when
2199 * the confirmation arrives.
2201 if (c->type != SSH_CHANNEL_CLOSED) {
2203 * Not a closed channel - mark it as draining, which will
2204 * cause it to be freed later.
2206 buffer_clear(&c->input);
2207 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2211 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2214 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2216 int id = packet_get_int();
2217 Channel *c = channel_lookup(id);
2221 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2222 chan_rcvd_oclose(c);
2227 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2229 int id = packet_get_int();
2230 Channel *c = channel_lookup(id);
2234 packet_disconnect("Received close confirmation for "
2235 "out-of-range channel %d.", id);
2236 if (c->type != SSH_CHANNEL_CLOSED)
2237 packet_disconnect("Received close confirmation for "
2238 "non-closed channel %d (type %d).", id, c->type);
2244 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2249 id = packet_get_int();
2250 c = channel_lookup(id);
2252 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2253 packet_disconnect("Received open confirmation for "
2254 "non-opening channel %d.", id);
2255 remote_id = packet_get_int();
2256 /* Record the remote channel number and mark that the channel is now open. */
2257 c->remote_id = remote_id;
2258 c->type = SSH_CHANNEL_OPEN;
2261 c->remote_window = packet_get_int();
2262 c->remote_maxpacket = packet_get_int();
2263 if (c->open_confirm) {
2264 debug2("callback start");
2265 c->open_confirm(c->self, c->open_confirm_ctx);
2266 debug2("callback done");
2268 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2269 c->remote_window, c->remote_maxpacket);
2275 reason2txt(int reason)
2278 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2279 return "administratively prohibited";
2280 case SSH2_OPEN_CONNECT_FAILED:
2281 return "connect failed";
2282 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2283 return "unknown channel type";
2284 case SSH2_OPEN_RESOURCE_SHORTAGE:
2285 return "resource shortage";
2287 return "unknown reason";
2292 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2295 char *msg = NULL, *lang = NULL;
2298 id = packet_get_int();
2299 c = channel_lookup(id);
2301 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2302 packet_disconnect("Received open failure for "
2303 "non-opening channel %d.", id);
2305 reason = packet_get_int();
2306 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2307 msg = packet_get_string(NULL);
2308 lang = packet_get_string(NULL);
2310 logit("channel %d: open failed: %s%s%s", id,
2311 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2318 /* Free the channel. This will also close the socket. */
2324 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2333 /* Get the channel number and verify it. */
2334 id = packet_get_int();
2335 c = channel_lookup(id);
2338 logit("Received window adjust for non-open channel %d.", id);
2341 adjust = packet_get_int();
2343 debug2("channel %d: rcvd adjust %u", id, adjust);
2344 c->remote_window += adjust;
2349 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2353 char *host, *originator_string;
2356 remote_id = packet_get_int();
2357 host = packet_get_string(NULL);
2358 host_port = packet_get_int();
2360 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2361 originator_string = packet_get_string(NULL);
2363 originator_string = xstrdup("unknown (remote did not supply name)");
2366 c = channel_connect_to(host, host_port,
2367 "connected socket", originator_string);
2368 xfree(originator_string);
2371 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2372 packet_put_int(remote_id);
2375 c->remote_id = remote_id;
2380 channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
2383 struct channel_confirm *cc;
2386 /* Reset keepalive timeout */
2387 keep_alive_timeouts = 0;
2389 remote_id = packet_get_int();
2392 debug2("channel_input_confirm: type %d id %d", type, remote_id);
2394 if ((c = channel_lookup(remote_id)) == NULL) {
2395 logit("channel_input_success_failure: %d: unknown", remote_id);
2399 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
2401 cc->cb(type, c, cc->ctx);
2402 TAILQ_REMOVE(&c->status_confirms, cc, entry);
2403 bzero(cc, sizeof(*cc));
2407 /* -- tcp forwarding */
2410 channel_set_af(int af)
2416 channel_setup_fwd_listener(int type, const char *listen_addr, u_short listen_port,
2417 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2420 int sock, r, success = 0, wildcard = 0, is_client;
2421 struct addrinfo hints, *ai, *aitop;
2422 const char *host, *addr;
2423 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2425 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2426 listen_addr : host_to_connect;
2427 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2430 error("No forward host name.");
2433 if (strlen(host) > SSH_CHANNEL_PATH_LEN - 1) {
2434 error("Forward host name too long.");
2439 * Determine whether or not a port forward listens to loopback,
2440 * specified address or wildcard. On the client, a specified bind
2441 * address will always override gateway_ports. On the server, a
2442 * gateway_ports of 1 (``yes'') will override the client's
2443 * specification and force a wildcard bind, whereas a value of 2
2444 * (``clientspecified'') will bind to whatever address the client
2447 * Special-case listen_addrs are:
2449 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2450 * "" (empty string), "*" -> wildcard v4/v6
2451 * "localhost" -> loopback v4/v6
2454 if (listen_addr == NULL) {
2455 /* No address specified: default to gateway_ports setting */
2458 } else if (gateway_ports || is_client) {
2459 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2460 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
2461 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2462 (!is_client && gateway_ports == 1))
2464 else if (strcmp(listen_addr, "localhost") != 0)
2468 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2469 type, wildcard, (addr == NULL) ? "NULL" : addr);
2472 * getaddrinfo returns a loopback address if the hostname is
2473 * set to NULL and hints.ai_flags is not AI_PASSIVE
2475 memset(&hints, 0, sizeof(hints));
2476 hints.ai_family = IPv4or6;
2477 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2478 hints.ai_socktype = SOCK_STREAM;
2479 snprintf(strport, sizeof strport, "%d", listen_port);
2480 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2482 /* This really shouldn't happen */
2483 packet_disconnect("getaddrinfo: fatal error: %s",
2484 ssh_gai_strerror(r));
2486 error("channel_setup_fwd_listener: "
2487 "getaddrinfo(%.64s): %s", addr,
2488 ssh_gai_strerror(r));
2493 for (ai = aitop; ai; ai = ai->ai_next) {
2494 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
2496 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2497 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2498 error("channel_setup_fwd_listener: getnameinfo failed");
2501 /* Create a port to listen for the host. */
2502 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2504 /* this is no error since kernel may not support ipv6 */
2505 verbose("socket: %.100s", strerror(errno));
2509 channel_set_reuseaddr(sock);
2511 debug("Local forwarding listening on %s port %s.", ntop, strport);
2513 /* Bind the socket to the address. */
2514 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2515 /* address can be in use ipv6 address is already bound */
2517 error("bind: %.100s", strerror(errno));
2519 verbose("bind: %.100s", strerror(errno));
2524 /* Start listening for connections on the socket. */
2525 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2526 error("listen: %.100s", strerror(errno));
2530 /* Allocate a channel number for the socket. */
2531 c = channel_new("port listener", type, sock, sock, -1,
2532 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2533 0, "port listener", 1);
2534 strlcpy(c->path, host, sizeof(c->path));
2535 c->host_port = port_to_connect;
2536 c->listening_port = listen_port;
2540 error("channel_setup_fwd_listener: cannot listen to port: %d",
2542 freeaddrinfo(aitop);
2547 channel_cancel_rport_listener(const char *host, u_short port)
2552 for (i = 0; i < channels_alloc; i++) {
2553 Channel *c = channels[i];
2555 if (c != NULL && c->type == SSH_CHANNEL_RPORT_LISTENER &&
2556 strncmp(c->path, host, sizeof(c->path)) == 0 &&
2557 c->listening_port == port) {
2558 debug2("%s: close channel %d", __func__, i);
2567 /* protocol local port fwd, used by ssh (and sshd in v1) */
2569 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2570 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2572 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2573 listen_host, listen_port, host_to_connect, port_to_connect,
2577 /* protocol v2 remote port fwd, used by sshd */
2579 channel_setup_remote_fwd_listener(const char *listen_address,
2580 u_short listen_port, int gateway_ports)
2582 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2583 listen_address, listen_port, NULL, 0, gateway_ports);
2587 * Initiate forwarding of connections to port "port" on remote host through
2588 * the secure channel to host:port from local side.
2592 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
2593 const char *host_to_connect, u_short port_to_connect)
2595 int type, success = 0;
2597 /* Record locally that connection to this host/port is permitted. */
2598 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2599 fatal("channel_request_remote_forwarding: too many forwards");
2601 /* Send the forward request to the remote side. */
2603 const char *address_to_bind;
2604 if (listen_host == NULL) {
2605 if (datafellows & SSH_BUG_RFWD_ADDR)
2606 address_to_bind = "127.0.0.1";
2608 address_to_bind = "localhost";
2609 } else if (*listen_host == '\0' ||
2610 strcmp(listen_host, "*") == 0) {
2611 if (datafellows & SSH_BUG_RFWD_ADDR)
2612 address_to_bind = "0.0.0.0";
2614 address_to_bind = "";
2616 address_to_bind = listen_host;
2618 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2619 packet_put_cstring("tcpip-forward");
2620 packet_put_char(1); /* boolean: want reply */
2621 packet_put_cstring(address_to_bind);
2622 packet_put_int(listen_port);
2624 packet_write_wait();
2625 /* Assume that server accepts the request */
2628 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
2629 packet_put_int(listen_port);
2630 packet_put_cstring(host_to_connect);
2631 packet_put_int(port_to_connect);
2633 packet_write_wait();
2635 /* Wait for response from the remote side. */
2636 type = packet_read();
2638 case SSH_SMSG_SUCCESS:
2641 case SSH_SMSG_FAILURE:
2644 /* Unknown packet */
2645 packet_disconnect("Protocol error for port forward request:"
2646 "received packet type %d.", type);
2650 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host_to_connect);
2651 permitted_opens[num_permitted_opens].port_to_connect = port_to_connect;
2652 permitted_opens[num_permitted_opens].listen_port = listen_port;
2653 num_permitted_opens++;
2655 return (success ? 0 : -1);
2659 * Request cancellation of remote forwarding of connection host:port from
2663 channel_request_rforward_cancel(const char *host, u_short port)
2670 for (i = 0; i < num_permitted_opens; i++) {
2671 if (permitted_opens[i].host_to_connect != NULL &&
2672 permitted_opens[i].listen_port == port)
2675 if (i >= num_permitted_opens) {
2676 debug("%s: requested forward not found", __func__);
2679 packet_start(SSH2_MSG_GLOBAL_REQUEST);
2680 packet_put_cstring("cancel-tcpip-forward");
2682 packet_put_cstring(host == NULL ? "" : host);
2683 packet_put_int(port);
2686 permitted_opens[i].listen_port = 0;
2687 permitted_opens[i].port_to_connect = 0;
2688 xfree(permitted_opens[i].host_to_connect);
2689 permitted_opens[i].host_to_connect = NULL;
2693 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2694 * listening for the port, and sends back a success reply (or disconnect
2695 * message if there was an error).
2698 channel_input_port_forward_request(int is_root, int gateway_ports)
2700 u_short port, host_port;
2704 /* Get arguments from the packet. */
2705 port = packet_get_int();
2706 hostname = packet_get_string(NULL);
2707 host_port = packet_get_int();
2711 * Check that an unprivileged user is not trying to forward a
2714 if (port < IPPORT_RESERVED && !is_root)
2716 "Requested forwarding of port %d but user is not root.",
2719 packet_disconnect("Dynamic forwarding denied.");
2722 /* Initiate forwarding */
2723 success = channel_setup_local_fwd_listener(NULL, port, hostname,
2724 host_port, gateway_ports);
2726 /* Free the argument string. */
2729 return (success ? 0 : -1);
2733 * Permits opening to any host/port if permitted_opens[] is empty. This is
2734 * usually called by the server, because the user could connect to any port
2735 * anyway, and the server has no way to know but to trust the client anyway.
2738 channel_permit_all_opens(void)
2740 if (num_permitted_opens == 0)
2741 all_opens_permitted = 1;
2745 channel_add_permitted_opens(char *host, int port)
2747 if (num_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2748 fatal("channel_add_permitted_opens: too many forwards");
2749 debug("allow port forwarding to host %s port %d", host, port);
2751 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
2752 permitted_opens[num_permitted_opens].port_to_connect = port;
2753 num_permitted_opens++;
2755 all_opens_permitted = 0;
2759 channel_add_adm_permitted_opens(char *host, int port)
2761 if (num_adm_permitted_opens >= SSH_MAX_FORWARDS_PER_DIRECTION)
2762 fatal("channel_add_adm_permitted_opens: too many forwards");
2763 debug("config allows port forwarding to host %s port %d", host, port);
2765 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
2767 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
2768 return ++num_adm_permitted_opens;
2772 channel_clear_permitted_opens(void)
2776 for (i = 0; i < num_permitted_opens; i++)
2777 if (permitted_opens[i].host_to_connect != NULL)
2778 xfree(permitted_opens[i].host_to_connect);
2779 num_permitted_opens = 0;
2783 channel_clear_adm_permitted_opens(void)
2787 for (i = 0; i < num_adm_permitted_opens; i++)
2788 if (permitted_adm_opens[i].host_to_connect != NULL)
2789 xfree(permitted_adm_opens[i].host_to_connect);
2790 num_adm_permitted_opens = 0;
2794 channel_print_adm_permitted_opens(void)
2798 for (i = 0; i < num_adm_permitted_opens; i++)
2799 if (permitted_adm_opens[i].host_to_connect != NULL)
2800 printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
2801 permitted_adm_opens[i].port_to_connect);
2804 /* Try to start non-blocking connect to next host in cctx list */
2806 connect_next(struct channel_connect *cctx)
2808 int sock, saved_errno;
2809 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2811 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
2812 if (cctx->ai->ai_family != AF_INET &&
2813 cctx->ai->ai_family != AF_INET6)
2815 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
2816 ntop, sizeof(ntop), strport, sizeof(strport),
2817 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2818 error("connect_next: getnameinfo failed");
2821 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
2822 cctx->ai->ai_protocol)) == -1) {
2823 if (cctx->ai->ai_next == NULL)
2824 error("socket: %.100s", strerror(errno));
2826 verbose("socket: %.100s", strerror(errno));
2829 if (set_nonblock(sock) == -1)
2830 fatal("%s: set_nonblock(%d)", __func__, sock);
2831 if (connect(sock, cctx->ai->ai_addr,
2832 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
2833 debug("connect_next: host %.100s ([%.100s]:%s): "
2834 "%.100s", cctx->host, ntop, strport,
2836 saved_errno = errno;
2838 errno = saved_errno;
2839 continue; /* fail -- try next */
2841 debug("connect_next: host %.100s ([%.100s]:%s) "
2842 "in progress, fd=%d", cctx->host, ntop, strport, sock);
2843 cctx->ai = cctx->ai->ai_next;
2851 channel_connect_ctx_free(struct channel_connect *cctx)
2855 freeaddrinfo(cctx->aitop);
2856 bzero(cctx, sizeof(*cctx));
2858 cctx->ai = cctx->aitop = NULL;
2861 /* Return CONNECTING channel to remote host, port */
2863 connect_to(const char *host, u_short port, char *ctype, char *rname)
2865 struct addrinfo hints;
2868 char strport[NI_MAXSERV];
2869 struct channel_connect cctx;
2872 memset(&hints, 0, sizeof(hints));
2873 hints.ai_family = IPv4or6;
2874 hints.ai_socktype = SOCK_STREAM;
2875 snprintf(strport, sizeof strport, "%d", port);
2876 if ((gaierr = getaddrinfo(host, strport, &hints, &cctx.aitop)) != 0) {
2877 error("connect_to %.100s: unknown host (%s)", host,
2878 ssh_gai_strerror(gaierr));
2882 cctx.host = xstrdup(host);
2884 cctx.ai = cctx.aitop;
2886 if ((sock = connect_next(&cctx)) == -1) {
2887 error("connect to %.100s port %d failed: %s",
2888 host, port, strerror(errno));
2889 channel_connect_ctx_free(&cctx);
2892 c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
2893 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
2894 c->connect_ctx = cctx;
2899 channel_connect_by_listen_address(u_short listen_port, char *ctype, char *rname)
2903 for (i = 0; i < num_permitted_opens; i++) {
2904 if (permitted_opens[i].host_to_connect != NULL &&
2905 permitted_opens[i].listen_port == listen_port) {
2907 permitted_opens[i].host_to_connect,
2908 permitted_opens[i].port_to_connect, ctype, rname);
2911 error("WARNING: Server requests forwarding for unknown listen_port %d",
2916 /* Check if connecting to that port is permitted and connect. */
2918 channel_connect_to(const char *host, u_short port, char *ctype, char *rname)
2920 int i, permit, permit_adm = 1;
2922 permit = all_opens_permitted;
2924 for (i = 0; i < num_permitted_opens; i++)
2925 if (permitted_opens[i].host_to_connect != NULL &&
2926 permitted_opens[i].port_to_connect == port &&
2927 strcmp(permitted_opens[i].host_to_connect, host) == 0)
2931 if (num_adm_permitted_opens > 0) {
2933 for (i = 0; i < num_adm_permitted_opens; i++)
2934 if (permitted_adm_opens[i].host_to_connect != NULL &&
2935 permitted_adm_opens[i].port_to_connect == port &&
2936 strcmp(permitted_adm_opens[i].host_to_connect, host)
2941 if (!permit || !permit_adm) {
2942 logit("Received request to connect to host %.100s port %d, "
2943 "but the request was denied.", host, port);
2946 return connect_to(host, port, ctype, rname);
2950 channel_send_window_changes(void)
2955 for (i = 0; i < channels_alloc; i++) {
2956 if (channels[i] == NULL || !channels[i]->client_tty ||
2957 channels[i]->type != SSH_CHANNEL_OPEN)
2959 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
2961 channel_request_start(i, "window-change", 0);
2962 packet_put_int((u_int)ws.ws_col);
2963 packet_put_int((u_int)ws.ws_row);
2964 packet_put_int((u_int)ws.ws_xpixel);
2965 packet_put_int((u_int)ws.ws_ypixel);
2970 /* -- X11 forwarding */
2973 * Creates an internet domain socket for listening for X11 connections.
2974 * Returns 0 and a suitable display number for the DISPLAY variable
2975 * stored in display_numberp , or -1 if an error occurs.
2978 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
2979 int single_connection, u_int *display_numberp, int **chanids)
2982 int display_number, sock;
2984 struct addrinfo hints, *ai, *aitop;
2985 char strport[NI_MAXSERV];
2986 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
2988 if (chanids == NULL)
2991 for (display_number = x11_display_offset;
2992 display_number < MAX_DISPLAYS;
2994 port = 6000 + display_number;
2995 memset(&hints, 0, sizeof(hints));
2996 hints.ai_family = IPv4or6;
2997 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
2998 hints.ai_socktype = SOCK_STREAM;
2999 snprintf(strport, sizeof strport, "%d", port);
3000 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
3001 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
3004 for (ai = aitop; ai; ai = ai->ai_next) {
3005 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
3007 sock = socket(ai->ai_family, ai->ai_socktype,
3010 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)) {
3011 error("socket: %.100s", strerror(errno));
3012 freeaddrinfo(aitop);
3015 debug("x11_create_display_inet: Socket family %d not supported",
3021 if (ai->ai_family == AF_INET6) {
3023 if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0)
3024 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno));
3027 if (x11_use_localhost)
3028 channel_set_reuseaddr(sock);
3029 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3030 debug2("bind port %d: %.100s", port, strerror(errno));
3033 for (n = 0; n < num_socks; n++) {
3039 socks[num_socks++] = sock;
3040 if (num_socks == NUM_SOCKS)
3043 freeaddrinfo(aitop);
3047 if (display_number >= MAX_DISPLAYS) {
3048 error("Failed to allocate internet-domain X11 display socket.");
3051 /* Start listening for connections on the socket. */
3052 for (n = 0; n < num_socks; n++) {
3054 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3055 error("listen: %.100s", strerror(errno));
3061 /* Allocate a channel for each socket. */
3062 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
3063 for (n = 0; n < num_socks; n++) {
3065 nc = channel_new("x11 listener",
3066 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3067 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
3068 0, "X11 inet listener", 1);
3069 nc->single_connection = single_connection;
3070 (*chanids)[n] = nc->self;
3074 /* Return the display number for the DISPLAY environment variable. */
3075 *display_numberp = display_number;
3080 connect_local_xsocket(u_int dnr)
3083 struct sockaddr_un addr;
3085 sock = socket(AF_UNIX, SOCK_STREAM, 0);
3087 error("socket: %.100s", strerror(errno));
3088 memset(&addr, 0, sizeof(addr));
3089 addr.sun_family = AF_UNIX;
3090 snprintf(addr.sun_path, sizeof addr.sun_path, _PATH_UNIX_X, dnr);
3091 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
3094 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
3099 x11_connect_display(void)
3101 u_int display_number;
3102 const char *display;
3103 char buf[1024], *cp;
3104 struct addrinfo hints, *ai, *aitop;
3105 char strport[NI_MAXSERV];
3106 int gaierr, sock = 0;
3108 /* Try to open a socket for the local X server. */
3109 display = getenv("DISPLAY");
3111 error("DISPLAY not set.");
3115 * Now we decode the value of the DISPLAY variable and make a
3116 * connection to the real X server.
3120 * Check if it is a unix domain socket. Unix domain displays are in
3121 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
3123 if (strncmp(display, "unix:", 5) == 0 ||
3124 display[0] == ':') {
3125 /* Connect to the unix domain socket. */
3126 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
3127 error("Could not parse display number from DISPLAY: %.100s",
3131 /* Create a socket. */
3132 sock = connect_local_xsocket(display_number);
3136 /* OK, we now have a connection to the display. */
3140 * Connect to an inet socket. The DISPLAY value is supposedly
3141 * hostname:d[.s], where hostname may also be numeric IP address.
3143 strlcpy(buf, display, sizeof(buf));
3144 cp = strchr(buf, ':');
3146 error("Could not find ':' in DISPLAY: %.100s", display);
3150 /* buf now contains the host name. But first we parse the display number. */
3151 if (sscanf(cp + 1, "%u", &display_number) != 1) {
3152 error("Could not parse display number from DISPLAY: %.100s",
3157 /* Look up the host address */
3158 memset(&hints, 0, sizeof(hints));
3159 hints.ai_family = IPv4or6;
3160 hints.ai_socktype = SOCK_STREAM;
3161 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
3162 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
3163 error("%.100s: unknown host. (%s)", buf,
3164 ssh_gai_strerror(gaierr));
3167 for (ai = aitop; ai; ai = ai->ai_next) {
3168 /* Create a socket. */
3169 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3171 debug2("socket: %.100s", strerror(errno));
3174 /* Connect it to the display. */
3175 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3176 debug2("connect %.100s port %u: %.100s", buf,
3177 6000 + display_number, strerror(errno));
3184 freeaddrinfo(aitop);
3186 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3195 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3196 * the remote channel number. We should do whatever we want, and respond
3197 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3202 x11_input_open(int type, u_int32_t seq, void *ctxt)
3205 int remote_id, sock = 0;
3208 debug("Received X11 open request.");
3210 remote_id = packet_get_int();
3212 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3213 remote_host = packet_get_string(NULL);
3215 remote_host = xstrdup("unknown (remote did not supply name)");
3219 /* Obtain a connection to the real X display. */
3220 sock = x11_connect_display();
3222 /* Allocate a channel for this connection. */
3223 c = channel_new("connected x11 socket",
3224 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3226 c->remote_id = remote_id;
3231 /* Send refusal to the remote host. */
3232 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3233 packet_put_int(remote_id);
3235 /* Send a confirmation to the remote host. */
3236 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3237 packet_put_int(remote_id);
3238 packet_put_int(c->self);
3243 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3246 deny_input_open(int type, u_int32_t seq, void *ctxt)
3248 int rchan = packet_get_int();
3251 case SSH_SMSG_AGENT_OPEN:
3252 error("Warning: ssh server tried agent forwarding.");
3254 case SSH_SMSG_X11_OPEN:
3255 error("Warning: ssh server tried X11 forwarding.");
3258 error("deny_input_open: type %d", type);
3261 error("Warning: this is probably a break-in attempt by a malicious server.");
3262 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3263 packet_put_int(rchan);
3268 * Requests forwarding of X11 connections, generates fake authentication
3269 * data, and enables authentication spoofing.
3270 * This should be called in the client only.
3273 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3274 const char *proto, const char *data)
3276 u_int data_len = (u_int) strlen(data) / 2;
3283 if (x11_saved_display == NULL)
3284 x11_saved_display = xstrdup(disp);
3285 else if (strcmp(disp, x11_saved_display) != 0) {
3286 error("x11_request_forwarding_with_spoofing: different "
3287 "$DISPLAY already forwarded");
3291 cp = strchr(disp, ':');
3293 cp = strchr(cp, '.');
3295 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3299 if (x11_saved_proto == NULL) {
3300 /* Save protocol name. */
3301 x11_saved_proto = xstrdup(proto);
3303 * Extract real authentication data and generate fake data
3304 * of the same length.
3306 x11_saved_data = xmalloc(data_len);
3307 x11_fake_data = xmalloc(data_len);
3308 for (i = 0; i < data_len; i++) {
3309 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3310 fatal("x11_request_forwarding: bad "
3311 "authentication data: %.100s", data);
3314 x11_saved_data[i] = value;
3315 x11_fake_data[i] = rnd & 0xff;
3318 x11_saved_data_len = data_len;
3319 x11_fake_data_len = data_len;
3322 /* Convert the fake data into hex. */
3323 new_data = tohex(x11_fake_data, data_len);
3325 /* Send the request packet. */
3327 channel_request_start(client_session_id, "x11-req", 0);
3328 packet_put_char(0); /* XXX bool single connection */
3330 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3332 packet_put_cstring(proto);
3333 packet_put_cstring(new_data);
3334 packet_put_int(screen_number);
3336 packet_write_wait();
3341 /* -- agent forwarding */
3343 /* Sends a message to the server to request authentication fd forwarding. */
3346 auth_request_forwarding(void)
3348 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3350 packet_write_wait();