1 /* $OpenBSD: channels.c,v 1.318 2012/04/23 08:18: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>
65 #include "openbsd-compat/sys-queue.h"
79 #include "pathnames.h"
84 * Pointer to an array containing all allocated channels. The array is
85 * dynamically extended as needed.
87 static Channel **channels = NULL;
90 * Size of the channel array. All slots of the array must always be
91 * initialized (at least the type field); unused slots set to NULL
93 static u_int channels_alloc = 0;
96 * Maximum file descriptor value used in any of the channels. This is
97 * updated in channel_new.
99 static int channel_max_fd = 0;
102 /* -- tcp forwarding */
105 * Data structure for storing which hosts are permitted for forward requests.
106 * The local sides of any remote forwards are stored in this array to prevent
107 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
108 * network (which might be behind a firewall).
111 char *host_to_connect; /* Connect to 'host'. */
112 u_short port_to_connect; /* Connect to 'port'. */
113 u_short listen_port; /* Remote side should listen port number. */
116 /* List of all permitted host/port pairs to connect by the user. */
117 static ForwardPermission *permitted_opens = NULL;
119 /* List of all permitted host/port pairs to connect by the admin. */
120 static ForwardPermission *permitted_adm_opens = NULL;
122 /* Number of permitted host/port pairs in the array permitted by the user. */
123 static int num_permitted_opens = 0;
125 /* Number of permitted host/port pair in the array permitted by the admin. */
126 static int num_adm_permitted_opens = 0;
128 /* special-case port number meaning allow any port */
129 #define FWD_PERMIT_ANY_PORT 0
132 * If this is true, all opens are permitted. This is the case on the server
133 * on which we have to trust the client anyway, and the user could do
134 * anything after logging in anyway.
136 static int all_opens_permitted = 0;
139 /* -- X11 forwarding */
141 /* Maximum number of fake X11 displays to try. */
142 #define MAX_DISPLAYS 1000
144 /* Saved X11 local (client) display. */
145 static char *x11_saved_display = NULL;
147 /* Saved X11 authentication protocol name. */
148 static char *x11_saved_proto = NULL;
150 /* Saved X11 authentication data. This is the real data. */
151 static char *x11_saved_data = NULL;
152 static u_int x11_saved_data_len = 0;
155 * Fake X11 authentication data. This is what the server will be sending us;
156 * we should replace any occurrences of this by the real data.
158 static u_char *x11_fake_data = NULL;
159 static u_int x11_fake_data_len;
162 /* -- agent forwarding */
166 /* AF_UNSPEC or AF_INET or AF_INET6 */
167 static int IPv4or6 = AF_UNSPEC;
170 static void port_open_helper(Channel *c, char *rtype);
172 /* non-blocking connect helpers */
173 static int connect_next(struct channel_connect *);
174 static void channel_connect_ctx_free(struct channel_connect *);
177 static int hpn_disabled = 0;
178 static int hpn_buffer_size = 2 * 1024 * 1024;
180 /* -- channel core */
185 channel_by_id(int id)
189 if (id < 0 || (u_int)id >= channels_alloc) {
190 logit("channel_by_id: %d: bad id", id);
195 logit("channel_by_id: %d: bad id: channel free", id);
202 * Returns the channel if it is allowed to receive protocol messages.
203 * Private channels, like listening sockets, may not receive messages.
206 channel_lookup(int id)
210 if ((c = channel_by_id(id)) == NULL)
214 case SSH_CHANNEL_X11_OPEN:
215 case SSH_CHANNEL_LARVAL:
216 case SSH_CHANNEL_CONNECTING:
217 case SSH_CHANNEL_DYNAMIC:
218 case SSH_CHANNEL_OPENING:
219 case SSH_CHANNEL_OPEN:
220 case SSH_CHANNEL_INPUT_DRAINING:
221 case SSH_CHANNEL_OUTPUT_DRAINING:
224 logit("Non-public channel %d, type %d.", id, c->type);
229 * Register filedescriptors for a channel, used when allocating a channel or
230 * when the channel consumer/producer is ready, e.g. shell exec'd
233 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
234 int extusage, int nonblock, int is_tty)
236 /* Update the maximum file descriptor value. */
237 channel_max_fd = MAX(channel_max_fd, rfd);
238 channel_max_fd = MAX(channel_max_fd, wfd);
239 channel_max_fd = MAX(channel_max_fd, efd);
242 fcntl(rfd, F_SETFD, FD_CLOEXEC);
243 if (wfd != -1 && wfd != rfd)
244 fcntl(wfd, F_SETFD, FD_CLOEXEC);
245 if (efd != -1 && efd != rfd && efd != wfd)
246 fcntl(efd, F_SETFD, FD_CLOEXEC);
250 c->sock = (rfd == wfd) ? rfd : -1;
252 c->extended_usage = extusage;
254 if ((c->isatty = is_tty) != 0)
255 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
256 c->wfd_isatty = is_tty || isatty(c->wfd);
258 /* enable nonblocking mode */
270 * Allocate a new channel object and set its type and socket. This will cause
271 * remote_name to be freed.
274 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
275 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
281 /* Do initial allocation if this is the first call. */
282 if (channels_alloc == 0) {
284 channels = xcalloc(channels_alloc, sizeof(Channel *));
285 for (i = 0; i < channels_alloc; i++)
288 /* Try to find a free slot where to put the new channel. */
289 for (found = -1, i = 0; i < channels_alloc; i++)
290 if (channels[i] == NULL) {
291 /* Found a free slot. */
296 /* There are no free slots. Take last+1 slot and expand the array. */
297 found = channels_alloc;
298 if (channels_alloc > 10000)
299 fatal("channel_new: internal error: channels_alloc %d "
300 "too big.", channels_alloc);
301 channels = xrealloc(channels, channels_alloc + 10,
303 channels_alloc += 10;
304 debug2("channel: expanding %d", channels_alloc);
305 for (i = found; i < channels_alloc; i++)
308 /* Initialize and return new channel. */
309 c = channels[found] = xcalloc(1, sizeof(Channel));
310 buffer_init(&c->input);
311 buffer_init(&c->output);
312 buffer_init(&c->extended);
314 c->listening_addr = NULL;
315 c->listening_port = 0;
316 c->ostate = CHAN_OUTPUT_OPEN;
317 c->istate = CHAN_INPUT_OPEN;
319 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, 0);
324 c->local_window = window;
325 c->local_window_max = window;
326 c->local_consumed = 0;
327 c->local_maxpacket = maxpack;
328 c->dynamic_window = 0;
330 c->remote_name = xstrdup(remote_name);
331 c->remote_window = 0;
332 c->remote_maxpacket = 0;
334 c->single_connection = 0;
335 c->detach_user = NULL;
337 c->open_confirm = NULL;
338 c->open_confirm_ctx = NULL;
339 c->input_filter = NULL;
340 c->output_filter = NULL;
341 c->filter_ctx = NULL;
342 c->filter_cleanup = NULL;
347 c->delayed = 1; /* prevent call to channel_post handler */
348 TAILQ_INIT(&c->status_confirms);
349 debug("channel %d: new [%s]", found, remote_name);
354 channel_find_maxfd(void)
360 for (i = 0; i < channels_alloc; i++) {
363 max = MAX(max, c->rfd);
364 max = MAX(max, c->wfd);
365 max = MAX(max, c->efd);
372 channel_close_fd(int *fdp)
374 int ret = 0, fd = *fdp;
379 if (fd == channel_max_fd)
380 channel_max_fd = channel_find_maxfd();
385 /* Close all channel fd/socket. */
387 channel_close_fds(Channel *c)
389 channel_close_fd(&c->sock);
390 channel_close_fd(&c->rfd);
391 channel_close_fd(&c->wfd);
392 channel_close_fd(&c->efd);
395 /* Free the channel and close its fd/socket. */
397 channel_free(Channel *c)
401 struct channel_confirm *cc;
403 for (n = 0, i = 0; i < channels_alloc; i++)
406 debug("channel %d: free: %s, nchannels %u", c->self,
407 c->remote_name ? c->remote_name : "???", n);
409 s = channel_open_message();
410 debug3("channel %d: status: %s", c->self, s);
414 shutdown(c->sock, SHUT_RDWR);
415 channel_close_fds(c);
416 buffer_free(&c->input);
417 buffer_free(&c->output);
418 buffer_free(&c->extended);
419 if (c->remote_name) {
420 xfree(c->remote_name);
421 c->remote_name = NULL;
427 if (c->listening_addr) {
428 xfree(c->listening_addr);
429 c->listening_addr = NULL;
431 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
432 if (cc->abandon_cb != NULL)
433 cc->abandon_cb(c, cc->ctx);
434 TAILQ_REMOVE(&c->status_confirms, cc, entry);
435 bzero(cc, sizeof(*cc));
438 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
439 c->filter_cleanup(c->self, c->filter_ctx);
440 channels[c->self] = NULL;
445 channel_free_all(void)
449 for (i = 0; i < channels_alloc; i++)
450 if (channels[i] != NULL)
451 channel_free(channels[i]);
455 * Closes the sockets/fds of all channels. This is used to close extra file
456 * descriptors after a fork.
459 channel_close_all(void)
463 for (i = 0; i < channels_alloc; i++)
464 if (channels[i] != NULL)
465 channel_close_fds(channels[i]);
469 * Stop listening to channels.
472 channel_stop_listening(void)
477 for (i = 0; i < channels_alloc; i++) {
481 case SSH_CHANNEL_AUTH_SOCKET:
482 case SSH_CHANNEL_PORT_LISTENER:
483 case SSH_CHANNEL_RPORT_LISTENER:
484 case SSH_CHANNEL_X11_LISTENER:
485 channel_close_fd(&c->sock);
494 * Returns true if no channel has too much buffered data, and false if one or
495 * more channel is overfull.
498 channel_not_very_much_buffered_data(void)
503 for (i = 0; i < channels_alloc; i++) {
505 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
508 buffer_len(&c->input) > packet_get_maxsize()) {
509 debug2("channel %d: big input buffer %d",
510 c->self, buffer_len(&c->input));
514 if (buffer_len(&c->output) > packet_get_maxsize()) {
515 debug2("channel %d: big output buffer %u > %u",
516 c->self, buffer_len(&c->output),
517 packet_get_maxsize());
525 /* Returns true if any channel is still open. */
527 channel_still_open(void)
532 for (i = 0; i < channels_alloc; i++) {
537 case SSH_CHANNEL_X11_LISTENER:
538 case SSH_CHANNEL_PORT_LISTENER:
539 case SSH_CHANNEL_RPORT_LISTENER:
540 case SSH_CHANNEL_MUX_LISTENER:
541 case SSH_CHANNEL_CLOSED:
542 case SSH_CHANNEL_AUTH_SOCKET:
543 case SSH_CHANNEL_DYNAMIC:
544 case SSH_CHANNEL_CONNECTING:
545 case SSH_CHANNEL_ZOMBIE:
547 case SSH_CHANNEL_LARVAL:
549 fatal("cannot happen: SSH_CHANNEL_LARVAL");
551 case SSH_CHANNEL_OPENING:
552 case SSH_CHANNEL_OPEN:
553 case SSH_CHANNEL_X11_OPEN:
554 case SSH_CHANNEL_MUX_CLIENT:
556 case SSH_CHANNEL_INPUT_DRAINING:
557 case SSH_CHANNEL_OUTPUT_DRAINING:
559 fatal("cannot happen: OUT_DRAIN");
562 fatal("channel_still_open: bad channel type %d", c->type);
569 /* Returns the id of an open channel suitable for keepaliving */
571 channel_find_open(void)
576 for (i = 0; i < channels_alloc; i++) {
578 if (c == NULL || c->remote_id < 0)
581 case SSH_CHANNEL_CLOSED:
582 case SSH_CHANNEL_DYNAMIC:
583 case SSH_CHANNEL_X11_LISTENER:
584 case SSH_CHANNEL_PORT_LISTENER:
585 case SSH_CHANNEL_RPORT_LISTENER:
586 case SSH_CHANNEL_MUX_LISTENER:
587 case SSH_CHANNEL_MUX_CLIENT:
588 case SSH_CHANNEL_OPENING:
589 case SSH_CHANNEL_CONNECTING:
590 case SSH_CHANNEL_ZOMBIE:
592 case SSH_CHANNEL_LARVAL:
593 case SSH_CHANNEL_AUTH_SOCKET:
594 case SSH_CHANNEL_OPEN:
595 case SSH_CHANNEL_X11_OPEN:
597 case SSH_CHANNEL_INPUT_DRAINING:
598 case SSH_CHANNEL_OUTPUT_DRAINING:
600 fatal("cannot happen: OUT_DRAIN");
603 fatal("channel_find_open: bad channel type %d", c->type);
612 * Returns a message describing the currently open forwarded connections,
613 * suitable for sending to the client. The message contains crlf pairs for
617 channel_open_message(void)
624 buffer_init(&buffer);
625 snprintf(buf, sizeof buf, "The following connections are open:\r\n");
626 buffer_append(&buffer, buf, strlen(buf));
627 for (i = 0; i < channels_alloc; i++) {
632 case SSH_CHANNEL_X11_LISTENER:
633 case SSH_CHANNEL_PORT_LISTENER:
634 case SSH_CHANNEL_RPORT_LISTENER:
635 case SSH_CHANNEL_CLOSED:
636 case SSH_CHANNEL_AUTH_SOCKET:
637 case SSH_CHANNEL_ZOMBIE:
638 case SSH_CHANNEL_MUX_CLIENT:
639 case SSH_CHANNEL_MUX_LISTENER:
641 case SSH_CHANNEL_LARVAL:
642 case SSH_CHANNEL_OPENING:
643 case SSH_CHANNEL_CONNECTING:
644 case SSH_CHANNEL_DYNAMIC:
645 case SSH_CHANNEL_OPEN:
646 case SSH_CHANNEL_X11_OPEN:
647 case SSH_CHANNEL_INPUT_DRAINING:
648 case SSH_CHANNEL_OUTPUT_DRAINING:
649 snprintf(buf, sizeof buf,
650 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cc %d)\r\n",
651 c->self, c->remote_name,
652 c->type, c->remote_id,
653 c->istate, buffer_len(&c->input),
654 c->ostate, buffer_len(&c->output),
655 c->rfd, c->wfd, c->ctl_chan);
656 buffer_append(&buffer, buf, strlen(buf));
659 fatal("channel_open_message: bad channel type %d", c->type);
663 buffer_append(&buffer, "\0", 1);
664 cp = xstrdup(buffer_ptr(&buffer));
665 buffer_free(&buffer);
670 channel_send_open(int id)
672 Channel *c = channel_lookup(id);
675 logit("channel_send_open: %d: bad id", id);
678 debug2("channel %d: send open", id);
679 packet_start(SSH2_MSG_CHANNEL_OPEN);
680 packet_put_cstring(c->ctype);
681 packet_put_int(c->self);
682 packet_put_int(c->local_window);
683 packet_put_int(c->local_maxpacket);
688 channel_request_start(int id, char *service, int wantconfirm)
690 Channel *c = channel_lookup(id);
693 logit("channel_request_start: %d: unknown channel id", id);
696 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
697 packet_start(SSH2_MSG_CHANNEL_REQUEST);
698 packet_put_int(c->remote_id);
699 packet_put_cstring(service);
700 packet_put_char(wantconfirm);
704 channel_register_status_confirm(int id, channel_confirm_cb *cb,
705 channel_confirm_abandon_cb *abandon_cb, void *ctx)
707 struct channel_confirm *cc;
710 if ((c = channel_lookup(id)) == NULL)
711 fatal("channel_register_expect: %d: bad id", id);
713 cc = xmalloc(sizeof(*cc));
715 cc->abandon_cb = abandon_cb;
717 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
721 channel_register_open_confirm(int id, channel_open_fn *fn, void *ctx)
723 Channel *c = channel_lookup(id);
726 logit("channel_register_open_confirm: %d: bad id", id);
729 c->open_confirm = fn;
730 c->open_confirm_ctx = ctx;
734 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
736 Channel *c = channel_by_id(id);
739 logit("channel_register_cleanup: %d: bad id", id);
743 c->detach_close = do_close;
747 channel_cancel_cleanup(int id)
749 Channel *c = channel_by_id(id);
752 logit("channel_cancel_cleanup: %d: bad id", id);
755 c->detach_user = NULL;
760 channel_register_filter(int id, channel_infilter_fn *ifn,
761 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
763 Channel *c = channel_lookup(id);
766 logit("channel_register_filter: %d: bad id", id);
769 c->input_filter = ifn;
770 c->output_filter = ofn;
772 c->filter_cleanup = cfn;
776 channel_set_fds(int id, int rfd, int wfd, int efd,
777 int extusage, int nonblock, int is_tty, u_int window_max)
779 Channel *c = channel_lookup(id);
781 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
782 fatal("channel_activate for non-larval channel %d.", id);
783 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, is_tty);
784 c->type = SSH_CHANNEL_OPEN;
785 c->local_window = c->local_window_max = window_max;
786 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
787 packet_put_int(c->remote_id);
788 packet_put_int(c->local_window);
793 * 'channel_pre*' are called just before select() to add any bits relevant to
794 * channels in the select bitmasks.
797 * 'channel_post*': perform any appropriate operations for channels which
798 * have events pending.
800 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
801 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
802 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
806 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
808 FD_SET(c->sock, readset);
813 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
815 debug3("channel %d: waiting for connection", c->self);
816 FD_SET(c->sock, writeset);
820 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
822 if (buffer_len(&c->input) < packet_get_maxsize())
823 FD_SET(c->sock, readset);
824 if (buffer_len(&c->output) > 0)
825 FD_SET(c->sock, writeset);
828 int channel_tcpwinsz () {
829 u_int32_t tcpwinsz = 0;
830 socklen_t optsz = sizeof(tcpwinsz);
833 /* if we aren't on a socket return 128KB*/
834 if(!packet_connection_is_on_socket())
836 ret = getsockopt(packet_get_connection_in(),
837 SOL_SOCKET, SO_RCVBUF, &tcpwinsz, &optsz);
838 /* return no more than 64MB */
839 if ((ret == 0) && tcpwinsz > BUFFER_MAX_LEN_HPN)
840 tcpwinsz = BUFFER_MAX_LEN_HPN;
841 debug2("tcpwinsz: %d for connection: %d", tcpwinsz,
842 packet_get_connection_in());
847 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
849 u_int limit = compat20 ? c->remote_window : packet_get_maxsize();
851 /* check buffer limits */
852 if ((!c->tcpwinsz) || (c->dynamic_window > 0))
853 c->tcpwinsz = channel_tcpwinsz();
855 limit = MIN(limit, 2 * c->tcpwinsz);
857 if (c->istate == CHAN_INPUT_OPEN &&
859 buffer_len(&c->input) < limit &&
860 buffer_check_alloc(&c->input, CHAN_RBUF))
861 FD_SET(c->rfd, readset);
862 if (c->ostate == CHAN_OUTPUT_OPEN ||
863 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
864 if (buffer_len(&c->output) > 0) {
865 FD_SET(c->wfd, writeset);
866 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
867 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
868 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
869 c->self, c->efd, buffer_len(&c->extended));
874 /** XXX check close conditions, too */
875 if (compat20 && c->efd != -1 &&
876 !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
877 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
878 buffer_len(&c->extended) > 0)
879 FD_SET(c->efd, writeset);
880 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
881 (c->extended_usage == CHAN_EXTENDED_READ ||
882 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
883 buffer_len(&c->extended) < c->remote_window)
884 FD_SET(c->efd, readset);
886 /* XXX: What about efd? races? */
891 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
893 if (buffer_len(&c->input) == 0) {
894 packet_start(SSH_MSG_CHANNEL_CLOSE);
895 packet_put_int(c->remote_id);
897 c->type = SSH_CHANNEL_CLOSED;
898 debug2("channel %d: closing after input drain.", c->self);
904 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
906 if (buffer_len(&c->output) == 0)
909 FD_SET(c->sock, writeset);
913 * This is a special state for X11 authentication spoofing. An opened X11
914 * connection (when authentication spoofing is being done) remains in this
915 * state until the first packet has been completely read. The authentication
916 * data in that packet is then substituted by the real data if it matches the
917 * fake data, and the channel is put into normal mode.
918 * XXX All this happens at the client side.
919 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
922 x11_open_helper(Buffer *b)
925 u_int proto_len, data_len;
927 /* Check if the fixed size part of the packet is in buffer. */
928 if (buffer_len(b) < 12)
931 /* Parse the lengths of variable-length fields. */
933 if (ucp[0] == 0x42) { /* Byte order MSB first. */
934 proto_len = 256 * ucp[6] + ucp[7];
935 data_len = 256 * ucp[8] + ucp[9];
936 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
937 proto_len = ucp[6] + 256 * ucp[7];
938 data_len = ucp[8] + 256 * ucp[9];
940 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
945 /* Check if the whole packet is in buffer. */
947 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
950 /* Check if authentication protocol matches. */
951 if (proto_len != strlen(x11_saved_proto) ||
952 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
953 debug2("X11 connection uses different authentication protocol.");
956 /* Check if authentication data matches our fake data. */
957 if (data_len != x11_fake_data_len ||
958 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
959 x11_fake_data, x11_fake_data_len) != 0) {
960 debug2("X11 auth data does not match fake data.");
963 /* Check fake data length */
964 if (x11_fake_data_len != x11_saved_data_len) {
965 error("X11 fake_data_len %d != saved_data_len %d",
966 x11_fake_data_len, x11_saved_data_len);
970 * Received authentication protocol and data match
971 * our fake data. Substitute the fake data with real
974 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
975 x11_saved_data, x11_saved_data_len);
980 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
982 int ret = x11_open_helper(&c->output);
985 /* Start normal processing for the channel. */
986 c->type = SSH_CHANNEL_OPEN;
987 channel_pre_open_13(c, readset, writeset);
988 } else if (ret == -1) {
990 * We have received an X11 connection that has bad
991 * authentication information.
993 logit("X11 connection rejected because of wrong authentication.");
994 buffer_clear(&c->input);
995 buffer_clear(&c->output);
996 channel_close_fd(&c->sock);
998 c->type = SSH_CHANNEL_CLOSED;
999 packet_start(SSH_MSG_CHANNEL_CLOSE);
1000 packet_put_int(c->remote_id);
1006 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
1008 int ret = x11_open_helper(&c->output);
1010 /* c->force_drain = 1; */
1013 c->type = SSH_CHANNEL_OPEN;
1014 channel_pre_open(c, readset, writeset);
1015 } else if (ret == -1) {
1016 logit("X11 connection rejected because of wrong authentication.");
1017 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1018 chan_read_failed(c);
1019 buffer_clear(&c->input);
1021 buffer_clear(&c->output);
1022 /* for proto v1, the peer will send an IEOF */
1024 chan_write_failed(c);
1026 c->type = SSH_CHANNEL_OPEN;
1027 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1032 channel_pre_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1034 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1035 buffer_check_alloc(&c->input, CHAN_RBUF))
1036 FD_SET(c->rfd, readset);
1037 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1038 /* clear buffer immediately (discard any partial packet) */
1039 buffer_clear(&c->input);
1041 /* Start output drain. XXX just kill chan? */
1042 chan_rcvd_oclose(c);
1044 if (c->ostate == CHAN_OUTPUT_OPEN ||
1045 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1046 if (buffer_len(&c->output) > 0)
1047 FD_SET(c->wfd, writeset);
1048 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1053 /* try to decode a socks4 header */
1056 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
1059 u_int len, have, i, found, need;
1064 u_int16_t dest_port;
1065 struct in_addr dest_addr;
1068 debug2("channel %d: decode socks4", c->self);
1070 have = buffer_len(&c->input);
1071 len = sizeof(s4_req);
1074 p = buffer_ptr(&c->input);
1077 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1078 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1079 debug2("channel %d: socks4a request", c->self);
1080 /* ... and needs an extra string (the hostname) */
1083 /* Check for terminating NUL on the string(s) */
1084 for (found = 0, i = len; i < have; i++) {
1091 /* the peer is probably sending garbage */
1092 debug("channel %d: decode socks4: too long",
1099 buffer_get(&c->input, (char *)&s4_req.version, 1);
1100 buffer_get(&c->input, (char *)&s4_req.command, 1);
1101 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1102 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1103 have = buffer_len(&c->input);
1104 p = buffer_ptr(&c->input);
1106 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1107 len++; /* trailing '\0' */
1109 fatal("channel %d: decode socks4: len %d > have %d",
1110 c->self, len, have);
1111 strlcpy(username, p, sizeof(username));
1112 buffer_consume(&c->input, len);
1114 if (c->path != NULL) {
1118 if (need == 1) { /* SOCKS4: one string */
1119 host = inet_ntoa(s4_req.dest_addr);
1120 c->path = xstrdup(host);
1121 } else { /* SOCKS4A: two strings */
1122 have = buffer_len(&c->input);
1123 p = buffer_ptr(&c->input);
1125 debug2("channel %d: decode socks4a: host %s/%d",
1127 len++; /* trailing '\0' */
1129 fatal("channel %d: decode socks4a: len %d > have %d",
1130 c->self, len, have);
1131 if (len > NI_MAXHOST) {
1132 error("channel %d: hostname \"%.100s\" too long",
1136 c->path = xstrdup(p);
1137 buffer_consume(&c->input, len);
1139 c->host_port = ntohs(s4_req.dest_port);
1141 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1142 c->self, c->path, c->host_port, s4_req.command);
1144 if (s4_req.command != 1) {
1145 debug("channel %d: cannot handle: %s cn %d",
1146 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1149 s4_rsp.version = 0; /* vn: 0 for reply */
1150 s4_rsp.command = 90; /* cd: req granted */
1151 s4_rsp.dest_port = 0; /* ignored */
1152 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1153 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1157 /* try to decode a socks5 header */
1158 #define SSH_SOCKS5_AUTHDONE 0x1000
1159 #define SSH_SOCKS5_NOAUTH 0x00
1160 #define SSH_SOCKS5_IPV4 0x01
1161 #define SSH_SOCKS5_DOMAIN 0x03
1162 #define SSH_SOCKS5_IPV6 0x04
1163 #define SSH_SOCKS5_CONNECT 0x01
1164 #define SSH_SOCKS5_SUCCESS 0x00
1168 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1176 u_int16_t dest_port;
1177 u_char *p, dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1178 u_int have, need, i, found, nmethods, addrlen, af;
1180 debug2("channel %d: decode socks5", c->self);
1181 p = buffer_ptr(&c->input);
1184 have = buffer_len(&c->input);
1185 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1186 /* format: ver | nmethods | methods */
1190 if (have < nmethods + 2)
1192 /* look for method: "NO AUTHENTICATION REQUIRED" */
1193 for (found = 0, i = 2; i < nmethods + 2; i++) {
1194 if (p[i] == SSH_SOCKS5_NOAUTH) {
1200 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1204 buffer_consume(&c->input, nmethods + 2);
1205 buffer_put_char(&c->output, 0x05); /* version */
1206 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1207 FD_SET(c->sock, writeset);
1208 c->flags |= SSH_SOCKS5_AUTHDONE;
1209 debug2("channel %d: socks5 auth done", c->self);
1210 return 0; /* need more */
1212 debug2("channel %d: socks5 post auth", c->self);
1213 if (have < sizeof(s5_req)+1)
1214 return 0; /* need more */
1215 memcpy(&s5_req, p, sizeof(s5_req));
1216 if (s5_req.version != 0x05 ||
1217 s5_req.command != SSH_SOCKS5_CONNECT ||
1218 s5_req.reserved != 0x00) {
1219 debug2("channel %d: only socks5 connect supported", c->self);
1222 switch (s5_req.atyp){
1223 case SSH_SOCKS5_IPV4:
1227 case SSH_SOCKS5_DOMAIN:
1228 addrlen = p[sizeof(s5_req)];
1231 case SSH_SOCKS5_IPV6:
1236 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1239 need = sizeof(s5_req) + addrlen + 2;
1240 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1244 buffer_consume(&c->input, sizeof(s5_req));
1245 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1246 buffer_consume(&c->input, 1); /* host string length */
1247 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1248 buffer_get(&c->input, (char *)&dest_port, 2);
1249 dest_addr[addrlen] = '\0';
1250 if (c->path != NULL) {
1254 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1255 if (addrlen >= NI_MAXHOST) {
1256 error("channel %d: dynamic request: socks5 hostname "
1257 "\"%.100s\" too long", c->self, dest_addr);
1260 c->path = xstrdup(dest_addr);
1262 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1264 c->path = xstrdup(ntop);
1266 c->host_port = ntohs(dest_port);
1268 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1269 c->self, c->path, c->host_port, s5_req.command);
1271 s5_rsp.version = 0x05;
1272 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1273 s5_rsp.reserved = 0; /* ignored */
1274 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1275 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1276 dest_port = 0; /* ignored */
1278 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1279 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1280 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1285 channel_connect_stdio_fwd(const char *host_to_connect, u_short port_to_connect,
1290 debug("channel_connect_stdio_fwd %s:%d", host_to_connect,
1293 c = channel_new("stdio-forward", SSH_CHANNEL_OPENING, in, out,
1294 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1295 0, "stdio-forward", /*nonblock*/0);
1297 c->path = xstrdup(host_to_connect);
1298 c->host_port = port_to_connect;
1299 c->listening_port = 0;
1302 channel_register_fds(c, in, out, -1, 0, 1, 0);
1303 port_open_helper(c, "direct-tcpip");
1308 /* dynamic port forwarding */
1310 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1316 have = buffer_len(&c->input);
1317 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1318 /* buffer_dump(&c->input); */
1319 /* check if the fixed size part of the packet is in buffer. */
1322 FD_SET(c->sock, readset);
1325 /* try to guess the protocol */
1326 p = buffer_ptr(&c->input);
1329 ret = channel_decode_socks4(c, readset, writeset);
1332 ret = channel_decode_socks5(c, readset, writeset);
1340 } else if (ret == 0) {
1341 debug2("channel %d: pre_dynamic: need more", c->self);
1343 FD_SET(c->sock, readset);
1345 /* switch to the next state */
1346 c->type = SSH_CHANNEL_OPENING;
1347 port_open_helper(c, "direct-tcpip");
1351 /* This is our fake X11 server socket. */
1354 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1357 struct sockaddr_storage addr;
1360 char buf[16384], *remote_ipaddr;
1363 if (FD_ISSET(c->sock, readset)) {
1364 debug("X11 connection requested.");
1365 addrlen = sizeof(addr);
1366 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1367 if (c->single_connection) {
1368 debug2("single_connection: closing X11 listener.");
1369 channel_close_fd(&c->sock);
1373 error("accept: %.100s", strerror(errno));
1374 if (errno == EMFILE || errno == ENFILE)
1375 c->notbefore = time(NULL) + 1;
1378 set_nodelay(newsock);
1379 remote_ipaddr = get_peer_ipaddr(newsock);
1380 remote_port = get_peer_port(newsock);
1381 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1382 remote_ipaddr, remote_port);
1384 nc = channel_new("accepted x11 socket",
1385 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1386 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1388 packet_start(SSH2_MSG_CHANNEL_OPEN);
1389 packet_put_cstring("x11");
1390 packet_put_int(nc->self);
1391 packet_put_int(nc->local_window_max);
1392 packet_put_int(nc->local_maxpacket);
1393 /* originator ipaddr and port */
1394 packet_put_cstring(remote_ipaddr);
1395 if (datafellows & SSH_BUG_X11FWD) {
1396 debug2("ssh2 x11 bug compat mode");
1398 packet_put_int(remote_port);
1402 packet_start(SSH_SMSG_X11_OPEN);
1403 packet_put_int(nc->self);
1404 if (packet_get_protocol_flags() &
1405 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1406 packet_put_cstring(buf);
1409 xfree(remote_ipaddr);
1414 port_open_helper(Channel *c, char *rtype)
1418 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1419 int remote_port = get_peer_port(c->sock);
1421 if (remote_port == -1) {
1422 /* Fake addr/port to appease peers that validate it (Tectia) */
1423 xfree(remote_ipaddr);
1424 remote_ipaddr = xstrdup("127.0.0.1");
1425 remote_port = 65535;
1428 direct = (strcmp(rtype, "direct-tcpip") == 0);
1430 snprintf(buf, sizeof buf,
1431 "%s: listening port %d for %.100s port %d, "
1432 "connect from %.200s port %d",
1433 rtype, c->listening_port, c->path, c->host_port,
1434 remote_ipaddr, remote_port);
1436 xfree(c->remote_name);
1437 c->remote_name = xstrdup(buf);
1440 packet_start(SSH2_MSG_CHANNEL_OPEN);
1441 packet_put_cstring(rtype);
1442 packet_put_int(c->self);
1443 packet_put_int(c->local_window_max);
1444 packet_put_int(c->local_maxpacket);
1446 /* target host, port */
1447 packet_put_cstring(c->path);
1448 packet_put_int(c->host_port);
1450 /* listen address, port */
1451 packet_put_cstring(c->path);
1452 packet_put_int(c->listening_port);
1454 /* originator host and port */
1455 packet_put_cstring(remote_ipaddr);
1456 packet_put_int((u_int)remote_port);
1459 packet_start(SSH_MSG_PORT_OPEN);
1460 packet_put_int(c->self);
1461 packet_put_cstring(c->path);
1462 packet_put_int(c->host_port);
1463 if (packet_get_protocol_flags() &
1464 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1465 packet_put_cstring(c->remote_name);
1468 xfree(remote_ipaddr);
1472 channel_set_reuseaddr(int fd)
1477 * Set socket options.
1478 * Allow local port reuse in TIME_WAIT.
1480 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1481 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1485 * This socket is listening for connections to a forwarded TCP/IP port.
1489 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1492 struct sockaddr_storage addr;
1493 int newsock, nextstate;
1497 if (FD_ISSET(c->sock, readset)) {
1498 debug("Connection to port %d forwarding "
1499 "to %.100s port %d requested.",
1500 c->listening_port, c->path, c->host_port);
1502 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1503 nextstate = SSH_CHANNEL_OPENING;
1504 rtype = "forwarded-tcpip";
1506 if (c->host_port == 0) {
1507 nextstate = SSH_CHANNEL_DYNAMIC;
1508 rtype = "dynamic-tcpip";
1510 nextstate = SSH_CHANNEL_OPENING;
1511 rtype = "direct-tcpip";
1515 addrlen = sizeof(addr);
1516 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1518 error("accept: %.100s", strerror(errno));
1519 if (errno == EMFILE || errno == ENFILE)
1520 c->notbefore = time(NULL) + 1;
1523 set_nodelay(newsock);
1524 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1525 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1526 nc->listening_port = c->listening_port;
1527 nc->host_port = c->host_port;
1528 if (c->path != NULL)
1529 nc->path = xstrdup(c->path);
1531 if (nextstate != SSH_CHANNEL_DYNAMIC)
1532 port_open_helper(nc, rtype);
1537 * This is the authentication agent socket listening for connections from
1542 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1546 struct sockaddr_storage addr;
1549 if (FD_ISSET(c->sock, readset)) {
1550 addrlen = sizeof(addr);
1551 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1553 error("accept from auth socket: %.100s",
1555 if (errno == EMFILE || errno == ENFILE)
1556 c->notbefore = time(NULL) + 1;
1559 nc = channel_new("accepted auth socket",
1560 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1561 c->local_window_max, c->local_maxpacket,
1562 0, "accepted auth socket", 1);
1564 packet_start(SSH2_MSG_CHANNEL_OPEN);
1565 packet_put_cstring("auth-agent@openssh.com");
1566 packet_put_int(nc->self);
1567 packet_put_int(c->local_window_max);
1568 packet_put_int(c->local_maxpacket);
1570 packet_start(SSH_SMSG_AGENT_OPEN);
1571 packet_put_int(nc->self);
1579 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1582 socklen_t sz = sizeof(err);
1584 if (FD_ISSET(c->sock, writeset)) {
1585 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1587 error("getsockopt SO_ERROR failed");
1590 debug("channel %d: connected to %s port %d",
1591 c->self, c->connect_ctx.host, c->connect_ctx.port);
1592 channel_connect_ctx_free(&c->connect_ctx);
1593 c->type = SSH_CHANNEL_OPEN;
1595 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1596 packet_put_int(c->remote_id);
1597 packet_put_int(c->self);
1598 packet_put_int(c->local_window);
1599 packet_put_int(c->local_maxpacket);
1601 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1602 packet_put_int(c->remote_id);
1603 packet_put_int(c->self);
1606 debug("channel %d: connection failed: %s",
1607 c->self, strerror(err));
1608 /* Try next address, if any */
1609 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1611 c->sock = c->rfd = c->wfd = sock;
1612 channel_max_fd = channel_find_maxfd();
1615 /* Exhausted all addresses */
1616 error("connect_to %.100s port %d: failed.",
1617 c->connect_ctx.host, c->connect_ctx.port);
1618 channel_connect_ctx_free(&c->connect_ctx);
1620 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1621 packet_put_int(c->remote_id);
1622 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1623 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1624 packet_put_cstring(strerror(err));
1625 packet_put_cstring("");
1628 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1629 packet_put_int(c->remote_id);
1639 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1641 char buf[CHAN_RBUF];
1644 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1645 if (c->rfd != -1 && (force || FD_ISSET(c->rfd, readset))) {
1647 len = read(c->rfd, buf, sizeof(buf));
1648 if (len < 0 && (errno == EINTR ||
1649 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1651 #ifndef PTY_ZEROREAD
1654 if ((!c->isatty && len <= 0) ||
1655 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1657 debug2("channel %d: read<=0 rfd %d len %d",
1658 c->self, c->rfd, len);
1659 if (c->type != SSH_CHANNEL_OPEN) {
1660 debug2("channel %d: not open", c->self);
1663 } else if (compat13) {
1664 buffer_clear(&c->output);
1665 c->type = SSH_CHANNEL_INPUT_DRAINING;
1666 debug2("channel %d: input draining.", c->self);
1668 chan_read_failed(c);
1672 if (c->input_filter != NULL) {
1673 if (c->input_filter(c, buf, len) == -1) {
1674 debug2("channel %d: filter stops", c->self);
1675 chan_read_failed(c);
1677 } else if (c->datagram) {
1678 buffer_put_string(&c->input, buf, len);
1680 buffer_append(&c->input, buf, len);
1688 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1691 u_char *data = NULL, *buf;
1692 u_int dlen, olen = 0;
1695 /* Send buffered output data to the socket. */
1697 FD_ISSET(c->wfd, writeset) &&
1698 buffer_len(&c->output) > 0) {
1699 olen = buffer_len(&c->output);
1700 if (c->output_filter != NULL) {
1701 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1702 debug2("channel %d: filter stops", c->self);
1703 if (c->type != SSH_CHANNEL_OPEN)
1706 chan_write_failed(c);
1709 } else if (c->datagram) {
1710 buf = data = buffer_get_string(&c->output, &dlen);
1712 buf = data = buffer_ptr(&c->output);
1713 dlen = buffer_len(&c->output);
1717 /* ignore truncated writes, datagrams might get lost */
1718 len = write(c->wfd, buf, dlen);
1720 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1721 errno == EWOULDBLOCK))
1724 if (c->type != SSH_CHANNEL_OPEN)
1727 chan_write_failed(c);
1733 /* XXX: Later AIX versions can't push as much data to tty */
1734 if (compat20 && c->wfd_isatty)
1735 dlen = MIN(dlen, 8*1024);
1738 len = write(c->wfd, buf, dlen);
1740 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
1743 if (c->type != SSH_CHANNEL_OPEN) {
1744 debug2("channel %d: not open", c->self);
1747 } else if (compat13) {
1748 buffer_clear(&c->output);
1749 debug2("channel %d: input draining.", c->self);
1750 c->type = SSH_CHANNEL_INPUT_DRAINING;
1752 chan_write_failed(c);
1756 #ifndef BROKEN_TCGETATTR_ICANON
1757 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1758 if (tcgetattr(c->wfd, &tio) == 0 &&
1759 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1761 * Simulate echo to reduce the impact of
1762 * traffic analysis. We need to match the
1763 * size of a SSH2_MSG_CHANNEL_DATA message
1764 * (4 byte channel id + buf)
1766 packet_send_ignore(4 + len);
1771 buffer_consume(&c->output, len);
1774 if (compat20 && olen > 0)
1775 c->local_consumed += olen - buffer_len(&c->output);
1780 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1782 char buf[CHAN_RBUF];
1785 /** XXX handle drain efd, too */
1787 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1788 FD_ISSET(c->efd, writeset) &&
1789 buffer_len(&c->extended) > 0) {
1790 len = write(c->efd, buffer_ptr(&c->extended),
1791 buffer_len(&c->extended));
1792 debug2("channel %d: written %d to efd %d",
1793 c->self, len, c->efd);
1794 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1795 errno == EWOULDBLOCK))
1798 debug2("channel %d: closing write-efd %d",
1800 channel_close_fd(&c->efd);
1802 buffer_consume(&c->extended, len);
1803 c->local_consumed += len;
1805 } else if (c->efd != -1 &&
1806 (c->extended_usage == CHAN_EXTENDED_READ ||
1807 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1808 (c->detach_close || FD_ISSET(c->efd, readset))) {
1809 len = read(c->efd, buf, sizeof(buf));
1810 debug2("channel %d: read %d from efd %d",
1811 c->self, len, c->efd);
1812 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
1813 errno == EWOULDBLOCK) && !c->detach_close)))
1816 debug2("channel %d: closing read-efd %d",
1818 channel_close_fd(&c->efd);
1820 if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
1821 debug3("channel %d: discard efd",
1824 buffer_append(&c->extended, buf, len);
1832 channel_check_window(Channel *c)
1834 if (c->type == SSH_CHANNEL_OPEN &&
1835 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1836 ((c->local_window_max - c->local_window >
1837 c->local_maxpacket*3) ||
1838 c->local_window < c->local_window_max/2) &&
1839 c->local_consumed > 0) {
1841 /* adjust max window size if we are in a dynamic environment */
1842 if (c->dynamic_window && (c->tcpwinsz > c->local_window_max)) {
1843 /* grow the window somewhat aggressively to maintain pressure */
1844 addition = 1.5*(c->tcpwinsz - c->local_window_max);
1845 c->local_window_max += addition;
1847 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1848 packet_put_int(c->remote_id);
1849 packet_put_int(c->local_consumed + addition);
1851 debug2("channel %d: window %d sent adjust %d",
1852 c->self, c->local_window,
1854 c->local_window += c->local_consumed + addition;
1855 c->local_consumed = 0;
1861 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1863 channel_handle_rfd(c, readset, writeset);
1864 channel_handle_wfd(c, readset, writeset);
1867 channel_handle_efd(c, readset, writeset);
1868 channel_check_window(c);
1872 read_mux(Channel *c, u_int need)
1874 char buf[CHAN_RBUF];
1878 if (buffer_len(&c->input) < need) {
1879 rlen = need - buffer_len(&c->input);
1880 len = read(c->rfd, buf, MIN(rlen, CHAN_RBUF));
1882 if (errno != EINTR && errno != EAGAIN) {
1883 debug2("channel %d: ctl read<=0 rfd %d len %d",
1884 c->self, c->rfd, len);
1885 chan_read_failed(c);
1889 buffer_append(&c->input, buf, len);
1891 return buffer_len(&c->input);
1895 channel_post_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1901 fatal("%s: entered with !compat20", __func__);
1903 if (c->rfd != -1 && !c->mux_pause && FD_ISSET(c->rfd, readset) &&
1904 (c->istate == CHAN_INPUT_OPEN ||
1905 c->istate == CHAN_INPUT_WAIT_DRAIN)) {
1907 * Don't not read past the precise end of packets to
1908 * avoid disrupting fd passing.
1910 if (read_mux(c, 4) < 4) /* read header */
1912 need = get_u32(buffer_ptr(&c->input));
1913 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
1914 if (need > CHANNEL_MUX_MAX_PACKET) {
1915 debug2("channel %d: packet too big %u > %u",
1916 c->self, CHANNEL_MUX_MAX_PACKET, need);
1917 chan_rcvd_oclose(c);
1920 if (read_mux(c, need + 4) < need + 4) /* read body */
1922 if (c->mux_rcb(c) != 0) {
1923 debug("channel %d: mux_rcb failed", c->self);
1929 if (c->wfd != -1 && FD_ISSET(c->wfd, writeset) &&
1930 buffer_len(&c->output) > 0) {
1931 len = write(c->wfd, buffer_ptr(&c->output),
1932 buffer_len(&c->output));
1933 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1939 buffer_consume(&c->output, len);
1944 channel_post_mux_listener(Channel *c, fd_set *readset, fd_set *writeset)
1947 struct sockaddr_storage addr;
1953 if (!FD_ISSET(c->sock, readset))
1956 debug("multiplexing control connection");
1959 * Accept connection on control socket
1961 memset(&addr, 0, sizeof(addr));
1962 addrlen = sizeof(addr);
1963 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
1965 error("%s accept: %s", __func__, strerror(errno));
1966 if (errno == EMFILE || errno == ENFILE)
1967 c->notbefore = time(NULL) + 1;
1971 if (getpeereid(newsock, &euid, &egid) < 0) {
1972 error("%s getpeereid failed: %s", __func__,
1977 if ((euid != 0) && (getuid() != euid)) {
1978 error("multiplex uid mismatch: peer euid %u != uid %u",
1979 (u_int)euid, (u_int)getuid());
1983 nc = channel_new("multiplex client", SSH_CHANNEL_MUX_CLIENT,
1984 newsock, newsock, -1, c->local_window_max,
1985 c->local_maxpacket, 0, "mux-control", 1);
1986 nc->mux_rcb = c->mux_rcb;
1987 debug3("%s: new mux channel %d fd %d", __func__,
1988 nc->self, nc->sock);
1989 /* establish state */
1991 /* mux state transitions must not elicit protocol messages */
1992 nc->flags |= CHAN_LOCAL;
1997 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
2001 /* Send buffered output data to the socket. */
2002 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
2003 len = write(c->sock, buffer_ptr(&c->output),
2004 buffer_len(&c->output));
2006 buffer_clear(&c->output);
2008 buffer_consume(&c->output, len);
2013 channel_handler_init_20(void)
2015 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2016 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2017 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2018 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2019 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2020 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2021 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2022 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2023 channel_pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2024 channel_pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2026 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2027 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2028 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2029 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2030 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2031 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2032 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2033 channel_post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2034 channel_post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2038 channel_handler_init_13(void)
2040 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
2041 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
2042 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2043 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2044 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2045 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
2046 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
2047 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2048 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2050 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2051 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2052 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2053 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2054 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
2055 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2056 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2060 channel_handler_init_15(void)
2062 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2063 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2064 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2065 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2066 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2067 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2068 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2070 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2071 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2072 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2073 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2074 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2075 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2079 channel_handler_init(void)
2083 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
2084 channel_pre[i] = NULL;
2085 channel_post[i] = NULL;
2088 channel_handler_init_20();
2090 channel_handler_init_13();
2092 channel_handler_init_15();
2095 /* gc dead channels */
2097 channel_garbage_collect(Channel *c)
2101 if (c->detach_user != NULL) {
2102 if (!chan_is_dead(c, c->detach_close))
2104 debug2("channel %d: gc: notify user", c->self);
2105 c->detach_user(c->self, NULL);
2106 /* if we still have a callback */
2107 if (c->detach_user != NULL)
2109 debug2("channel %d: gc: user detached", c->self);
2111 if (!chan_is_dead(c, 1))
2113 debug2("channel %d: garbage collecting", c->self);
2118 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset,
2119 time_t *unpause_secs)
2121 static int did_init = 0;
2127 channel_handler_init();
2131 if (unpause_secs != NULL)
2133 for (i = 0, oalloc = channels_alloc; i < oalloc; i++) {
2138 if (ftab == channel_pre)
2143 if (ftab[c->type] != NULL) {
2145 * Run handlers that are not paused.
2147 if (c->notbefore <= now)
2148 (*ftab[c->type])(c, readset, writeset);
2149 else if (unpause_secs != NULL) {
2151 * Collect the time that the earliest
2152 * channel comes off pause.
2154 debug3("%s: chan %d: skip for %d more seconds",
2156 (int)(c->notbefore - now));
2157 if (*unpause_secs == 0 ||
2158 (c->notbefore - now) < *unpause_secs)
2159 *unpause_secs = c->notbefore - now;
2162 channel_garbage_collect(c);
2164 if (unpause_secs != NULL && *unpause_secs != 0)
2165 debug3("%s: first channel unpauses in %d seconds",
2166 __func__, (int)*unpause_secs);
2170 * Allocate/update select bitmasks and add any bits relevant to channels in
2174 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
2175 u_int *nallocp, time_t *minwait_secs, int rekeying)
2177 u_int n, sz, nfdset;
2179 n = MAX(*maxfdp, channel_max_fd);
2181 nfdset = howmany(n+1, NFDBITS);
2182 /* Explicitly test here, because xrealloc isn't always called */
2183 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
2184 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2185 sz = nfdset * sizeof(fd_mask);
2187 /* perhaps check sz < nalloc/2 and shrink? */
2188 if (*readsetp == NULL || sz > *nallocp) {
2189 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
2190 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
2194 memset(*readsetp, 0, sz);
2195 memset(*writesetp, 0, sz);
2198 channel_handler(channel_pre, *readsetp, *writesetp,
2203 * After select, perform any appropriate operations for channels which have
2207 channel_after_select(fd_set *readset, fd_set *writeset)
2209 channel_handler(channel_post, readset, writeset, NULL);
2213 /* If there is data to send to the connection, enqueue some of it now. */
2215 channel_output_poll(void)
2219 int packet_length = 0;
2221 for (i = 0; i < channels_alloc; i++) {
2227 * We are only interested in channels that can have buffered
2231 if (c->type != SSH_CHANNEL_OPEN &&
2232 c->type != SSH_CHANNEL_INPUT_DRAINING)
2235 if (c->type != SSH_CHANNEL_OPEN)
2239 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2240 /* XXX is this true? */
2241 debug3("channel %d: will not send data after close", c->self);
2245 /* Get the amount of buffered data for this channel. */
2246 if ((c->istate == CHAN_INPUT_OPEN ||
2247 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
2248 (len = buffer_len(&c->input)) > 0) {
2254 data = buffer_get_string(&c->input,
2256 if (dlen > c->remote_window ||
2257 dlen > c->remote_maxpacket) {
2258 debug("channel %d: datagram "
2259 "too big for channel",
2264 packet_start(SSH2_MSG_CHANNEL_DATA);
2265 packet_put_int(c->remote_id);
2266 packet_put_string(data, dlen);
2267 packet_length = packet_send();
2268 c->remote_window -= dlen + 4;
2274 * Send some data for the other side over the secure
2278 if (len > c->remote_window)
2279 len = c->remote_window;
2280 if (len > c->remote_maxpacket)
2281 len = c->remote_maxpacket;
2283 if (packet_is_interactive()) {
2287 /* Keep the packets at reasonable size. */
2288 if (len > packet_get_maxsize()/2)
2289 len = packet_get_maxsize()/2;
2293 packet_start(compat20 ?
2294 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
2295 packet_put_int(c->remote_id);
2296 packet_put_string(buffer_ptr(&c->input), len);
2297 packet_length = packet_send();
2298 buffer_consume(&c->input, len);
2299 c->remote_window -= len;
2301 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2303 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2305 * input-buffer is empty and read-socket shutdown:
2306 * tell peer, that we will not send more data: send IEOF.
2307 * hack for extended data: delay EOF if EFD still in use.
2309 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2310 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2311 c->self, c->efd, buffer_len(&c->extended));
2315 /* Send extended data, i.e. stderr */
2317 !(c->flags & CHAN_EOF_SENT) &&
2318 c->remote_window > 0 &&
2319 (len = buffer_len(&c->extended)) > 0 &&
2320 c->extended_usage == CHAN_EXTENDED_READ) {
2321 debug2("channel %d: rwin %u elen %u euse %d",
2322 c->self, c->remote_window, buffer_len(&c->extended),
2324 if (len > c->remote_window)
2325 len = c->remote_window;
2326 if (len > c->remote_maxpacket)
2327 len = c->remote_maxpacket;
2328 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
2329 packet_put_int(c->remote_id);
2330 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
2331 packet_put_string(buffer_ptr(&c->extended), len);
2332 packet_length = packet_send();
2333 buffer_consume(&c->extended, len);
2334 c->remote_window -= len;
2335 debug2("channel %d: sent ext data %d", c->self, len);
2338 return (packet_length);
2342 /* -- protocol input */
2346 channel_input_data(int type, u_int32_t seq, void *ctxt)
2350 u_int data_len, win_len;
2353 /* Get the channel number and verify it. */
2354 id = packet_get_int();
2355 c = channel_lookup(id);
2357 packet_disconnect("Received data for nonexistent channel %d.", id);
2359 /* Ignore any data for non-open channels (might happen on close) */
2360 if (c->type != SSH_CHANNEL_OPEN &&
2361 c->type != SSH_CHANNEL_X11_OPEN)
2365 data = packet_get_string_ptr(&data_len);
2368 win_len += 4; /* string length header */
2371 * Ignore data for protocol > 1.3 if output end is no longer open.
2372 * For protocol 2 the sending side is reducing its window as it sends
2373 * data, so we must 'fake' consumption of the data in order to ensure
2374 * that window updates are sent back. Otherwise the connection might
2377 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2379 c->local_window -= win_len;
2380 c->local_consumed += win_len;
2386 if (win_len > c->local_maxpacket) {
2387 logit("channel %d: rcvd big packet %d, maxpack %d",
2388 c->self, win_len, c->local_maxpacket);
2390 if (win_len > c->local_window) {
2391 logit("channel %d: rcvd too much data %d, win %d",
2392 c->self, win_len, c->local_window);
2395 c->local_window -= win_len;
2398 buffer_put_string(&c->output, data, data_len);
2400 buffer_append(&c->output, data, data_len);
2406 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2410 u_int data_len, tcode;
2413 /* Get the channel number and verify it. */
2414 id = packet_get_int();
2415 c = channel_lookup(id);
2418 packet_disconnect("Received extended_data for bad channel %d.", id);
2419 if (c->type != SSH_CHANNEL_OPEN) {
2420 logit("channel %d: ext data for non open", id);
2423 if (c->flags & CHAN_EOF_RCVD) {
2424 if (datafellows & SSH_BUG_EXTEOF)
2425 debug("channel %d: accepting ext data after eof", id);
2427 packet_disconnect("Received extended_data after EOF "
2428 "on channel %d.", id);
2430 tcode = packet_get_int();
2432 c->extended_usage != CHAN_EXTENDED_WRITE ||
2433 tcode != SSH2_EXTENDED_DATA_STDERR) {
2434 logit("channel %d: bad ext data", c->self);
2437 data = packet_get_string(&data_len);
2439 if (data_len > c->local_window) {
2440 logit("channel %d: rcvd too much extended_data %d, win %d",
2441 c->self, data_len, c->local_window);
2445 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2446 c->local_window -= data_len;
2447 buffer_append(&c->extended, data, data_len);
2453 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2458 id = packet_get_int();
2460 c = channel_lookup(id);
2462 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2465 /* XXX force input close */
2466 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2467 debug("channel %d: FORCE input drain", c->self);
2468 c->istate = CHAN_INPUT_WAIT_DRAIN;
2469 if (buffer_len(&c->input) == 0)
2477 channel_input_close(int type, u_int32_t seq, void *ctxt)
2482 id = packet_get_int();
2484 c = channel_lookup(id);
2486 packet_disconnect("Received close for nonexistent channel %d.", id);
2489 * Send a confirmation that we have closed the channel and no more
2490 * data is coming for it.
2492 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2493 packet_put_int(c->remote_id);
2497 * If the channel is in closed state, we have sent a close request,
2498 * and the other side will eventually respond with a confirmation.
2499 * Thus, we cannot free the channel here, because then there would be
2500 * no-one to receive the confirmation. The channel gets freed when
2501 * the confirmation arrives.
2503 if (c->type != SSH_CHANNEL_CLOSED) {
2505 * Not a closed channel - mark it as draining, which will
2506 * cause it to be freed later.
2508 buffer_clear(&c->input);
2509 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2513 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2516 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2518 int id = packet_get_int();
2519 Channel *c = channel_lookup(id);
2523 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2524 chan_rcvd_oclose(c);
2529 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2531 int id = packet_get_int();
2532 Channel *c = channel_lookup(id);
2536 packet_disconnect("Received close confirmation for "
2537 "out-of-range channel %d.", id);
2538 if (c->type != SSH_CHANNEL_CLOSED)
2539 packet_disconnect("Received close confirmation for "
2540 "non-closed channel %d (type %d).", id, c->type);
2546 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2551 id = packet_get_int();
2552 c = channel_lookup(id);
2554 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2555 packet_disconnect("Received open confirmation for "
2556 "non-opening channel %d.", id);
2557 remote_id = packet_get_int();
2558 /* Record the remote channel number and mark that the channel is now open. */
2559 c->remote_id = remote_id;
2560 c->type = SSH_CHANNEL_OPEN;
2563 c->remote_window = packet_get_int();
2564 c->remote_maxpacket = packet_get_int();
2565 if (c->open_confirm) {
2566 debug2("callback start");
2567 c->open_confirm(c->self, 1, c->open_confirm_ctx);
2568 debug2("callback done");
2570 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2571 c->remote_window, c->remote_maxpacket);
2577 reason2txt(int reason)
2580 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2581 return "administratively prohibited";
2582 case SSH2_OPEN_CONNECT_FAILED:
2583 return "connect failed";
2584 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2585 return "unknown channel type";
2586 case SSH2_OPEN_RESOURCE_SHORTAGE:
2587 return "resource shortage";
2589 return "unknown reason";
2594 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2597 char *msg = NULL, *lang = NULL;
2600 id = packet_get_int();
2601 c = channel_lookup(id);
2603 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2604 packet_disconnect("Received open failure for "
2605 "non-opening channel %d.", id);
2607 reason = packet_get_int();
2608 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2609 msg = packet_get_string(NULL);
2610 lang = packet_get_string(NULL);
2612 logit("channel %d: open failed: %s%s%s", id,
2613 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2618 if (c->open_confirm) {
2619 debug2("callback start");
2620 c->open_confirm(c->self, 0, c->open_confirm_ctx);
2621 debug2("callback done");
2625 /* Schedule the channel for cleanup/deletion. */
2631 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2640 /* Get the channel number and verify it. */
2641 id = packet_get_int();
2642 c = channel_lookup(id);
2645 logit("Received window adjust for non-open channel %d.", id);
2648 adjust = packet_get_int();
2650 debug2("channel %d: rcvd adjust %u", id, adjust);
2651 c->remote_window += adjust;
2656 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2660 char *host, *originator_string;
2663 remote_id = packet_get_int();
2664 host = packet_get_string(NULL);
2665 host_port = packet_get_int();
2667 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2668 originator_string = packet_get_string(NULL);
2670 originator_string = xstrdup("unknown (remote did not supply name)");
2673 c = channel_connect_to(host, host_port,
2674 "connected socket", originator_string);
2675 xfree(originator_string);
2678 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2679 packet_put_int(remote_id);
2682 c->remote_id = remote_id;
2687 channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
2690 struct channel_confirm *cc;
2693 /* Reset keepalive timeout */
2694 packet_set_alive_timeouts(0);
2696 id = packet_get_int();
2699 debug2("channel_input_status_confirm: type %d id %d", type, id);
2701 if ((c = channel_lookup(id)) == NULL) {
2702 logit("channel_input_status_confirm: %d: unknown", id);
2706 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
2708 cc->cb(type, c, cc->ctx);
2709 TAILQ_REMOVE(&c->status_confirms, cc, entry);
2710 bzero(cc, sizeof(*cc));
2714 /* -- tcp forwarding */
2717 channel_set_af(int af)
2724 channel_set_hpn(int external_hpn_disabled, int external_hpn_buffer_size)
2726 hpn_disabled = external_hpn_disabled;
2727 hpn_buffer_size = external_hpn_buffer_size;
2728 debug("HPN Disabled: %d, HPN Buffer Size: %d", hpn_disabled, hpn_buffer_size);
2731 * Determine whether or not a port forward listens to loopback, the
2732 * specified address or wildcard. On the client, a specified bind
2733 * address will always override gateway_ports. On the server, a
2734 * gateway_ports of 1 (``yes'') will override the client's specification
2735 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
2736 * will bind to whatever address the client asked for.
2738 * Special-case listen_addrs are:
2740 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2741 * "" (empty string), "*" -> wildcard v4/v6
2742 * "localhost" -> loopback v4/v6
2745 channel_fwd_bind_addr(const char *listen_addr, int *wildcardp,
2746 int is_client, int gateway_ports)
2748 const char *addr = NULL;
2751 if (listen_addr == NULL) {
2752 /* No address specified: default to gateway_ports setting */
2755 } else if (gateway_ports || is_client) {
2756 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2757 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
2758 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2759 (!is_client && gateway_ports == 1))
2761 else if (strcmp(listen_addr, "localhost") != 0)
2764 if (wildcardp != NULL)
2765 *wildcardp = wildcard;
2770 channel_setup_fwd_listener(int type, const char *listen_addr,
2771 u_short listen_port, int *allocated_listen_port,
2772 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2775 int sock, r, success = 0, wildcard = 0, is_client;
2776 struct addrinfo hints, *ai, *aitop;
2777 const char *host, *addr;
2778 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2781 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2782 listen_addr : host_to_connect;
2783 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2786 error("No forward host name.");
2789 if (strlen(host) >= NI_MAXHOST) {
2790 error("Forward host name too long.");
2794 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
2795 addr = channel_fwd_bind_addr(listen_addr, &wildcard,
2796 is_client, gateway_ports);
2797 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2798 type, wildcard, (addr == NULL) ? "NULL" : addr);
2801 * getaddrinfo returns a loopback address if the hostname is
2802 * set to NULL and hints.ai_flags is not AI_PASSIVE
2804 memset(&hints, 0, sizeof(hints));
2805 hints.ai_family = IPv4or6;
2806 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2807 hints.ai_socktype = SOCK_STREAM;
2808 snprintf(strport, sizeof strport, "%d", listen_port);
2809 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2811 /* This really shouldn't happen */
2812 packet_disconnect("getaddrinfo: fatal error: %s",
2813 ssh_gai_strerror(r));
2815 error("channel_setup_fwd_listener: "
2816 "getaddrinfo(%.64s): %s", addr,
2817 ssh_gai_strerror(r));
2821 if (allocated_listen_port != NULL)
2822 *allocated_listen_port = 0;
2823 for (ai = aitop; ai; ai = ai->ai_next) {
2824 switch (ai->ai_family) {
2826 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
2830 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
2837 * If allocating a port for -R forwards, then use the
2838 * same port for all address families.
2840 if (type == SSH_CHANNEL_RPORT_LISTENER && listen_port == 0 &&
2841 allocated_listen_port != NULL && *allocated_listen_port > 0)
2842 *lport_p = htons(*allocated_listen_port);
2844 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2845 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2846 error("channel_setup_fwd_listener: getnameinfo failed");
2849 /* Create a port to listen for the host. */
2850 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2852 /* this is no error since kernel may not support ipv6 */
2853 verbose("socket: %.100s", strerror(errno));
2857 channel_set_reuseaddr(sock);
2858 if (ai->ai_family == AF_INET6)
2859 sock_set_v6only(sock);
2861 debug("Local forwarding listening on %s port %s.",
2864 /* Bind the socket to the address. */
2865 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2866 /* address can be in use ipv6 address is already bound */
2868 error("bind: %.100s", strerror(errno));
2870 verbose("bind: %.100s", strerror(errno));
2875 /* Start listening for connections on the socket. */
2876 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2877 error("listen: %.100s", strerror(errno));
2883 * listen_port == 0 requests a dynamically allocated port -
2884 * record what we got.
2886 if (type == SSH_CHANNEL_RPORT_LISTENER && listen_port == 0 &&
2887 allocated_listen_port != NULL &&
2888 *allocated_listen_port == 0) {
2889 *allocated_listen_port = get_sock_port(sock, 1);
2890 debug("Allocated listen port %d",
2891 *allocated_listen_port);
2894 /* Allocate a channel number for the socket. */
2895 /* explicitly test for hpn disabled option. if true use smaller window size */
2897 c = channel_new("port listener", type, sock, sock, -1,
2898 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2899 0, "port listener", 1);
2901 c = channel_new("port listener", type, sock, sock, -1,
2902 hpn_buffer_size, CHAN_TCP_PACKET_DEFAULT,
2903 0, "port listener", 1);
2904 c->path = xstrdup(host);
2905 c->host_port = port_to_connect;
2906 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
2907 if (listen_port == 0 && allocated_listen_port != NULL &&
2908 !(datafellows & SSH_BUG_DYNAMIC_RPORT))
2909 c->listening_port = *allocated_listen_port;
2911 c->listening_port = listen_port;
2915 error("channel_setup_fwd_listener: cannot listen to port: %d",
2917 freeaddrinfo(aitop);
2922 channel_cancel_rport_listener(const char *host, u_short port)
2927 for (i = 0; i < channels_alloc; i++) {
2928 Channel *c = channels[i];
2929 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
2931 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
2932 debug2("%s: close channel %d", __func__, i);
2942 channel_cancel_lport_listener(const char *lhost, u_short lport,
2943 int cport, int gateway_ports)
2947 const char *addr = channel_fwd_bind_addr(lhost, NULL, 1, gateway_ports);
2949 for (i = 0; i < channels_alloc; i++) {
2950 Channel *c = channels[i];
2951 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
2953 if (c->listening_port != lport)
2955 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
2956 /* skip dynamic forwardings */
2957 if (c->host_port == 0)
2960 if (c->host_port != cport)
2963 if ((c->listening_addr == NULL && addr != NULL) ||
2964 (c->listening_addr != NULL && addr == NULL))
2966 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
2967 debug2("%s: close channel %d", __func__, i);
2976 /* protocol local port fwd, used by ssh (and sshd in v1) */
2978 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2979 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2981 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2982 listen_host, listen_port, NULL, host_to_connect, port_to_connect,
2986 /* protocol v2 remote port fwd, used by sshd */
2988 channel_setup_remote_fwd_listener(const char *listen_address,
2989 u_short listen_port, int *allocated_listen_port, int gateway_ports)
2991 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
2992 listen_address, listen_port, allocated_listen_port,
2993 NULL, 0, gateway_ports);
2997 * Translate the requested rfwd listen host to something usable for
3001 channel_rfwd_bind_host(const char *listen_host)
3003 if (listen_host == NULL) {
3004 if (datafellows & SSH_BUG_RFWD_ADDR)
3008 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3009 if (datafellows & SSH_BUG_RFWD_ADDR)
3018 * Initiate forwarding of connections to port "port" on remote host through
3019 * the secure channel to host:port from local side.
3020 * Returns handle (index) for updating the dynamic listen port with
3021 * channel_update_permitted_opens().
3024 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
3025 const char *host_to_connect, u_short port_to_connect)
3027 int type, success = 0, idx = -1;
3029 /* Send the forward request to the remote side. */
3031 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3032 packet_put_cstring("tcpip-forward");
3033 packet_put_char(1); /* boolean: want reply */
3034 packet_put_cstring(channel_rfwd_bind_host(listen_host));
3035 packet_put_int(listen_port);
3037 packet_write_wait();
3038 /* Assume that server accepts the request */
3041 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
3042 packet_put_int(listen_port);
3043 packet_put_cstring(host_to_connect);
3044 packet_put_int(port_to_connect);
3046 packet_write_wait();
3048 /* Wait for response from the remote side. */
3049 type = packet_read();
3051 case SSH_SMSG_SUCCESS:
3054 case SSH_SMSG_FAILURE:
3057 /* Unknown packet */
3058 packet_disconnect("Protocol error for port forward request:"
3059 "received packet type %d.", type);
3063 /* Record that connection to this host/port is permitted. */
3064 permitted_opens = xrealloc(permitted_opens,
3065 num_permitted_opens + 1, sizeof(*permitted_opens));
3066 idx = num_permitted_opens++;
3067 permitted_opens[idx].host_to_connect = xstrdup(host_to_connect);
3068 permitted_opens[idx].port_to_connect = port_to_connect;
3069 permitted_opens[idx].listen_port = listen_port;
3075 * Request cancellation of remote forwarding of connection host:port from
3079 channel_request_rforward_cancel(const char *host, u_short port)
3086 for (i = 0; i < num_permitted_opens; i++) {
3087 if (permitted_opens[i].host_to_connect != NULL &&
3088 permitted_opens[i].listen_port == port)
3091 if (i >= num_permitted_opens) {
3092 debug("%s: requested forward not found", __func__);
3095 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3096 packet_put_cstring("cancel-tcpip-forward");
3098 packet_put_cstring(channel_rfwd_bind_host(host));
3099 packet_put_int(port);
3102 permitted_opens[i].listen_port = 0;
3103 permitted_opens[i].port_to_connect = 0;
3104 xfree(permitted_opens[i].host_to_connect);
3105 permitted_opens[i].host_to_connect = NULL;
3111 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
3112 * listening for the port, and sends back a success reply (or disconnect
3113 * message if there was an error).
3116 channel_input_port_forward_request(int is_root, int gateway_ports)
3118 u_short port, host_port;
3122 /* Get arguments from the packet. */
3123 port = packet_get_int();
3124 hostname = packet_get_string(NULL);
3125 host_port = packet_get_int();
3129 * Check that an unprivileged user is not trying to forward a
3132 if (port < IPPORT_RESERVED && !is_root)
3134 "Requested forwarding of port %d but user is not root.",
3137 packet_disconnect("Dynamic forwarding denied.");
3140 /* Initiate forwarding */
3141 success = channel_setup_local_fwd_listener(NULL, port, hostname,
3142 host_port, gateway_ports);
3144 /* Free the argument string. */
3147 return (success ? 0 : -1);
3151 * Permits opening to any host/port if permitted_opens[] is empty. This is
3152 * usually called by the server, because the user could connect to any port
3153 * anyway, and the server has no way to know but to trust the client anyway.
3156 channel_permit_all_opens(void)
3158 if (num_permitted_opens == 0)
3159 all_opens_permitted = 1;
3163 channel_add_permitted_opens(char *host, int port)
3165 debug("allow port forwarding to host %s port %d", host, port);
3167 permitted_opens = xrealloc(permitted_opens,
3168 num_permitted_opens + 1, sizeof(*permitted_opens));
3169 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
3170 permitted_opens[num_permitted_opens].port_to_connect = port;
3171 num_permitted_opens++;
3173 all_opens_permitted = 0;
3177 * Update the listen port for a dynamic remote forward, after
3178 * the actual 'newport' has been allocated. If 'newport' < 0 is
3179 * passed then they entry will be invalidated.
3182 channel_update_permitted_opens(int idx, int newport)
3184 if (idx < 0 || idx >= num_permitted_opens) {
3185 debug("channel_update_permitted_opens: index out of range:"
3186 " %d num_permitted_opens %d", idx, num_permitted_opens);
3189 debug("%s allowed port %d for forwarding to host %s port %d",
3190 newport > 0 ? "Updating" : "Removing",
3192 permitted_opens[idx].host_to_connect,
3193 permitted_opens[idx].port_to_connect);
3195 permitted_opens[idx].listen_port =
3196 (datafellows & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
3198 permitted_opens[idx].listen_port = 0;
3199 permitted_opens[idx].port_to_connect = 0;
3200 xfree(permitted_opens[idx].host_to_connect);
3201 permitted_opens[idx].host_to_connect = NULL;
3206 channel_add_adm_permitted_opens(char *host, int port)
3208 debug("config allows port forwarding to host %s port %d", host, port);
3210 permitted_adm_opens = xrealloc(permitted_adm_opens,
3211 num_adm_permitted_opens + 1, sizeof(*permitted_adm_opens));
3212 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
3214 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
3215 return ++num_adm_permitted_opens;
3219 channel_disable_adm_local_opens(void)
3221 if (num_adm_permitted_opens == 0) {
3222 permitted_adm_opens = xmalloc(sizeof(*permitted_adm_opens));
3223 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
3225 num_adm_permitted_opens = 1;
3230 channel_clear_permitted_opens(void)
3234 for (i = 0; i < num_permitted_opens; i++)
3235 if (permitted_opens[i].host_to_connect != NULL)
3236 xfree(permitted_opens[i].host_to_connect);
3237 if (num_permitted_opens > 0) {
3238 xfree(permitted_opens);
3239 permitted_opens = NULL;
3241 num_permitted_opens = 0;
3245 channel_clear_adm_permitted_opens(void)
3249 for (i = 0; i < num_adm_permitted_opens; i++)
3250 if (permitted_adm_opens[i].host_to_connect != NULL)
3251 xfree(permitted_adm_opens[i].host_to_connect);
3252 if (num_adm_permitted_opens > 0) {
3253 xfree(permitted_adm_opens);
3254 permitted_adm_opens = NULL;
3256 num_adm_permitted_opens = 0;
3260 channel_print_adm_permitted_opens(void)
3264 printf("permitopen");
3265 if (num_adm_permitted_opens == 0) {
3269 for (i = 0; i < num_adm_permitted_opens; i++)
3270 if (permitted_adm_opens[i].host_to_connect == NULL)
3273 printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
3274 permitted_adm_opens[i].port_to_connect);
3278 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
3280 permitopen_port(const char *p)
3284 if (strcmp(p, "*") == 0)
3285 return FWD_PERMIT_ANY_PORT;
3286 if ((port = a2port(p)) > 0)
3292 port_match(u_short allowedport, u_short requestedport)
3294 if (allowedport == FWD_PERMIT_ANY_PORT ||
3295 allowedport == requestedport)
3300 /* Try to start non-blocking connect to next host in cctx list */
3302 connect_next(struct channel_connect *cctx)
3304 int sock, saved_errno;
3305 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3307 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
3308 if (cctx->ai->ai_family != AF_INET &&
3309 cctx->ai->ai_family != AF_INET6)
3311 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
3312 ntop, sizeof(ntop), strport, sizeof(strport),
3313 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3314 error("connect_next: getnameinfo failed");
3317 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
3318 cctx->ai->ai_protocol)) == -1) {
3319 if (cctx->ai->ai_next == NULL)
3320 error("socket: %.100s", strerror(errno));
3322 verbose("socket: %.100s", strerror(errno));
3325 if (set_nonblock(sock) == -1)
3326 fatal("%s: set_nonblock(%d)", __func__, sock);
3327 if (connect(sock, cctx->ai->ai_addr,
3328 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
3329 debug("connect_next: host %.100s ([%.100s]:%s): "
3330 "%.100s", cctx->host, ntop, strport,
3332 saved_errno = errno;
3334 errno = saved_errno;
3335 continue; /* fail -- try next */
3337 debug("connect_next: host %.100s ([%.100s]:%s) "
3338 "in progress, fd=%d", cctx->host, ntop, strport, sock);
3339 cctx->ai = cctx->ai->ai_next;
3347 channel_connect_ctx_free(struct channel_connect *cctx)
3351 freeaddrinfo(cctx->aitop);
3352 bzero(cctx, sizeof(*cctx));
3354 cctx->ai = cctx->aitop = NULL;
3357 /* Return CONNECTING channel to remote host, port */
3359 connect_to(const char *host, u_short port, char *ctype, char *rname)
3361 struct addrinfo hints;
3364 char strport[NI_MAXSERV];
3365 struct channel_connect cctx;
3368 memset(&cctx, 0, sizeof(cctx));
3369 memset(&hints, 0, sizeof(hints));
3370 hints.ai_family = IPv4or6;
3371 hints.ai_socktype = SOCK_STREAM;
3372 snprintf(strport, sizeof strport, "%d", port);
3373 if ((gaierr = getaddrinfo(host, strport, &hints, &cctx.aitop)) != 0) {
3374 error("connect_to %.100s: unknown host (%s)", host,
3375 ssh_gai_strerror(gaierr));
3379 cctx.host = xstrdup(host);
3381 cctx.ai = cctx.aitop;
3383 if ((sock = connect_next(&cctx)) == -1) {
3384 error("connect to %.100s port %d failed: %s",
3385 host, port, strerror(errno));
3386 channel_connect_ctx_free(&cctx);
3389 c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
3390 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
3391 c->connect_ctx = cctx;
3396 channel_connect_by_listen_address(u_short listen_port, char *ctype, char *rname)
3400 for (i = 0; i < num_permitted_opens; i++) {
3401 if (permitted_opens[i].host_to_connect != NULL &&
3402 port_match(permitted_opens[i].listen_port, listen_port)) {
3404 permitted_opens[i].host_to_connect,
3405 permitted_opens[i].port_to_connect, ctype, rname);
3408 error("WARNING: Server requests forwarding for unknown listen_port %d",
3413 /* Check if connecting to that port is permitted and connect. */
3415 channel_connect_to(const char *host, u_short port, char *ctype, char *rname)
3417 int i, permit, permit_adm = 1;
3419 permit = all_opens_permitted;
3421 for (i = 0; i < num_permitted_opens; i++)
3422 if (permitted_opens[i].host_to_connect != NULL &&
3423 port_match(permitted_opens[i].port_to_connect, port) &&
3424 strcmp(permitted_opens[i].host_to_connect, host) == 0)
3428 if (num_adm_permitted_opens > 0) {
3430 for (i = 0; i < num_adm_permitted_opens; i++)
3431 if (permitted_adm_opens[i].host_to_connect != NULL &&
3432 port_match(permitted_adm_opens[i].port_to_connect, port) &&
3433 strcmp(permitted_adm_opens[i].host_to_connect, host)
3438 if (!permit || !permit_adm) {
3439 logit("Received request to connect to host %.100s port %d, "
3440 "but the request was denied.", host, port);
3443 return connect_to(host, port, ctype, rname);
3447 channel_send_window_changes(void)
3452 for (i = 0; i < channels_alloc; i++) {
3453 if (channels[i] == NULL || !channels[i]->client_tty ||
3454 channels[i]->type != SSH_CHANNEL_OPEN)
3456 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
3458 channel_request_start(i, "window-change", 0);
3459 packet_put_int((u_int)ws.ws_col);
3460 packet_put_int((u_int)ws.ws_row);
3461 packet_put_int((u_int)ws.ws_xpixel);
3462 packet_put_int((u_int)ws.ws_ypixel);
3467 /* -- X11 forwarding */
3470 * Creates an internet domain socket for listening for X11 connections.
3471 * Returns 0 and a suitable display number for the DISPLAY variable
3472 * stored in display_numberp , or -1 if an error occurs.
3475 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
3476 int single_connection, u_int *display_numberp, int **chanids)
3479 int display_number, sock;
3481 struct addrinfo hints, *ai, *aitop;
3482 char strport[NI_MAXSERV];
3483 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
3485 if (chanids == NULL)
3488 for (display_number = x11_display_offset;
3489 display_number < MAX_DISPLAYS;
3491 port = 6000 + display_number;
3492 memset(&hints, 0, sizeof(hints));
3493 hints.ai_family = IPv4or6;
3494 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
3495 hints.ai_socktype = SOCK_STREAM;
3496 snprintf(strport, sizeof strport, "%d", port);
3497 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
3498 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
3501 for (ai = aitop; ai; ai = ai->ai_next) {
3502 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
3504 sock = socket(ai->ai_family, ai->ai_socktype,
3507 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
3509 && (errno != EPFNOSUPPORT)
3512 error("socket: %.100s", strerror(errno));
3513 freeaddrinfo(aitop);
3516 debug("x11_create_display_inet: Socket family %d not supported",
3521 if (ai->ai_family == AF_INET6)
3522 sock_set_v6only(sock);
3523 if (x11_use_localhost)
3524 channel_set_reuseaddr(sock);
3525 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3526 debug2("bind port %d: %.100s", port, strerror(errno));
3529 for (n = 0; n < num_socks; n++) {
3535 socks[num_socks++] = sock;
3536 if (num_socks == NUM_SOCKS)
3539 freeaddrinfo(aitop);
3543 if (display_number >= MAX_DISPLAYS) {
3544 error("Failed to allocate internet-domain X11 display socket.");
3547 /* Start listening for connections on the socket. */
3548 for (n = 0; n < num_socks; n++) {
3550 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3551 error("listen: %.100s", strerror(errno));
3557 /* Allocate a channel for each socket. */
3558 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
3559 for (n = 0; n < num_socks; n++) {
3561 /* Is this really necassary? */
3563 nc = channel_new("x11 listener",
3564 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3565 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
3566 0, "X11 inet listener", 1);
3568 nc = channel_new("x11 listener",
3569 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3570 hpn_buffer_size, CHAN_X11_PACKET_DEFAULT,
3571 0, "X11 inet listener", 1);
3572 nc->single_connection = single_connection;
3573 (*chanids)[n] = nc->self;
3577 /* Return the display number for the DISPLAY environment variable. */
3578 *display_numberp = display_number;
3583 connect_local_xsocket_path(const char *pathname)
3586 struct sockaddr_un addr;
3588 sock = socket(AF_UNIX, SOCK_STREAM, 0);
3590 error("socket: %.100s", strerror(errno));
3591 memset(&addr, 0, sizeof(addr));
3592 addr.sun_family = AF_UNIX;
3593 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
3594 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
3597 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
3602 connect_local_xsocket(u_int dnr)
3605 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
3606 return connect_local_xsocket_path(buf);
3610 x11_connect_display(void)
3612 u_int display_number;
3613 const char *display;
3614 char buf[1024], *cp;
3615 struct addrinfo hints, *ai, *aitop;
3616 char strport[NI_MAXSERV];
3617 int gaierr, sock = 0;
3619 /* Try to open a socket for the local X server. */
3620 display = getenv("DISPLAY");
3622 error("DISPLAY not set.");
3626 * Now we decode the value of the DISPLAY variable and make a
3627 * connection to the real X server.
3630 /* Check if the display is from launchd. */
3632 if (strncmp(display, "/tmp/launch", 11) == 0) {
3633 sock = connect_local_xsocket_path(display);
3637 /* OK, we now have a connection to the display. */
3642 * Check if it is a unix domain socket. Unix domain displays are in
3643 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
3645 if (strncmp(display, "unix:", 5) == 0 ||
3646 display[0] == ':') {
3647 /* Connect to the unix domain socket. */
3648 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
3649 error("Could not parse display number from DISPLAY: %.100s",
3653 /* Create a socket. */
3654 sock = connect_local_xsocket(display_number);
3658 /* OK, we now have a connection to the display. */
3662 * Connect to an inet socket. The DISPLAY value is supposedly
3663 * hostname:d[.s], where hostname may also be numeric IP address.
3665 strlcpy(buf, display, sizeof(buf));
3666 cp = strchr(buf, ':');
3668 error("Could not find ':' in DISPLAY: %.100s", display);
3672 /* buf now contains the host name. But first we parse the display number. */
3673 if (sscanf(cp + 1, "%u", &display_number) != 1) {
3674 error("Could not parse display number from DISPLAY: %.100s",
3679 /* Look up the host address */
3680 memset(&hints, 0, sizeof(hints));
3681 hints.ai_family = IPv4or6;
3682 hints.ai_socktype = SOCK_STREAM;
3683 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
3684 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
3685 error("%.100s: unknown host. (%s)", buf,
3686 ssh_gai_strerror(gaierr));
3689 for (ai = aitop; ai; ai = ai->ai_next) {
3690 /* Create a socket. */
3691 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3693 debug2("socket: %.100s", strerror(errno));
3696 /* Connect it to the display. */
3697 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3698 debug2("connect %.100s port %u: %.100s", buf,
3699 6000 + display_number, strerror(errno));
3706 freeaddrinfo(aitop);
3708 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3717 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3718 * the remote channel number. We should do whatever we want, and respond
3719 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3724 x11_input_open(int type, u_int32_t seq, void *ctxt)
3727 int remote_id, sock = 0;
3730 debug("Received X11 open request.");
3732 remote_id = packet_get_int();
3734 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3735 remote_host = packet_get_string(NULL);
3737 remote_host = xstrdup("unknown (remote did not supply name)");
3741 /* Obtain a connection to the real X display. */
3742 sock = x11_connect_display();
3744 /* Allocate a channel for this connection. */
3745 c = channel_new("connected x11 socket",
3746 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3748 c->remote_id = remote_id;
3753 /* Send refusal to the remote host. */
3754 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3755 packet_put_int(remote_id);
3757 /* Send a confirmation to the remote host. */
3758 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3759 packet_put_int(remote_id);
3760 packet_put_int(c->self);
3765 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3768 deny_input_open(int type, u_int32_t seq, void *ctxt)
3770 int rchan = packet_get_int();
3773 case SSH_SMSG_AGENT_OPEN:
3774 error("Warning: ssh server tried agent forwarding.");
3776 case SSH_SMSG_X11_OPEN:
3777 error("Warning: ssh server tried X11 forwarding.");
3780 error("deny_input_open: type %d", type);
3783 error("Warning: this is probably a break-in attempt by a malicious server.");
3784 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3785 packet_put_int(rchan);
3790 * Requests forwarding of X11 connections, generates fake authentication
3791 * data, and enables authentication spoofing.
3792 * This should be called in the client only.
3795 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3796 const char *proto, const char *data, int want_reply)
3798 u_int data_len = (u_int) strlen(data) / 2;
3805 if (x11_saved_display == NULL)
3806 x11_saved_display = xstrdup(disp);
3807 else if (strcmp(disp, x11_saved_display) != 0) {
3808 error("x11_request_forwarding_with_spoofing: different "
3809 "$DISPLAY already forwarded");
3813 cp = strchr(disp, ':');
3815 cp = strchr(cp, '.');
3817 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3821 if (x11_saved_proto == NULL) {
3822 /* Save protocol name. */
3823 x11_saved_proto = xstrdup(proto);
3825 * Extract real authentication data and generate fake data
3826 * of the same length.
3828 x11_saved_data = xmalloc(data_len);
3829 x11_fake_data = xmalloc(data_len);
3830 for (i = 0; i < data_len; i++) {
3831 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3832 fatal("x11_request_forwarding: bad "
3833 "authentication data: %.100s", data);
3836 x11_saved_data[i] = value;
3837 x11_fake_data[i] = rnd & 0xff;
3840 x11_saved_data_len = data_len;
3841 x11_fake_data_len = data_len;
3844 /* Convert the fake data into hex. */
3845 new_data = tohex(x11_fake_data, data_len);
3847 /* Send the request packet. */
3849 channel_request_start(client_session_id, "x11-req", want_reply);
3850 packet_put_char(0); /* XXX bool single connection */
3852 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3854 packet_put_cstring(proto);
3855 packet_put_cstring(new_data);
3856 packet_put_int(screen_number);
3858 packet_write_wait();
3863 /* -- agent forwarding */
3865 /* Sends a message to the server to request authentication fd forwarding. */
3868 auth_request_forwarding(void)
3870 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3872 packet_write_wait();