1 /* $OpenBSD: channels.c,v 1.318 2012/04/23 08:18:17 djm Exp $ */
4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
5 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
7 * This file contains functions for generic socket connection forwarding.
8 * There is also code for initiating connection forwarding for X11 connections,
9 * arbitrary tcp/ip connections, and the authentication agent connection.
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
17 * SSH2 support added by Markus Friedl.
18 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
19 * Copyright (c) 1999 Dug Song. All rights reserved.
20 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
25 * 1. Redistributions of source code must retain the above copyright
26 * notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 * notice, this list of conditions and the following disclaimer in the
29 * documentation and/or other materials provided with the distribution.
31 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
32 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
33 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
35 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
37 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
38 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
39 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
40 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45 #include <sys/types.h>
46 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
66 #include "openbsd-compat/sys-queue.h"
80 #include "pathnames.h"
85 * Pointer to an array containing all allocated channels. The array is
86 * dynamically extended as needed.
88 static Channel **channels = NULL;
91 * Size of the channel array. All slots of the array must always be
92 * initialized (at least the type field); unused slots set to NULL
94 static u_int channels_alloc = 0;
97 * Maximum file descriptor value used in any of the channels. This is
98 * updated in channel_new.
100 static int channel_max_fd = 0;
103 /* -- tcp forwarding */
106 * Data structure for storing which hosts are permitted for forward requests.
107 * The local sides of any remote forwards are stored in this array to prevent
108 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
109 * network (which might be behind a firewall).
112 char *host_to_connect; /* Connect to 'host'. */
113 u_short port_to_connect; /* Connect to 'port'. */
114 u_short listen_port; /* Remote side should listen port number. */
117 /* List of all permitted host/port pairs to connect by the user. */
118 static ForwardPermission *permitted_opens = NULL;
120 /* List of all permitted host/port pairs to connect by the admin. */
121 static ForwardPermission *permitted_adm_opens = NULL;
123 /* Number of permitted host/port pairs in the array permitted by the user. */
124 static int num_permitted_opens = 0;
126 /* Number of permitted host/port pair in the array permitted by the admin. */
127 static int num_adm_permitted_opens = 0;
129 /* special-case port number meaning allow any port */
130 #define FWD_PERMIT_ANY_PORT 0
133 * If this is true, all opens are permitted. This is the case on the server
134 * on which we have to trust the client anyway, and the user could do
135 * anything after logging in anyway.
137 static int all_opens_permitted = 0;
140 /* -- X11 forwarding */
142 /* Maximum number of fake X11 displays to try. */
143 #define MAX_DISPLAYS 1000
145 /* Saved X11 local (client) display. */
146 static char *x11_saved_display = NULL;
148 /* Saved X11 authentication protocol name. */
149 static char *x11_saved_proto = NULL;
151 /* Saved X11 authentication data. This is the real data. */
152 static char *x11_saved_data = NULL;
153 static u_int x11_saved_data_len = 0;
156 * Fake X11 authentication data. This is what the server will be sending us;
157 * we should replace any occurrences of this by the real data.
159 static u_char *x11_fake_data = NULL;
160 static u_int x11_fake_data_len;
163 /* -- agent forwarding */
167 /* AF_UNSPEC or AF_INET or AF_INET6 */
168 static int IPv4or6 = AF_UNSPEC;
171 static void port_open_helper(Channel *c, char *rtype);
173 /* non-blocking connect helpers */
174 static int connect_next(struct channel_connect *);
175 static void channel_connect_ctx_free(struct channel_connect *);
179 static int hpn_disabled = 0;
180 static u_int buffer_size = CHAN_HPN_MIN_WINDOW_DEFAULT;
182 /* -- 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->dynamic_window = 0;
325 c->local_window = window;
326 c->local_window_max = window;
327 c->local_consumed = 0;
328 c->local_maxpacket = maxpack;
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);
829 channel_tcpwinsz(void)
836 /* If we are not on a socket return 128KB. */
837 if (!packet_connection_is_on_socket())
841 optsz = sizeof(tcpwinsz);
842 sd = packet_get_connection_in();
843 ret = getsockopt(sd, SOL_SOCKET, SO_RCVBUF, &tcpwinsz, &optsz);
845 /* Return no more than the maximum buffer size. */
846 maxlen = buffer_get_max_len();
847 if ((ret == 0) && tcpwinsz > maxlen)
849 /* In case getsockopt() failed return a minimum. */
851 tcpwinsz = CHAN_TCP_WINDOW_DEFAULT;
852 debug2("tcpwinsz: %d for connection: %d", tcpwinsz, sd);
857 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
861 /* Check buffer limits. */
862 if (!c->tcpwinsz || c->dynamic_window > 0)
863 c->tcpwinsz = channel_tcpwinsz();
865 limit = MIN(compat20 ? c->remote_window : packet_get_maxsize(),
868 if (c->istate == CHAN_INPUT_OPEN &&
870 buffer_len(&c->input) < limit &&
871 buffer_check_alloc(&c->input, CHAN_RBUF))
872 FD_SET(c->rfd, readset);
873 if (c->ostate == CHAN_OUTPUT_OPEN ||
874 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
875 if (buffer_len(&c->output) > 0) {
876 FD_SET(c->wfd, writeset);
877 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
878 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
879 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
880 c->self, c->efd, buffer_len(&c->extended));
885 /** XXX check close conditions, too */
886 if (compat20 && c->efd != -1 &&
887 !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
888 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
889 buffer_len(&c->extended) > 0)
890 FD_SET(c->efd, writeset);
891 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
892 (c->extended_usage == CHAN_EXTENDED_READ ||
893 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
894 buffer_len(&c->extended) < c->remote_window)
895 FD_SET(c->efd, readset);
897 /* XXX: What about efd? races? */
902 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
904 if (buffer_len(&c->input) == 0) {
905 packet_start(SSH_MSG_CHANNEL_CLOSE);
906 packet_put_int(c->remote_id);
908 c->type = SSH_CHANNEL_CLOSED;
909 debug2("channel %d: closing after input drain.", c->self);
915 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
917 if (buffer_len(&c->output) == 0)
920 FD_SET(c->sock, writeset);
924 * This is a special state for X11 authentication spoofing. An opened X11
925 * connection (when authentication spoofing is being done) remains in this
926 * state until the first packet has been completely read. The authentication
927 * data in that packet is then substituted by the real data if it matches the
928 * fake data, and the channel is put into normal mode.
929 * XXX All this happens at the client side.
930 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
933 x11_open_helper(Buffer *b)
936 u_int proto_len, data_len;
938 /* Check if the fixed size part of the packet is in buffer. */
939 if (buffer_len(b) < 12)
942 /* Parse the lengths of variable-length fields. */
944 if (ucp[0] == 0x42) { /* Byte order MSB first. */
945 proto_len = 256 * ucp[6] + ucp[7];
946 data_len = 256 * ucp[8] + ucp[9];
947 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
948 proto_len = ucp[6] + 256 * ucp[7];
949 data_len = ucp[8] + 256 * ucp[9];
951 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
956 /* Check if the whole packet is in buffer. */
958 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
961 /* Check if authentication protocol matches. */
962 if (proto_len != strlen(x11_saved_proto) ||
963 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
964 debug2("X11 connection uses different authentication protocol.");
967 /* Check if authentication data matches our fake data. */
968 if (data_len != x11_fake_data_len ||
969 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
970 x11_fake_data, x11_fake_data_len) != 0) {
971 debug2("X11 auth data does not match fake data.");
974 /* Check fake data length */
975 if (x11_fake_data_len != x11_saved_data_len) {
976 error("X11 fake_data_len %d != saved_data_len %d",
977 x11_fake_data_len, x11_saved_data_len);
981 * Received authentication protocol and data match
982 * our fake data. Substitute the fake data with real
985 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
986 x11_saved_data, x11_saved_data_len);
991 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
993 int ret = x11_open_helper(&c->output);
996 /* Start normal processing for the channel. */
997 c->type = SSH_CHANNEL_OPEN;
998 channel_pre_open_13(c, readset, writeset);
999 } else if (ret == -1) {
1001 * We have received an X11 connection that has bad
1002 * authentication information.
1004 logit("X11 connection rejected because of wrong authentication.");
1005 buffer_clear(&c->input);
1006 buffer_clear(&c->output);
1007 channel_close_fd(&c->sock);
1009 c->type = SSH_CHANNEL_CLOSED;
1010 packet_start(SSH_MSG_CHANNEL_CLOSE);
1011 packet_put_int(c->remote_id);
1017 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
1019 int ret = x11_open_helper(&c->output);
1021 /* c->force_drain = 1; */
1024 c->type = SSH_CHANNEL_OPEN;
1025 channel_pre_open(c, readset, writeset);
1026 } else if (ret == -1) {
1027 logit("X11 connection rejected because of wrong authentication.");
1028 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1029 chan_read_failed(c);
1030 buffer_clear(&c->input);
1032 buffer_clear(&c->output);
1033 /* for proto v1, the peer will send an IEOF */
1035 chan_write_failed(c);
1037 c->type = SSH_CHANNEL_OPEN;
1038 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1043 channel_pre_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1045 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1046 buffer_check_alloc(&c->input, CHAN_RBUF))
1047 FD_SET(c->rfd, readset);
1048 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1049 /* clear buffer immediately (discard any partial packet) */
1050 buffer_clear(&c->input);
1052 /* Start output drain. XXX just kill chan? */
1053 chan_rcvd_oclose(c);
1055 if (c->ostate == CHAN_OUTPUT_OPEN ||
1056 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1057 if (buffer_len(&c->output) > 0)
1058 FD_SET(c->wfd, writeset);
1059 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1064 /* try to decode a socks4 header */
1067 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
1070 u_int len, have, i, found, need;
1075 u_int16_t dest_port;
1076 struct in_addr dest_addr;
1079 debug2("channel %d: decode socks4", c->self);
1081 have = buffer_len(&c->input);
1082 len = sizeof(s4_req);
1085 p = buffer_ptr(&c->input);
1088 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1089 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1090 debug2("channel %d: socks4a request", c->self);
1091 /* ... and needs an extra string (the hostname) */
1094 /* Check for terminating NUL on the string(s) */
1095 for (found = 0, i = len; i < have; i++) {
1102 /* the peer is probably sending garbage */
1103 debug("channel %d: decode socks4: too long",
1110 buffer_get(&c->input, (char *)&s4_req.version, 1);
1111 buffer_get(&c->input, (char *)&s4_req.command, 1);
1112 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1113 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1114 have = buffer_len(&c->input);
1115 p = buffer_ptr(&c->input);
1117 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1118 len++; /* trailing '\0' */
1120 fatal("channel %d: decode socks4: len %d > have %d",
1121 c->self, len, have);
1122 strlcpy(username, p, sizeof(username));
1123 buffer_consume(&c->input, len);
1125 if (c->path != NULL) {
1129 if (need == 1) { /* SOCKS4: one string */
1130 host = inet_ntoa(s4_req.dest_addr);
1131 c->path = xstrdup(host);
1132 } else { /* SOCKS4A: two strings */
1133 have = buffer_len(&c->input);
1134 p = buffer_ptr(&c->input);
1136 debug2("channel %d: decode socks4a: host %s/%d",
1138 len++; /* trailing '\0' */
1140 fatal("channel %d: decode socks4a: len %d > have %d",
1141 c->self, len, have);
1142 if (len > NI_MAXHOST) {
1143 error("channel %d: hostname \"%.100s\" too long",
1147 c->path = xstrdup(p);
1148 buffer_consume(&c->input, len);
1150 c->host_port = ntohs(s4_req.dest_port);
1152 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1153 c->self, c->path, c->host_port, s4_req.command);
1155 if (s4_req.command != 1) {
1156 debug("channel %d: cannot handle: %s cn %d",
1157 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1160 s4_rsp.version = 0; /* vn: 0 for reply */
1161 s4_rsp.command = 90; /* cd: req granted */
1162 s4_rsp.dest_port = 0; /* ignored */
1163 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1164 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1168 /* try to decode a socks5 header */
1169 #define SSH_SOCKS5_AUTHDONE 0x1000
1170 #define SSH_SOCKS5_NOAUTH 0x00
1171 #define SSH_SOCKS5_IPV4 0x01
1172 #define SSH_SOCKS5_DOMAIN 0x03
1173 #define SSH_SOCKS5_IPV6 0x04
1174 #define SSH_SOCKS5_CONNECT 0x01
1175 #define SSH_SOCKS5_SUCCESS 0x00
1179 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1187 u_int16_t dest_port;
1188 u_char *p, dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
1189 u_int have, need, i, found, nmethods, addrlen, af;
1191 debug2("channel %d: decode socks5", c->self);
1192 p = buffer_ptr(&c->input);
1195 have = buffer_len(&c->input);
1196 if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
1197 /* format: ver | nmethods | methods */
1201 if (have < nmethods + 2)
1203 /* look for method: "NO AUTHENTICATION REQUIRED" */
1204 for (found = 0, i = 2; i < nmethods + 2; i++) {
1205 if (p[i] == SSH_SOCKS5_NOAUTH) {
1211 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1215 buffer_consume(&c->input, nmethods + 2);
1216 buffer_put_char(&c->output, 0x05); /* version */
1217 buffer_put_char(&c->output, SSH_SOCKS5_NOAUTH); /* method */
1218 FD_SET(c->sock, writeset);
1219 c->flags |= SSH_SOCKS5_AUTHDONE;
1220 debug2("channel %d: socks5 auth done", c->self);
1221 return 0; /* need more */
1223 debug2("channel %d: socks5 post auth", c->self);
1224 if (have < sizeof(s5_req)+1)
1225 return 0; /* need more */
1226 memcpy(&s5_req, p, sizeof(s5_req));
1227 if (s5_req.version != 0x05 ||
1228 s5_req.command != SSH_SOCKS5_CONNECT ||
1229 s5_req.reserved != 0x00) {
1230 debug2("channel %d: only socks5 connect supported", c->self);
1233 switch (s5_req.atyp){
1234 case SSH_SOCKS5_IPV4:
1238 case SSH_SOCKS5_DOMAIN:
1239 addrlen = p[sizeof(s5_req)];
1242 case SSH_SOCKS5_IPV6:
1247 debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
1250 need = sizeof(s5_req) + addrlen + 2;
1251 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1255 buffer_consume(&c->input, sizeof(s5_req));
1256 if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
1257 buffer_consume(&c->input, 1); /* host string length */
1258 buffer_get(&c->input, (char *)&dest_addr, addrlen);
1259 buffer_get(&c->input, (char *)&dest_port, 2);
1260 dest_addr[addrlen] = '\0';
1261 if (c->path != NULL) {
1265 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1266 if (addrlen >= NI_MAXHOST) {
1267 error("channel %d: dynamic request: socks5 hostname "
1268 "\"%.100s\" too long", c->self, dest_addr);
1271 c->path = xstrdup(dest_addr);
1273 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1275 c->path = xstrdup(ntop);
1277 c->host_port = ntohs(dest_port);
1279 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1280 c->self, c->path, c->host_port, s5_req.command);
1282 s5_rsp.version = 0x05;
1283 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1284 s5_rsp.reserved = 0; /* ignored */
1285 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1286 ((struct in_addr *)&dest_addr)->s_addr = INADDR_ANY;
1287 dest_port = 0; /* ignored */
1289 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1290 buffer_append(&c->output, &dest_addr, sizeof(struct in_addr));
1291 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1296 channel_connect_stdio_fwd(const char *host_to_connect, u_short port_to_connect,
1301 debug("channel_connect_stdio_fwd %s:%d", host_to_connect,
1304 c = channel_new("stdio-forward", SSH_CHANNEL_OPENING, in, out,
1305 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1306 0, "stdio-forward", /*nonblock*/0);
1308 c->path = xstrdup(host_to_connect);
1309 c->host_port = port_to_connect;
1310 c->listening_port = 0;
1313 channel_register_fds(c, in, out, -1, 0, 1, 0);
1314 port_open_helper(c, "direct-tcpip");
1319 /* dynamic port forwarding */
1321 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1327 have = buffer_len(&c->input);
1328 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1329 /* buffer_dump(&c->input); */
1330 /* check if the fixed size part of the packet is in buffer. */
1333 FD_SET(c->sock, readset);
1336 /* try to guess the protocol */
1337 p = buffer_ptr(&c->input);
1340 ret = channel_decode_socks4(c, readset, writeset);
1343 ret = channel_decode_socks5(c, readset, writeset);
1351 } else if (ret == 0) {
1352 debug2("channel %d: pre_dynamic: need more", c->self);
1354 FD_SET(c->sock, readset);
1356 /* switch to the next state */
1357 c->type = SSH_CHANNEL_OPENING;
1358 port_open_helper(c, "direct-tcpip");
1362 /* This is our fake X11 server socket. */
1365 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1368 struct sockaddr_storage addr;
1371 char buf[16384], *remote_ipaddr;
1374 if (FD_ISSET(c->sock, readset)) {
1375 debug("X11 connection requested.");
1376 addrlen = sizeof(addr);
1377 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1378 if (c->single_connection) {
1379 debug2("single_connection: closing X11 listener.");
1380 channel_close_fd(&c->sock);
1384 error("accept: %.100s", strerror(errno));
1385 if (errno == EMFILE || errno == ENFILE)
1386 c->notbefore = time(NULL) + 1;
1389 set_nodelay(newsock);
1390 remote_ipaddr = get_peer_ipaddr(newsock);
1391 remote_port = get_peer_port(newsock);
1392 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1393 remote_ipaddr, remote_port);
1395 nc = channel_new("accepted x11 socket",
1396 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1397 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1399 packet_start(SSH2_MSG_CHANNEL_OPEN);
1400 packet_put_cstring("x11");
1401 packet_put_int(nc->self);
1402 packet_put_int(nc->local_window_max);
1403 packet_put_int(nc->local_maxpacket);
1404 /* originator ipaddr and port */
1405 packet_put_cstring(remote_ipaddr);
1406 if (datafellows & SSH_BUG_X11FWD) {
1407 debug2("ssh2 x11 bug compat mode");
1409 packet_put_int(remote_port);
1413 packet_start(SSH_SMSG_X11_OPEN);
1414 packet_put_int(nc->self);
1415 if (packet_get_protocol_flags() &
1416 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1417 packet_put_cstring(buf);
1420 xfree(remote_ipaddr);
1425 port_open_helper(Channel *c, char *rtype)
1429 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1430 int remote_port = get_peer_port(c->sock);
1432 if (remote_port == -1) {
1433 /* Fake addr/port to appease peers that validate it (Tectia) */
1434 xfree(remote_ipaddr);
1435 remote_ipaddr = xstrdup("127.0.0.1");
1436 remote_port = 65535;
1439 direct = (strcmp(rtype, "direct-tcpip") == 0);
1441 snprintf(buf, sizeof buf,
1442 "%s: listening port %d for %.100s port %d, "
1443 "connect from %.200s port %d",
1444 rtype, c->listening_port, c->path, c->host_port,
1445 remote_ipaddr, remote_port);
1447 xfree(c->remote_name);
1448 c->remote_name = xstrdup(buf);
1451 packet_start(SSH2_MSG_CHANNEL_OPEN);
1452 packet_put_cstring(rtype);
1453 packet_put_int(c->self);
1454 packet_put_int(c->local_window_max);
1455 packet_put_int(c->local_maxpacket);
1457 /* target host, port */
1458 packet_put_cstring(c->path);
1459 packet_put_int(c->host_port);
1461 /* listen address, port */
1462 packet_put_cstring(c->path);
1463 packet_put_int(c->listening_port);
1465 /* originator host and port */
1466 packet_put_cstring(remote_ipaddr);
1467 packet_put_int((u_int)remote_port);
1470 packet_start(SSH_MSG_PORT_OPEN);
1471 packet_put_int(c->self);
1472 packet_put_cstring(c->path);
1473 packet_put_int(c->host_port);
1474 if (packet_get_protocol_flags() &
1475 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1476 packet_put_cstring(c->remote_name);
1479 xfree(remote_ipaddr);
1483 channel_set_reuseaddr(int fd)
1488 * Set socket options.
1489 * Allow local port reuse in TIME_WAIT.
1491 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1492 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1496 * This socket is listening for connections to a forwarded TCP/IP port.
1500 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1503 struct sockaddr_storage addr;
1504 int newsock, nextstate;
1508 if (FD_ISSET(c->sock, readset)) {
1509 debug("Connection to port %d forwarding "
1510 "to %.100s port %d requested.",
1511 c->listening_port, c->path, c->host_port);
1513 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1514 nextstate = SSH_CHANNEL_OPENING;
1515 rtype = "forwarded-tcpip";
1517 if (c->host_port == 0) {
1518 nextstate = SSH_CHANNEL_DYNAMIC;
1519 rtype = "dynamic-tcpip";
1521 nextstate = SSH_CHANNEL_OPENING;
1522 rtype = "direct-tcpip";
1526 addrlen = sizeof(addr);
1527 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1529 error("accept: %.100s", strerror(errno));
1530 if (errno == EMFILE || errno == ENFILE)
1531 c->notbefore = time(NULL) + 1;
1534 set_nodelay(newsock);
1535 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1536 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1537 nc->listening_port = c->listening_port;
1538 nc->host_port = c->host_port;
1539 if (c->path != NULL)
1540 nc->path = xstrdup(c->path);
1542 if (nextstate != SSH_CHANNEL_DYNAMIC)
1543 port_open_helper(nc, rtype);
1548 * This is the authentication agent socket listening for connections from
1553 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1557 struct sockaddr_storage addr;
1560 if (FD_ISSET(c->sock, readset)) {
1561 addrlen = sizeof(addr);
1562 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1564 error("accept from auth socket: %.100s",
1566 if (errno == EMFILE || errno == ENFILE)
1567 c->notbefore = time(NULL) + 1;
1570 nc = channel_new("accepted auth socket",
1571 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1572 c->local_window_max, c->local_maxpacket,
1573 0, "accepted auth socket", 1);
1575 packet_start(SSH2_MSG_CHANNEL_OPEN);
1576 packet_put_cstring("auth-agent@openssh.com");
1577 packet_put_int(nc->self);
1578 packet_put_int(c->local_window_max);
1579 packet_put_int(c->local_maxpacket);
1581 packet_start(SSH_SMSG_AGENT_OPEN);
1582 packet_put_int(nc->self);
1590 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1593 socklen_t sz = sizeof(err);
1595 if (FD_ISSET(c->sock, writeset)) {
1596 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1598 error("getsockopt SO_ERROR failed");
1601 debug("channel %d: connected to %s port %d",
1602 c->self, c->connect_ctx.host, c->connect_ctx.port);
1603 channel_connect_ctx_free(&c->connect_ctx);
1604 c->type = SSH_CHANNEL_OPEN;
1606 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1607 packet_put_int(c->remote_id);
1608 packet_put_int(c->self);
1609 packet_put_int(c->local_window);
1610 packet_put_int(c->local_maxpacket);
1612 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1613 packet_put_int(c->remote_id);
1614 packet_put_int(c->self);
1617 debug("channel %d: connection failed: %s",
1618 c->self, strerror(err));
1619 /* Try next address, if any */
1620 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1622 c->sock = c->rfd = c->wfd = sock;
1623 channel_max_fd = channel_find_maxfd();
1626 /* Exhausted all addresses */
1627 error("connect_to %.100s port %d: failed.",
1628 c->connect_ctx.host, c->connect_ctx.port);
1629 channel_connect_ctx_free(&c->connect_ctx);
1631 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1632 packet_put_int(c->remote_id);
1633 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1634 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1635 packet_put_cstring(strerror(err));
1636 packet_put_cstring("");
1639 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1640 packet_put_int(c->remote_id);
1650 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1652 char buf[CHAN_RBUF];
1655 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1656 if (c->rfd != -1 && (force || FD_ISSET(c->rfd, readset))) {
1658 len = read(c->rfd, buf, sizeof(buf));
1659 if (len < 0 && (errno == EINTR ||
1660 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1662 #ifndef PTY_ZEROREAD
1665 if ((!c->isatty && len <= 0) ||
1666 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1668 debug2("channel %d: read<=0 rfd %d len %d",
1669 c->self, c->rfd, len);
1670 if (c->type != SSH_CHANNEL_OPEN) {
1671 debug2("channel %d: not open", c->self);
1674 } else if (compat13) {
1675 buffer_clear(&c->output);
1676 c->type = SSH_CHANNEL_INPUT_DRAINING;
1677 debug2("channel %d: input draining.", c->self);
1679 chan_read_failed(c);
1683 if (c->input_filter != NULL) {
1684 if (c->input_filter(c, buf, len) == -1) {
1685 debug2("channel %d: filter stops", c->self);
1686 chan_read_failed(c);
1688 } else if (c->datagram) {
1689 buffer_put_string(&c->input, buf, len);
1691 buffer_append(&c->input, buf, len);
1699 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1702 u_char *data = NULL, *buf;
1703 u_int dlen, olen = 0;
1706 /* Send buffered output data to the socket. */
1708 FD_ISSET(c->wfd, writeset) &&
1709 buffer_len(&c->output) > 0) {
1710 olen = buffer_len(&c->output);
1711 if (c->output_filter != NULL) {
1712 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1713 debug2("channel %d: filter stops", c->self);
1714 if (c->type != SSH_CHANNEL_OPEN)
1717 chan_write_failed(c);
1720 } else if (c->datagram) {
1721 buf = data = buffer_get_string(&c->output, &dlen);
1723 buf = data = buffer_ptr(&c->output);
1724 dlen = buffer_len(&c->output);
1728 /* ignore truncated writes, datagrams might get lost */
1729 len = write(c->wfd, buf, dlen);
1731 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1732 errno == EWOULDBLOCK))
1735 if (c->type != SSH_CHANNEL_OPEN)
1738 chan_write_failed(c);
1744 /* XXX: Later AIX versions can't push as much data to tty */
1745 if (compat20 && c->wfd_isatty)
1746 dlen = MIN(dlen, 8*1024);
1749 len = write(c->wfd, buf, dlen);
1751 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
1754 if (c->type != SSH_CHANNEL_OPEN) {
1755 debug2("channel %d: not open", c->self);
1758 } else if (compat13) {
1759 buffer_clear(&c->output);
1760 debug2("channel %d: input draining.", c->self);
1761 c->type = SSH_CHANNEL_INPUT_DRAINING;
1763 chan_write_failed(c);
1767 #ifndef BROKEN_TCGETATTR_ICANON
1768 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1769 if (tcgetattr(c->wfd, &tio) == 0 &&
1770 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1772 * Simulate echo to reduce the impact of
1773 * traffic analysis. We need to match the
1774 * size of a SSH2_MSG_CHANNEL_DATA message
1775 * (4 byte channel id + buf)
1777 packet_send_ignore(4 + len);
1782 buffer_consume(&c->output, len);
1785 if (compat20 && olen > 0)
1786 c->local_consumed += olen - buffer_len(&c->output);
1791 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1793 char buf[CHAN_RBUF];
1796 /** XXX handle drain efd, too */
1798 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1799 FD_ISSET(c->efd, writeset) &&
1800 buffer_len(&c->extended) > 0) {
1801 len = write(c->efd, buffer_ptr(&c->extended),
1802 buffer_len(&c->extended));
1803 debug2("channel %d: written %d to efd %d",
1804 c->self, len, c->efd);
1805 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1806 errno == EWOULDBLOCK))
1809 debug2("channel %d: closing write-efd %d",
1811 channel_close_fd(&c->efd);
1813 buffer_consume(&c->extended, len);
1814 c->local_consumed += len;
1816 } else if (c->efd != -1 &&
1817 (c->extended_usage == CHAN_EXTENDED_READ ||
1818 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1819 (c->detach_close || FD_ISSET(c->efd, readset))) {
1820 len = read(c->efd, buf, sizeof(buf));
1821 debug2("channel %d: read %d from efd %d",
1822 c->self, len, c->efd);
1823 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
1824 errno == EWOULDBLOCK) && !c->detach_close)))
1827 debug2("channel %d: closing read-efd %d",
1829 channel_close_fd(&c->efd);
1831 if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
1832 debug3("channel %d: discard efd",
1835 buffer_append(&c->extended, buf, len);
1843 channel_check_window(Channel *c)
1845 if (c->type == SSH_CHANNEL_OPEN &&
1846 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1847 ((c->local_window_max - c->local_window >
1848 c->local_maxpacket*3) ||
1849 c->local_window < c->local_window_max/2) &&
1850 c->local_consumed > 0) {
1853 /* Adjust max window size if we are in a dynamic environment. */
1854 if (c->dynamic_window && c->tcpwinsz > c->local_window_max) {
1856 * Grow the window somewhat aggressively to maintain
1859 addition = 1.5 * (c->tcpwinsz - c->local_window_max);
1860 c->local_window_max += addition;
1862 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1863 packet_put_int(c->remote_id);
1864 packet_put_int(c->local_consumed + addition);
1866 debug2("channel %d: window %d sent adjust %d",
1867 c->self, c->local_window,
1869 c->local_window += c->local_consumed + addition;
1870 c->local_consumed = 0;
1876 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1878 channel_handle_rfd(c, readset, writeset);
1879 channel_handle_wfd(c, readset, writeset);
1882 channel_handle_efd(c, readset, writeset);
1883 channel_check_window(c);
1887 read_mux(Channel *c, u_int need)
1889 char buf[CHAN_RBUF];
1893 if (buffer_len(&c->input) < need) {
1894 rlen = need - buffer_len(&c->input);
1895 len = read(c->rfd, buf, MIN(rlen, CHAN_RBUF));
1897 if (errno != EINTR && errno != EAGAIN) {
1898 debug2("channel %d: ctl read<=0 rfd %d len %d",
1899 c->self, c->rfd, len);
1900 chan_read_failed(c);
1904 buffer_append(&c->input, buf, len);
1906 return buffer_len(&c->input);
1910 channel_post_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1916 fatal("%s: entered with !compat20", __func__);
1918 if (c->rfd != -1 && !c->mux_pause && FD_ISSET(c->rfd, readset) &&
1919 (c->istate == CHAN_INPUT_OPEN ||
1920 c->istate == CHAN_INPUT_WAIT_DRAIN)) {
1922 * Don't not read past the precise end of packets to
1923 * avoid disrupting fd passing.
1925 if (read_mux(c, 4) < 4) /* read header */
1927 need = get_u32(buffer_ptr(&c->input));
1928 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
1929 if (need > CHANNEL_MUX_MAX_PACKET) {
1930 debug2("channel %d: packet too big %u > %u",
1931 c->self, CHANNEL_MUX_MAX_PACKET, need);
1932 chan_rcvd_oclose(c);
1935 if (read_mux(c, need + 4) < need + 4) /* read body */
1937 if (c->mux_rcb(c) != 0) {
1938 debug("channel %d: mux_rcb failed", c->self);
1944 if (c->wfd != -1 && FD_ISSET(c->wfd, writeset) &&
1945 buffer_len(&c->output) > 0) {
1946 len = write(c->wfd, buffer_ptr(&c->output),
1947 buffer_len(&c->output));
1948 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1954 buffer_consume(&c->output, len);
1959 channel_post_mux_listener(Channel *c, fd_set *readset, fd_set *writeset)
1962 struct sockaddr_storage addr;
1968 if (!FD_ISSET(c->sock, readset))
1971 debug("multiplexing control connection");
1974 * Accept connection on control socket
1976 memset(&addr, 0, sizeof(addr));
1977 addrlen = sizeof(addr);
1978 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
1980 error("%s accept: %s", __func__, strerror(errno));
1981 if (errno == EMFILE || errno == ENFILE)
1982 c->notbefore = time(NULL) + 1;
1986 if (getpeereid(newsock, &euid, &egid) < 0) {
1987 error("%s getpeereid failed: %s", __func__,
1992 if ((euid != 0) && (getuid() != euid)) {
1993 error("multiplex uid mismatch: peer euid %u != uid %u",
1994 (u_int)euid, (u_int)getuid());
1998 nc = channel_new("multiplex client", SSH_CHANNEL_MUX_CLIENT,
1999 newsock, newsock, -1, c->local_window_max,
2000 c->local_maxpacket, 0, "mux-control", 1);
2001 nc->mux_rcb = c->mux_rcb;
2002 debug3("%s: new mux channel %d fd %d", __func__,
2003 nc->self, nc->sock);
2004 /* establish state */
2006 /* mux state transitions must not elicit protocol messages */
2007 nc->flags |= CHAN_LOCAL;
2012 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
2016 /* Send buffered output data to the socket. */
2017 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
2018 len = write(c->sock, buffer_ptr(&c->output),
2019 buffer_len(&c->output));
2021 buffer_clear(&c->output);
2023 buffer_consume(&c->output, len);
2028 channel_handler_init_20(void)
2030 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2031 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2032 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2033 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2034 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2035 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2036 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2037 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2038 channel_pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2039 channel_pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2041 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2042 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2043 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2044 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2045 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2046 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2047 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2048 channel_post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2049 channel_post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2053 channel_handler_init_13(void)
2055 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
2056 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
2057 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2058 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2059 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2060 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
2061 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
2062 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2063 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2065 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2066 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2067 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2068 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2069 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
2070 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2071 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2075 channel_handler_init_15(void)
2077 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2078 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2079 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2080 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2081 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2082 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2083 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2085 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2086 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2087 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2088 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2089 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2090 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2094 channel_handler_init(void)
2098 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
2099 channel_pre[i] = NULL;
2100 channel_post[i] = NULL;
2103 channel_handler_init_20();
2105 channel_handler_init_13();
2107 channel_handler_init_15();
2110 /* gc dead channels */
2112 channel_garbage_collect(Channel *c)
2116 if (c->detach_user != NULL) {
2117 if (!chan_is_dead(c, c->detach_close))
2119 debug2("channel %d: gc: notify user", c->self);
2120 c->detach_user(c->self, NULL);
2121 /* if we still have a callback */
2122 if (c->detach_user != NULL)
2124 debug2("channel %d: gc: user detached", c->self);
2126 if (!chan_is_dead(c, 1))
2128 debug2("channel %d: garbage collecting", c->self);
2133 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset,
2134 time_t *unpause_secs)
2136 static int did_init = 0;
2142 channel_handler_init();
2146 if (unpause_secs != NULL)
2148 for (i = 0, oalloc = channels_alloc; i < oalloc; i++) {
2153 if (ftab == channel_pre)
2158 if (ftab[c->type] != NULL) {
2160 * Run handlers that are not paused.
2162 if (c->notbefore <= now)
2163 (*ftab[c->type])(c, readset, writeset);
2164 else if (unpause_secs != NULL) {
2166 * Collect the time that the earliest
2167 * channel comes off pause.
2169 debug3("%s: chan %d: skip for %d more seconds",
2171 (int)(c->notbefore - now));
2172 if (*unpause_secs == 0 ||
2173 (c->notbefore - now) < *unpause_secs)
2174 *unpause_secs = c->notbefore - now;
2177 channel_garbage_collect(c);
2179 if (unpause_secs != NULL && *unpause_secs != 0)
2180 debug3("%s: first channel unpauses in %d seconds",
2181 __func__, (int)*unpause_secs);
2185 * Allocate/update select bitmasks and add any bits relevant to channels in
2189 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
2190 u_int *nallocp, time_t *minwait_secs, int rekeying)
2192 u_int n, sz, nfdset;
2194 n = MAX(*maxfdp, channel_max_fd);
2196 nfdset = howmany(n+1, NFDBITS);
2197 /* Explicitly test here, because xrealloc isn't always called */
2198 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
2199 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2200 sz = nfdset * sizeof(fd_mask);
2202 /* perhaps check sz < nalloc/2 and shrink? */
2203 if (*readsetp == NULL || sz > *nallocp) {
2204 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
2205 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
2209 memset(*readsetp, 0, sz);
2210 memset(*writesetp, 0, sz);
2213 channel_handler(channel_pre, *readsetp, *writesetp,
2218 * After select, perform any appropriate operations for channels which have
2222 channel_after_select(fd_set *readset, fd_set *writeset)
2224 channel_handler(channel_post, readset, writeset, NULL);
2228 /* If there is data to send to the connection, enqueue some of it now. */
2230 channel_output_poll(void)
2235 for (i = 0; i < channels_alloc; i++) {
2241 * We are only interested in channels that can have buffered
2245 if (c->type != SSH_CHANNEL_OPEN &&
2246 c->type != SSH_CHANNEL_INPUT_DRAINING)
2249 if (c->type != SSH_CHANNEL_OPEN)
2253 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2254 /* XXX is this true? */
2255 debug3("channel %d: will not send data after close", c->self);
2259 /* Get the amount of buffered data for this channel. */
2260 if ((c->istate == CHAN_INPUT_OPEN ||
2261 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
2262 (len = buffer_len(&c->input)) > 0) {
2268 data = buffer_get_string(&c->input,
2270 if (dlen > c->remote_window ||
2271 dlen > c->remote_maxpacket) {
2272 debug("channel %d: datagram "
2273 "too big for channel",
2278 packet_start(SSH2_MSG_CHANNEL_DATA);
2279 packet_put_int(c->remote_id);
2280 packet_put_string(data, dlen);
2282 c->remote_window -= dlen + 4;
2288 * Send some data for the other side over the secure
2292 if (len > c->remote_window)
2293 len = c->remote_window;
2294 if (len > c->remote_maxpacket)
2295 len = c->remote_maxpacket;
2297 if (packet_is_interactive()) {
2301 /* Keep the packets at reasonable size. */
2302 if (len > packet_get_maxsize()/2)
2303 len = packet_get_maxsize()/2;
2307 packet_start(compat20 ?
2308 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
2309 packet_put_int(c->remote_id);
2310 packet_put_string(buffer_ptr(&c->input), len);
2312 buffer_consume(&c->input, len);
2313 c->remote_window -= len;
2315 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2317 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2319 * input-buffer is empty and read-socket shutdown:
2320 * tell peer, that we will not send more data: send IEOF.
2321 * hack for extended data: delay EOF if EFD still in use.
2323 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2324 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2325 c->self, c->efd, buffer_len(&c->extended));
2329 /* Send extended data, i.e. stderr */
2331 !(c->flags & CHAN_EOF_SENT) &&
2332 c->remote_window > 0 &&
2333 (len = buffer_len(&c->extended)) > 0 &&
2334 c->extended_usage == CHAN_EXTENDED_READ) {
2335 debug2("channel %d: rwin %u elen %u euse %d",
2336 c->self, c->remote_window, buffer_len(&c->extended),
2338 if (len > c->remote_window)
2339 len = c->remote_window;
2340 if (len > c->remote_maxpacket)
2341 len = c->remote_maxpacket;
2342 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
2343 packet_put_int(c->remote_id);
2344 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
2345 packet_put_string(buffer_ptr(&c->extended), len);
2347 buffer_consume(&c->extended, len);
2348 c->remote_window -= len;
2349 debug2("channel %d: sent ext data %d", c->self, len);
2355 /* -- protocol input */
2359 channel_input_data(int type, u_int32_t seq, void *ctxt)
2363 u_int data_len, win_len;
2366 /* Get the channel number and verify it. */
2367 id = packet_get_int();
2368 c = channel_lookup(id);
2370 packet_disconnect("Received data for nonexistent channel %d.", id);
2372 /* Ignore any data for non-open channels (might happen on close) */
2373 if (c->type != SSH_CHANNEL_OPEN &&
2374 c->type != SSH_CHANNEL_X11_OPEN)
2378 data = packet_get_string_ptr(&data_len);
2381 win_len += 4; /* string length header */
2384 * Ignore data for protocol > 1.3 if output end is no longer open.
2385 * For protocol 2 the sending side is reducing its window as it sends
2386 * data, so we must 'fake' consumption of the data in order to ensure
2387 * that window updates are sent back. Otherwise the connection might
2390 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2392 c->local_window -= win_len;
2393 c->local_consumed += win_len;
2399 if (win_len > c->local_maxpacket) {
2400 logit("channel %d: rcvd big packet %d, maxpack %d",
2401 c->self, win_len, c->local_maxpacket);
2403 if (win_len > c->local_window) {
2404 logit("channel %d: rcvd too much data %d, win %d",
2405 c->self, win_len, c->local_window);
2408 c->local_window -= win_len;
2411 buffer_put_string(&c->output, data, data_len);
2413 buffer_append(&c->output, data, data_len);
2419 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2423 u_int data_len, tcode;
2426 /* Get the channel number and verify it. */
2427 id = packet_get_int();
2428 c = channel_lookup(id);
2431 packet_disconnect("Received extended_data for bad channel %d.", id);
2432 if (c->type != SSH_CHANNEL_OPEN) {
2433 logit("channel %d: ext data for non open", id);
2436 if (c->flags & CHAN_EOF_RCVD) {
2437 if (datafellows & SSH_BUG_EXTEOF)
2438 debug("channel %d: accepting ext data after eof", id);
2440 packet_disconnect("Received extended_data after EOF "
2441 "on channel %d.", id);
2443 tcode = packet_get_int();
2445 c->extended_usage != CHAN_EXTENDED_WRITE ||
2446 tcode != SSH2_EXTENDED_DATA_STDERR) {
2447 logit("channel %d: bad ext data", c->self);
2450 data = packet_get_string(&data_len);
2452 if (data_len > c->local_window) {
2453 logit("channel %d: rcvd too much extended_data %d, win %d",
2454 c->self, data_len, c->local_window);
2458 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2459 c->local_window -= data_len;
2460 buffer_append(&c->extended, data, data_len);
2466 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2471 id = packet_get_int();
2473 c = channel_lookup(id);
2475 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2478 /* XXX force input close */
2479 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2480 debug("channel %d: FORCE input drain", c->self);
2481 c->istate = CHAN_INPUT_WAIT_DRAIN;
2482 if (buffer_len(&c->input) == 0)
2490 channel_input_close(int type, u_int32_t seq, void *ctxt)
2495 id = packet_get_int();
2497 c = channel_lookup(id);
2499 packet_disconnect("Received close for nonexistent channel %d.", id);
2502 * Send a confirmation that we have closed the channel and no more
2503 * data is coming for it.
2505 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2506 packet_put_int(c->remote_id);
2510 * If the channel is in closed state, we have sent a close request,
2511 * and the other side will eventually respond with a confirmation.
2512 * Thus, we cannot free the channel here, because then there would be
2513 * no-one to receive the confirmation. The channel gets freed when
2514 * the confirmation arrives.
2516 if (c->type != SSH_CHANNEL_CLOSED) {
2518 * Not a closed channel - mark it as draining, which will
2519 * cause it to be freed later.
2521 buffer_clear(&c->input);
2522 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2526 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2529 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2531 int id = packet_get_int();
2532 Channel *c = channel_lookup(id);
2536 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2537 chan_rcvd_oclose(c);
2542 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2544 int id = packet_get_int();
2545 Channel *c = channel_lookup(id);
2549 packet_disconnect("Received close confirmation for "
2550 "out-of-range channel %d.", id);
2551 if (c->type != SSH_CHANNEL_CLOSED)
2552 packet_disconnect("Received close confirmation for "
2553 "non-closed channel %d (type %d).", id, c->type);
2559 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2564 id = packet_get_int();
2565 c = channel_lookup(id);
2567 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2568 packet_disconnect("Received open confirmation for "
2569 "non-opening channel %d.", id);
2570 remote_id = packet_get_int();
2571 /* Record the remote channel number and mark that the channel is now open. */
2572 c->remote_id = remote_id;
2573 c->type = SSH_CHANNEL_OPEN;
2576 c->remote_window = packet_get_int();
2577 c->remote_maxpacket = packet_get_int();
2578 if (c->open_confirm) {
2579 debug2("callback start");
2580 c->open_confirm(c->self, 1, c->open_confirm_ctx);
2581 debug2("callback done");
2583 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2584 c->remote_window, c->remote_maxpacket);
2590 reason2txt(int reason)
2593 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2594 return "administratively prohibited";
2595 case SSH2_OPEN_CONNECT_FAILED:
2596 return "connect failed";
2597 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2598 return "unknown channel type";
2599 case SSH2_OPEN_RESOURCE_SHORTAGE:
2600 return "resource shortage";
2602 return "unknown reason";
2607 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2610 char *msg = NULL, *lang = NULL;
2613 id = packet_get_int();
2614 c = channel_lookup(id);
2616 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2617 packet_disconnect("Received open failure for "
2618 "non-opening channel %d.", id);
2620 reason = packet_get_int();
2621 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2622 msg = packet_get_string(NULL);
2623 lang = packet_get_string(NULL);
2625 logit("channel %d: open failed: %s%s%s", id,
2626 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2631 if (c->open_confirm) {
2632 debug2("callback start");
2633 c->open_confirm(c->self, 0, c->open_confirm_ctx);
2634 debug2("callback done");
2638 /* Schedule the channel for cleanup/deletion. */
2644 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2653 /* Get the channel number and verify it. */
2654 id = packet_get_int();
2655 c = channel_lookup(id);
2658 logit("Received window adjust for non-open channel %d.", id);
2661 adjust = packet_get_int();
2663 debug2("channel %d: rcvd adjust %u", id, adjust);
2664 c->remote_window += adjust;
2669 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2673 char *host, *originator_string;
2676 remote_id = packet_get_int();
2677 host = packet_get_string(NULL);
2678 host_port = packet_get_int();
2680 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2681 originator_string = packet_get_string(NULL);
2683 originator_string = xstrdup("unknown (remote did not supply name)");
2686 c = channel_connect_to(host, host_port,
2687 "connected socket", originator_string);
2688 xfree(originator_string);
2691 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2692 packet_put_int(remote_id);
2695 c->remote_id = remote_id;
2700 channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
2703 struct channel_confirm *cc;
2706 /* Reset keepalive timeout */
2707 packet_set_alive_timeouts(0);
2709 id = packet_get_int();
2712 debug2("channel_input_status_confirm: type %d id %d", type, id);
2714 if ((c = channel_lookup(id)) == NULL) {
2715 logit("channel_input_status_confirm: %d: unknown", id);
2719 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
2721 cc->cb(type, c, cc->ctx);
2722 TAILQ_REMOVE(&c->status_confirms, cc, entry);
2723 bzero(cc, sizeof(*cc));
2727 /* -- tcp forwarding */
2730 channel_set_af(int af)
2736 channel_set_hpn(int disabled, u_int buf_size)
2738 hpn_disabled = disabled;
2739 buffer_size = buf_size;
2740 debug("HPN Disabled: %d, HPN Buffer Size: %d",
2741 hpn_disabled, buffer_size);
2745 * Determine whether or not a port forward listens to loopback, the
2746 * specified address or wildcard. On the client, a specified bind
2747 * address will always override gateway_ports. On the server, a
2748 * gateway_ports of 1 (``yes'') will override the client's specification
2749 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
2750 * will bind to whatever address the client asked for.
2752 * Special-case listen_addrs are:
2754 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2755 * "" (empty string), "*" -> wildcard v4/v6
2756 * "localhost" -> loopback v4/v6
2759 channel_fwd_bind_addr(const char *listen_addr, int *wildcardp,
2760 int is_client, int gateway_ports)
2762 const char *addr = NULL;
2765 if (listen_addr == NULL) {
2766 /* No address specified: default to gateway_ports setting */
2769 } else if (gateway_ports || is_client) {
2770 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2771 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
2772 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2773 (!is_client && gateway_ports == 1))
2775 else if (strcmp(listen_addr, "localhost") != 0)
2778 if (wildcardp != NULL)
2779 *wildcardp = wildcard;
2784 channel_setup_fwd_listener(int type, const char *listen_addr,
2785 u_short listen_port, int *allocated_listen_port,
2786 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2789 int sock, r, success = 0, wildcard = 0, is_client;
2790 struct addrinfo hints, *ai, *aitop;
2791 const char *host, *addr;
2792 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2795 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2796 listen_addr : host_to_connect;
2797 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2800 error("No forward host name.");
2803 if (strlen(host) >= NI_MAXHOST) {
2804 error("Forward host name too long.");
2808 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
2809 addr = channel_fwd_bind_addr(listen_addr, &wildcard,
2810 is_client, gateway_ports);
2811 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2812 type, wildcard, (addr == NULL) ? "NULL" : addr);
2815 * getaddrinfo returns a loopback address if the hostname is
2816 * set to NULL and hints.ai_flags is not AI_PASSIVE
2818 memset(&hints, 0, sizeof(hints));
2819 hints.ai_family = IPv4or6;
2820 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2821 hints.ai_socktype = SOCK_STREAM;
2822 snprintf(strport, sizeof strport, "%d", listen_port);
2823 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2825 /* This really shouldn't happen */
2826 packet_disconnect("getaddrinfo: fatal error: %s",
2827 ssh_gai_strerror(r));
2829 error("channel_setup_fwd_listener: "
2830 "getaddrinfo(%.64s): %s", addr,
2831 ssh_gai_strerror(r));
2835 if (allocated_listen_port != NULL)
2836 *allocated_listen_port = 0;
2837 for (ai = aitop; ai; ai = ai->ai_next) {
2838 switch (ai->ai_family) {
2840 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
2844 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
2851 * If allocating a port for -R forwards, then use the
2852 * same port for all address families.
2854 if (type == SSH_CHANNEL_RPORT_LISTENER && listen_port == 0 &&
2855 allocated_listen_port != NULL && *allocated_listen_port > 0)
2856 *lport_p = htons(*allocated_listen_port);
2858 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2859 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2860 error("channel_setup_fwd_listener: getnameinfo failed");
2863 /* Create a port to listen for the host. */
2864 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2866 /* this is no error since kernel may not support ipv6 */
2867 verbose("socket: %.100s", strerror(errno));
2871 channel_set_reuseaddr(sock);
2872 if (ai->ai_family == AF_INET6)
2873 sock_set_v6only(sock);
2875 debug("Local forwarding listening on %s port %s.",
2878 /* Bind the socket to the address. */
2879 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2880 /* address can be in use ipv6 address is already bound */
2882 error("bind: %.100s", strerror(errno));
2884 verbose("bind: %.100s", strerror(errno));
2889 /* Start listening for connections on the socket. */
2890 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2891 error("listen: %.100s", strerror(errno));
2897 * listen_port == 0 requests a dynamically allocated port -
2898 * record what we got.
2900 if (type == SSH_CHANNEL_RPORT_LISTENER && listen_port == 0 &&
2901 allocated_listen_port != NULL &&
2902 *allocated_listen_port == 0) {
2903 *allocated_listen_port = get_sock_port(sock, 1);
2904 debug("Allocated listen port %d",
2905 *allocated_listen_port);
2909 * Allocate a channel number for the socket. Explicitly test
2910 * for hpn disabled option. If true use smaller window size.
2913 c = channel_new("port listener", type, sock, sock, -1,
2914 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2915 0, "port listener", 1);
2917 c = channel_new("port listener", type, sock, sock, -1,
2918 buffer_size, CHAN_TCP_PACKET_DEFAULT,
2919 0, "port listener", 1);
2920 c->path = xstrdup(host);
2921 c->host_port = port_to_connect;
2922 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
2923 if (listen_port == 0 && allocated_listen_port != NULL &&
2924 !(datafellows & SSH_BUG_DYNAMIC_RPORT))
2925 c->listening_port = *allocated_listen_port;
2927 c->listening_port = listen_port;
2931 error("channel_setup_fwd_listener: cannot listen to port: %d",
2933 freeaddrinfo(aitop);
2938 channel_cancel_rport_listener(const char *host, u_short port)
2943 for (i = 0; i < channels_alloc; i++) {
2944 Channel *c = channels[i];
2945 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
2947 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
2948 debug2("%s: close channel %d", __func__, i);
2958 channel_cancel_lport_listener(const char *lhost, u_short lport,
2959 int cport, int gateway_ports)
2963 const char *addr = channel_fwd_bind_addr(lhost, NULL, 1, gateway_ports);
2965 for (i = 0; i < channels_alloc; i++) {
2966 Channel *c = channels[i];
2967 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
2969 if (c->listening_port != lport)
2971 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
2972 /* skip dynamic forwardings */
2973 if (c->host_port == 0)
2976 if (c->host_port != cport)
2979 if ((c->listening_addr == NULL && addr != NULL) ||
2980 (c->listening_addr != NULL && addr == NULL))
2982 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
2983 debug2("%s: close channel %d", __func__, i);
2992 /* protocol local port fwd, used by ssh (and sshd in v1) */
2994 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
2995 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2997 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
2998 listen_host, listen_port, NULL, host_to_connect, port_to_connect,
3002 /* protocol v2 remote port fwd, used by sshd */
3004 channel_setup_remote_fwd_listener(const char *listen_address,
3005 u_short listen_port, int *allocated_listen_port, int gateway_ports)
3007 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
3008 listen_address, listen_port, allocated_listen_port,
3009 NULL, 0, gateway_ports);
3013 * Translate the requested rfwd listen host to something usable for
3017 channel_rfwd_bind_host(const char *listen_host)
3019 if (listen_host == NULL) {
3020 if (datafellows & SSH_BUG_RFWD_ADDR)
3024 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3025 if (datafellows & SSH_BUG_RFWD_ADDR)
3034 * Initiate forwarding of connections to port "port" on remote host through
3035 * the secure channel to host:port from local side.
3036 * Returns handle (index) for updating the dynamic listen port with
3037 * channel_update_permitted_opens().
3040 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
3041 const char *host_to_connect, u_short port_to_connect)
3043 int type, success = 0, idx = -1;
3045 /* Send the forward request to the remote side. */
3047 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3048 packet_put_cstring("tcpip-forward");
3049 packet_put_char(1); /* boolean: want reply */
3050 packet_put_cstring(channel_rfwd_bind_host(listen_host));
3051 packet_put_int(listen_port);
3053 packet_write_wait();
3054 /* Assume that server accepts the request */
3057 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
3058 packet_put_int(listen_port);
3059 packet_put_cstring(host_to_connect);
3060 packet_put_int(port_to_connect);
3062 packet_write_wait();
3064 /* Wait for response from the remote side. */
3065 type = packet_read();
3067 case SSH_SMSG_SUCCESS:
3070 case SSH_SMSG_FAILURE:
3073 /* Unknown packet */
3074 packet_disconnect("Protocol error for port forward request:"
3075 "received packet type %d.", type);
3079 /* Record that connection to this host/port is permitted. */
3080 permitted_opens = xrealloc(permitted_opens,
3081 num_permitted_opens + 1, sizeof(*permitted_opens));
3082 idx = num_permitted_opens++;
3083 permitted_opens[idx].host_to_connect = xstrdup(host_to_connect);
3084 permitted_opens[idx].port_to_connect = port_to_connect;
3085 permitted_opens[idx].listen_port = listen_port;
3091 * Request cancellation of remote forwarding of connection host:port from
3095 channel_request_rforward_cancel(const char *host, u_short port)
3102 for (i = 0; i < num_permitted_opens; i++) {
3103 if (permitted_opens[i].host_to_connect != NULL &&
3104 permitted_opens[i].listen_port == port)
3107 if (i >= num_permitted_opens) {
3108 debug("%s: requested forward not found", __func__);
3111 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3112 packet_put_cstring("cancel-tcpip-forward");
3114 packet_put_cstring(channel_rfwd_bind_host(host));
3115 packet_put_int(port);
3118 permitted_opens[i].listen_port = 0;
3119 permitted_opens[i].port_to_connect = 0;
3120 xfree(permitted_opens[i].host_to_connect);
3121 permitted_opens[i].host_to_connect = NULL;
3127 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
3128 * listening for the port, and sends back a success reply (or disconnect
3129 * message if there was an error).
3132 channel_input_port_forward_request(int is_root, int gateway_ports)
3134 u_short port, host_port;
3138 /* Get arguments from the packet. */
3139 port = packet_get_int();
3140 hostname = packet_get_string(NULL);
3141 host_port = packet_get_int();
3145 * Check that an unprivileged user is not trying to forward a
3148 if (port < IPPORT_RESERVED && !is_root)
3150 "Requested forwarding of port %d but user is not root.",
3153 packet_disconnect("Dynamic forwarding denied.");
3156 /* Initiate forwarding */
3157 success = channel_setup_local_fwd_listener(NULL, port, hostname,
3158 host_port, gateway_ports);
3160 /* Free the argument string. */
3163 return (success ? 0 : -1);
3167 * Permits opening to any host/port if permitted_opens[] is empty. This is
3168 * usually called by the server, because the user could connect to any port
3169 * anyway, and the server has no way to know but to trust the client anyway.
3172 channel_permit_all_opens(void)
3174 if (num_permitted_opens == 0)
3175 all_opens_permitted = 1;
3179 channel_add_permitted_opens(char *host, int port)
3181 debug("allow port forwarding to host %s port %d", host, port);
3183 permitted_opens = xrealloc(permitted_opens,
3184 num_permitted_opens + 1, sizeof(*permitted_opens));
3185 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
3186 permitted_opens[num_permitted_opens].port_to_connect = port;
3187 num_permitted_opens++;
3189 all_opens_permitted = 0;
3193 * Update the listen port for a dynamic remote forward, after
3194 * the actual 'newport' has been allocated. If 'newport' < 0 is
3195 * passed then they entry will be invalidated.
3198 channel_update_permitted_opens(int idx, int newport)
3200 if (idx < 0 || idx >= num_permitted_opens) {
3201 debug("channel_update_permitted_opens: index out of range:"
3202 " %d num_permitted_opens %d", idx, num_permitted_opens);
3205 debug("%s allowed port %d for forwarding to host %s port %d",
3206 newport > 0 ? "Updating" : "Removing",
3208 permitted_opens[idx].host_to_connect,
3209 permitted_opens[idx].port_to_connect);
3211 permitted_opens[idx].listen_port =
3212 (datafellows & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
3214 permitted_opens[idx].listen_port = 0;
3215 permitted_opens[idx].port_to_connect = 0;
3216 xfree(permitted_opens[idx].host_to_connect);
3217 permitted_opens[idx].host_to_connect = NULL;
3222 channel_add_adm_permitted_opens(char *host, int port)
3224 debug("config allows port forwarding to host %s port %d", host, port);
3226 permitted_adm_opens = xrealloc(permitted_adm_opens,
3227 num_adm_permitted_opens + 1, sizeof(*permitted_adm_opens));
3228 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
3230 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
3231 return ++num_adm_permitted_opens;
3235 channel_disable_adm_local_opens(void)
3237 if (num_adm_permitted_opens == 0) {
3238 permitted_adm_opens = xmalloc(sizeof(*permitted_adm_opens));
3239 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
3241 num_adm_permitted_opens = 1;
3246 channel_clear_permitted_opens(void)
3250 for (i = 0; i < num_permitted_opens; i++)
3251 if (permitted_opens[i].host_to_connect != NULL)
3252 xfree(permitted_opens[i].host_to_connect);
3253 if (num_permitted_opens > 0) {
3254 xfree(permitted_opens);
3255 permitted_opens = NULL;
3257 num_permitted_opens = 0;
3261 channel_clear_adm_permitted_opens(void)
3265 for (i = 0; i < num_adm_permitted_opens; i++)
3266 if (permitted_adm_opens[i].host_to_connect != NULL)
3267 xfree(permitted_adm_opens[i].host_to_connect);
3268 if (num_adm_permitted_opens > 0) {
3269 xfree(permitted_adm_opens);
3270 permitted_adm_opens = NULL;
3272 num_adm_permitted_opens = 0;
3276 channel_print_adm_permitted_opens(void)
3280 printf("permitopen");
3281 if (num_adm_permitted_opens == 0) {
3285 for (i = 0; i < num_adm_permitted_opens; i++)
3286 if (permitted_adm_opens[i].host_to_connect == NULL)
3289 printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
3290 permitted_adm_opens[i].port_to_connect);
3294 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
3296 permitopen_port(const char *p)
3300 if (strcmp(p, "*") == 0)
3301 return FWD_PERMIT_ANY_PORT;
3302 if ((port = a2port(p)) > 0)
3308 port_match(u_short allowedport, u_short requestedport)
3310 if (allowedport == FWD_PERMIT_ANY_PORT ||
3311 allowedport == requestedport)
3316 /* Try to start non-blocking connect to next host in cctx list */
3318 connect_next(struct channel_connect *cctx)
3320 int sock, saved_errno;
3321 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3323 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
3324 if (cctx->ai->ai_family != AF_INET &&
3325 cctx->ai->ai_family != AF_INET6)
3327 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
3328 ntop, sizeof(ntop), strport, sizeof(strport),
3329 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3330 error("connect_next: getnameinfo failed");
3333 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
3334 cctx->ai->ai_protocol)) == -1) {
3335 if (cctx->ai->ai_next == NULL)
3336 error("socket: %.100s", strerror(errno));
3338 verbose("socket: %.100s", strerror(errno));
3341 if (set_nonblock(sock) == -1)
3342 fatal("%s: set_nonblock(%d)", __func__, sock);
3343 if (connect(sock, cctx->ai->ai_addr,
3344 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
3345 debug("connect_next: host %.100s ([%.100s]:%s): "
3346 "%.100s", cctx->host, ntop, strport,
3348 saved_errno = errno;
3350 errno = saved_errno;
3351 continue; /* fail -- try next */
3353 debug("connect_next: host %.100s ([%.100s]:%s) "
3354 "in progress, fd=%d", cctx->host, ntop, strport, sock);
3355 cctx->ai = cctx->ai->ai_next;
3363 channel_connect_ctx_free(struct channel_connect *cctx)
3367 freeaddrinfo(cctx->aitop);
3368 bzero(cctx, sizeof(*cctx));
3370 cctx->ai = cctx->aitop = NULL;
3373 /* Return CONNECTING channel to remote host, port */
3375 connect_to(const char *host, u_short port, char *ctype, char *rname)
3377 struct addrinfo hints;
3380 char strport[NI_MAXSERV];
3381 struct channel_connect cctx;
3384 memset(&cctx, 0, sizeof(cctx));
3385 memset(&hints, 0, sizeof(hints));
3386 hints.ai_family = IPv4or6;
3387 hints.ai_socktype = SOCK_STREAM;
3388 snprintf(strport, sizeof strport, "%d", port);
3389 if ((gaierr = getaddrinfo(host, strport, &hints, &cctx.aitop)) != 0) {
3390 error("connect_to %.100s: unknown host (%s)", host,
3391 ssh_gai_strerror(gaierr));
3395 cctx.host = xstrdup(host);
3397 cctx.ai = cctx.aitop;
3399 if ((sock = connect_next(&cctx)) == -1) {
3400 error("connect to %.100s port %d failed: %s",
3401 host, port, strerror(errno));
3402 channel_connect_ctx_free(&cctx);
3405 c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
3406 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
3407 c->connect_ctx = cctx;
3412 channel_connect_by_listen_address(u_short listen_port, char *ctype, char *rname)
3416 for (i = 0; i < num_permitted_opens; i++) {
3417 if (permitted_opens[i].host_to_connect != NULL &&
3418 port_match(permitted_opens[i].listen_port, listen_port)) {
3420 permitted_opens[i].host_to_connect,
3421 permitted_opens[i].port_to_connect, ctype, rname);
3424 error("WARNING: Server requests forwarding for unknown listen_port %d",
3429 /* Check if connecting to that port is permitted and connect. */
3431 channel_connect_to(const char *host, u_short port, char *ctype, char *rname)
3433 int i, permit, permit_adm = 1;
3435 permit = all_opens_permitted;
3437 for (i = 0; i < num_permitted_opens; i++)
3438 if (permitted_opens[i].host_to_connect != NULL &&
3439 port_match(permitted_opens[i].port_to_connect, port) &&
3440 strcmp(permitted_opens[i].host_to_connect, host) == 0)
3444 if (num_adm_permitted_opens > 0) {
3446 for (i = 0; i < num_adm_permitted_opens; i++)
3447 if (permitted_adm_opens[i].host_to_connect != NULL &&
3448 port_match(permitted_adm_opens[i].port_to_connect, port) &&
3449 strcmp(permitted_adm_opens[i].host_to_connect, host)
3454 if (!permit || !permit_adm) {
3455 logit("Received request to connect to host %.100s port %d, "
3456 "but the request was denied.", host, port);
3459 return connect_to(host, port, ctype, rname);
3463 channel_send_window_changes(void)
3468 for (i = 0; i < channels_alloc; i++) {
3469 if (channels[i] == NULL || !channels[i]->client_tty ||
3470 channels[i]->type != SSH_CHANNEL_OPEN)
3472 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
3474 channel_request_start(i, "window-change", 0);
3475 packet_put_int((u_int)ws.ws_col);
3476 packet_put_int((u_int)ws.ws_row);
3477 packet_put_int((u_int)ws.ws_xpixel);
3478 packet_put_int((u_int)ws.ws_ypixel);
3483 /* -- X11 forwarding */
3486 * Creates an internet domain socket for listening for X11 connections.
3487 * Returns 0 and a suitable display number for the DISPLAY variable
3488 * stored in display_numberp , or -1 if an error occurs.
3491 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
3492 int single_connection, u_int *display_numberp, int **chanids)
3495 int display_number, sock;
3497 struct addrinfo hints, *ai, *aitop;
3498 char strport[NI_MAXSERV];
3499 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
3501 if (chanids == NULL)
3504 for (display_number = x11_display_offset;
3505 display_number < MAX_DISPLAYS;
3507 port = 6000 + display_number;
3508 memset(&hints, 0, sizeof(hints));
3509 hints.ai_family = IPv4or6;
3510 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
3511 hints.ai_socktype = SOCK_STREAM;
3512 snprintf(strport, sizeof strport, "%d", port);
3513 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
3514 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
3517 for (ai = aitop; ai; ai = ai->ai_next) {
3518 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
3520 sock = socket(ai->ai_family, ai->ai_socktype,
3523 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
3525 && (errno != EPFNOSUPPORT)
3528 error("socket: %.100s", strerror(errno));
3529 freeaddrinfo(aitop);
3532 debug("x11_create_display_inet: Socket family %d not supported",
3537 if (ai->ai_family == AF_INET6)
3538 sock_set_v6only(sock);
3539 if (x11_use_localhost)
3540 channel_set_reuseaddr(sock);
3541 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3542 debug2("bind port %d: %.100s", port, strerror(errno));
3545 for (n = 0; n < num_socks; n++) {
3551 socks[num_socks++] = sock;
3552 if (num_socks == NUM_SOCKS)
3555 freeaddrinfo(aitop);
3559 if (display_number >= MAX_DISPLAYS) {
3560 error("Failed to allocate internet-domain X11 display socket.");
3563 /* Start listening for connections on the socket. */
3564 for (n = 0; n < num_socks; n++) {
3566 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3567 error("listen: %.100s", strerror(errno));
3573 /* Allocate a channel for each socket. */
3574 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
3575 for (n = 0; n < num_socks; n++) {
3578 nc = channel_new("x11 listener",
3579 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3580 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
3581 0, "X11 inet listener", 1);
3583 nc = channel_new("x11 listener",
3584 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3585 buffer_size, CHAN_X11_PACKET_DEFAULT,
3586 0, "X11 inet listener", 1);
3587 nc->single_connection = single_connection;
3588 (*chanids)[n] = nc->self;
3592 /* Return the display number for the DISPLAY environment variable. */
3593 *display_numberp = display_number;
3598 connect_local_xsocket_path(const char *pathname)
3601 struct sockaddr_un addr;
3603 sock = socket(AF_UNIX, SOCK_STREAM, 0);
3605 error("socket: %.100s", strerror(errno));
3606 memset(&addr, 0, sizeof(addr));
3607 addr.sun_family = AF_UNIX;
3608 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
3609 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
3612 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
3617 connect_local_xsocket(u_int dnr)
3620 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
3621 return connect_local_xsocket_path(buf);
3625 x11_connect_display(void)
3627 u_int display_number;
3628 const char *display;
3629 char buf[1024], *cp;
3630 struct addrinfo hints, *ai, *aitop;
3631 char strport[NI_MAXSERV];
3632 int gaierr, sock = 0;
3634 /* Try to open a socket for the local X server. */
3635 display = getenv("DISPLAY");
3637 error("DISPLAY not set.");
3641 * Now we decode the value of the DISPLAY variable and make a
3642 * connection to the real X server.
3645 /* Check if the display is from launchd. */
3647 if (strncmp(display, "/tmp/launch", 11) == 0) {
3648 sock = connect_local_xsocket_path(display);
3652 /* OK, we now have a connection to the display. */
3657 * Check if it is a unix domain socket. Unix domain displays are in
3658 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
3660 if (strncmp(display, "unix:", 5) == 0 ||
3661 display[0] == ':') {
3662 /* Connect to the unix domain socket. */
3663 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
3664 error("Could not parse display number from DISPLAY: %.100s",
3668 /* Create a socket. */
3669 sock = connect_local_xsocket(display_number);
3673 /* OK, we now have a connection to the display. */
3677 * Connect to an inet socket. The DISPLAY value is supposedly
3678 * hostname:d[.s], where hostname may also be numeric IP address.
3680 strlcpy(buf, display, sizeof(buf));
3681 cp = strchr(buf, ':');
3683 error("Could not find ':' in DISPLAY: %.100s", display);
3687 /* buf now contains the host name. But first we parse the display number. */
3688 if (sscanf(cp + 1, "%u", &display_number) != 1) {
3689 error("Could not parse display number from DISPLAY: %.100s",
3694 /* Look up the host address */
3695 memset(&hints, 0, sizeof(hints));
3696 hints.ai_family = IPv4or6;
3697 hints.ai_socktype = SOCK_STREAM;
3698 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
3699 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
3700 error("%.100s: unknown host. (%s)", buf,
3701 ssh_gai_strerror(gaierr));
3704 for (ai = aitop; ai; ai = ai->ai_next) {
3705 /* Create a socket. */
3706 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3708 debug2("socket: %.100s", strerror(errno));
3711 /* Connect it to the display. */
3712 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3713 debug2("connect %.100s port %u: %.100s", buf,
3714 6000 + display_number, strerror(errno));
3721 freeaddrinfo(aitop);
3723 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3732 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3733 * the remote channel number. We should do whatever we want, and respond
3734 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3739 x11_input_open(int type, u_int32_t seq, void *ctxt)
3742 int remote_id, sock = 0;
3745 debug("Received X11 open request.");
3747 remote_id = packet_get_int();
3749 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3750 remote_host = packet_get_string(NULL);
3752 remote_host = xstrdup("unknown (remote did not supply name)");
3756 /* Obtain a connection to the real X display. */
3757 sock = x11_connect_display();
3759 /* Allocate a channel for this connection. */
3760 c = channel_new("connected x11 socket",
3761 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3763 c->remote_id = remote_id;
3768 /* Send refusal to the remote host. */
3769 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3770 packet_put_int(remote_id);
3772 /* Send a confirmation to the remote host. */
3773 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3774 packet_put_int(remote_id);
3775 packet_put_int(c->self);
3780 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3783 deny_input_open(int type, u_int32_t seq, void *ctxt)
3785 int rchan = packet_get_int();
3788 case SSH_SMSG_AGENT_OPEN:
3789 error("Warning: ssh server tried agent forwarding.");
3791 case SSH_SMSG_X11_OPEN:
3792 error("Warning: ssh server tried X11 forwarding.");
3795 error("deny_input_open: type %d", type);
3798 error("Warning: this is probably a break-in attempt by a malicious server.");
3799 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3800 packet_put_int(rchan);
3805 * Requests forwarding of X11 connections, generates fake authentication
3806 * data, and enables authentication spoofing.
3807 * This should be called in the client only.
3810 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3811 const char *proto, const char *data, int want_reply)
3813 u_int data_len = (u_int) strlen(data) / 2;
3820 if (x11_saved_display == NULL)
3821 x11_saved_display = xstrdup(disp);
3822 else if (strcmp(disp, x11_saved_display) != 0) {
3823 error("x11_request_forwarding_with_spoofing: different "
3824 "$DISPLAY already forwarded");
3828 cp = strchr(disp, ':');
3830 cp = strchr(cp, '.');
3832 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3836 if (x11_saved_proto == NULL) {
3837 /* Save protocol name. */
3838 x11_saved_proto = xstrdup(proto);
3840 * Extract real authentication data and generate fake data
3841 * of the same length.
3843 x11_saved_data = xmalloc(data_len);
3844 x11_fake_data = xmalloc(data_len);
3845 for (i = 0; i < data_len; i++) {
3846 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3847 fatal("x11_request_forwarding: bad "
3848 "authentication data: %.100s", data);
3851 x11_saved_data[i] = value;
3852 x11_fake_data[i] = rnd & 0xff;
3855 x11_saved_data_len = data_len;
3856 x11_fake_data_len = data_len;
3859 /* Convert the fake data into hex. */
3860 new_data = tohex(x11_fake_data, data_len);
3862 /* Send the request packet. */
3864 channel_request_start(client_session_id, "x11-req", want_reply);
3865 packet_put_char(0); /* XXX bool single connection */
3867 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3869 packet_put_cstring(proto);
3870 packet_put_cstring(new_data);
3871 packet_put_int(screen_number);
3873 packet_write_wait();
3878 /* -- agent forwarding */
3880 /* Sends a message to the server to request authentication fd forwarding. */
3883 auth_request_forwarding(void)
3885 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3887 packet_write_wait();