1 /* $OpenBSD: channels.c,v 1.328 2013/12/19 01:04:36 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:
222 case SSH_CHANNEL_ABANDONED:
225 logit("Non-public channel %d, type %d.", id, c->type);
230 * Register filedescriptors for a channel, used when allocating a channel or
231 * when the channel consumer/producer is ready, e.g. shell exec'd
234 channel_register_fds(Channel *c, int rfd, int wfd, int efd,
235 int extusage, int nonblock, int is_tty)
237 /* Update the maximum file descriptor value. */
238 channel_max_fd = MAX(channel_max_fd, rfd);
239 channel_max_fd = MAX(channel_max_fd, wfd);
240 channel_max_fd = MAX(channel_max_fd, efd);
243 fcntl(rfd, F_SETFD, FD_CLOEXEC);
244 if (wfd != -1 && wfd != rfd)
245 fcntl(wfd, F_SETFD, FD_CLOEXEC);
246 if (efd != -1 && efd != rfd && efd != wfd)
247 fcntl(efd, F_SETFD, FD_CLOEXEC);
251 c->sock = (rfd == wfd) ? rfd : -1;
253 c->extended_usage = extusage;
255 if ((c->isatty = is_tty) != 0)
256 debug2("channel %d: rfd %d isatty", c->self, c->rfd);
258 /* XXX: Later AIX versions can't push as much data to tty */
259 c->wfd_isatty = is_tty || isatty(c->wfd);
262 /* enable nonblocking mode */
274 * Allocate a new channel object and set its type and socket. This will cause
275 * remote_name to be freed.
278 channel_new(char *ctype, int type, int rfd, int wfd, int efd,
279 u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
285 /* Do initial allocation if this is the first call. */
286 if (channels_alloc == 0) {
288 channels = xcalloc(channels_alloc, sizeof(Channel *));
289 for (i = 0; i < channels_alloc; i++)
292 /* Try to find a free slot where to put the new channel. */
293 for (found = -1, i = 0; i < channels_alloc; i++)
294 if (channels[i] == NULL) {
295 /* Found a free slot. */
300 /* There are no free slots. Take last+1 slot and expand the array. */
301 found = channels_alloc;
302 if (channels_alloc > 10000)
303 fatal("channel_new: internal error: channels_alloc %d "
304 "too big.", channels_alloc);
305 channels = xrealloc(channels, channels_alloc + 10,
307 channels_alloc += 10;
308 debug2("channel: expanding %d", channels_alloc);
309 for (i = found; i < channels_alloc; i++)
312 /* Initialize and return new channel. */
313 c = channels[found] = xcalloc(1, sizeof(Channel));
314 buffer_init(&c->input);
315 buffer_init(&c->output);
316 buffer_init(&c->extended);
318 c->listening_addr = NULL;
319 c->listening_port = 0;
320 c->ostate = CHAN_OUTPUT_OPEN;
321 c->istate = CHAN_INPUT_OPEN;
323 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, 0);
328 c->dynamic_window = 0;
329 c->local_window = window;
330 c->local_window_max = window;
331 c->local_consumed = 0;
332 c->local_maxpacket = maxpack;
334 c->remote_name = xstrdup(remote_name);
335 c->remote_window = 0;
336 c->remote_maxpacket = 0;
338 c->single_connection = 0;
339 c->detach_user = NULL;
341 c->open_confirm = NULL;
342 c->open_confirm_ctx = NULL;
343 c->input_filter = NULL;
344 c->output_filter = NULL;
345 c->filter_ctx = NULL;
346 c->filter_cleanup = NULL;
351 c->delayed = 1; /* prevent call to channel_post handler */
352 TAILQ_INIT(&c->status_confirms);
353 debug("channel %d: new [%s]", found, remote_name);
358 channel_find_maxfd(void)
364 for (i = 0; i < channels_alloc; i++) {
367 max = MAX(max, c->rfd);
368 max = MAX(max, c->wfd);
369 max = MAX(max, c->efd);
376 channel_close_fd(int *fdp)
378 int ret = 0, fd = *fdp;
383 if (fd == channel_max_fd)
384 channel_max_fd = channel_find_maxfd();
389 /* Close all channel fd/socket. */
391 channel_close_fds(Channel *c)
393 channel_close_fd(&c->sock);
394 channel_close_fd(&c->rfd);
395 channel_close_fd(&c->wfd);
396 channel_close_fd(&c->efd);
399 /* Free the channel and close its fd/socket. */
401 channel_free(Channel *c)
405 struct channel_confirm *cc;
407 for (n = 0, i = 0; i < channels_alloc; i++)
410 debug("channel %d: free: %s, nchannels %u", c->self,
411 c->remote_name ? c->remote_name : "???", n);
413 s = channel_open_message();
414 debug3("channel %d: status: %s", c->self, s);
418 shutdown(c->sock, SHUT_RDWR);
419 channel_close_fds(c);
420 buffer_free(&c->input);
421 buffer_free(&c->output);
422 buffer_free(&c->extended);
423 free(c->remote_name);
424 c->remote_name = NULL;
427 free(c->listening_addr);
428 c->listening_addr = NULL;
429 while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
430 if (cc->abandon_cb != NULL)
431 cc->abandon_cb(c, cc->ctx);
432 TAILQ_REMOVE(&c->status_confirms, cc, entry);
433 bzero(cc, sizeof(*cc));
436 if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
437 c->filter_cleanup(c->self, c->filter_ctx);
438 channels[c->self] = NULL;
443 channel_free_all(void)
447 for (i = 0; i < channels_alloc; i++)
448 if (channels[i] != NULL)
449 channel_free(channels[i]);
453 * Closes the sockets/fds of all channels. This is used to close extra file
454 * descriptors after a fork.
457 channel_close_all(void)
461 for (i = 0; i < channels_alloc; i++)
462 if (channels[i] != NULL)
463 channel_close_fds(channels[i]);
467 * Stop listening to channels.
470 channel_stop_listening(void)
475 for (i = 0; i < channels_alloc; i++) {
479 case SSH_CHANNEL_AUTH_SOCKET:
480 case SSH_CHANNEL_PORT_LISTENER:
481 case SSH_CHANNEL_RPORT_LISTENER:
482 case SSH_CHANNEL_X11_LISTENER:
483 channel_close_fd(&c->sock);
492 * Returns true if no channel has too much buffered data, and false if one or
493 * more channel is overfull.
496 channel_not_very_much_buffered_data(void)
501 for (i = 0; i < channels_alloc; i++) {
503 if (c != NULL && c->type == SSH_CHANNEL_OPEN) {
506 buffer_len(&c->input) > packet_get_maxsize()) {
507 debug2("channel %d: big input buffer %d",
508 c->self, buffer_len(&c->input));
512 if (buffer_len(&c->output) > packet_get_maxsize()) {
513 debug2("channel %d: big output buffer %u > %u",
514 c->self, buffer_len(&c->output),
515 packet_get_maxsize());
523 /* Returns true if any channel is still open. */
525 channel_still_open(void)
530 for (i = 0; i < channels_alloc; i++) {
535 case SSH_CHANNEL_X11_LISTENER:
536 case SSH_CHANNEL_PORT_LISTENER:
537 case SSH_CHANNEL_RPORT_LISTENER:
538 case SSH_CHANNEL_MUX_LISTENER:
539 case SSH_CHANNEL_CLOSED:
540 case SSH_CHANNEL_AUTH_SOCKET:
541 case SSH_CHANNEL_DYNAMIC:
542 case SSH_CHANNEL_CONNECTING:
543 case SSH_CHANNEL_ZOMBIE:
544 case SSH_CHANNEL_ABANDONED:
546 case SSH_CHANNEL_LARVAL:
548 fatal("cannot happen: SSH_CHANNEL_LARVAL");
550 case SSH_CHANNEL_OPENING:
551 case SSH_CHANNEL_OPEN:
552 case SSH_CHANNEL_X11_OPEN:
553 case SSH_CHANNEL_MUX_CLIENT:
555 case SSH_CHANNEL_INPUT_DRAINING:
556 case SSH_CHANNEL_OUTPUT_DRAINING:
558 fatal("cannot happen: OUT_DRAIN");
561 fatal("channel_still_open: bad channel type %d", c->type);
568 /* Returns the id of an open channel suitable for keepaliving */
570 channel_find_open(void)
575 for (i = 0; i < channels_alloc; i++) {
577 if (c == NULL || c->remote_id < 0)
580 case SSH_CHANNEL_CLOSED:
581 case SSH_CHANNEL_DYNAMIC:
582 case SSH_CHANNEL_X11_LISTENER:
583 case SSH_CHANNEL_PORT_LISTENER:
584 case SSH_CHANNEL_RPORT_LISTENER:
585 case SSH_CHANNEL_MUX_LISTENER:
586 case SSH_CHANNEL_MUX_CLIENT:
587 case SSH_CHANNEL_OPENING:
588 case SSH_CHANNEL_CONNECTING:
589 case SSH_CHANNEL_ZOMBIE:
590 case SSH_CHANNEL_ABANDONED:
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_ABANDONED:
639 case SSH_CHANNEL_MUX_CLIENT:
640 case SSH_CHANNEL_MUX_LISTENER:
642 case SSH_CHANNEL_LARVAL:
643 case SSH_CHANNEL_OPENING:
644 case SSH_CHANNEL_CONNECTING:
645 case SSH_CHANNEL_DYNAMIC:
646 case SSH_CHANNEL_OPEN:
647 case SSH_CHANNEL_X11_OPEN:
648 case SSH_CHANNEL_INPUT_DRAINING:
649 case SSH_CHANNEL_OUTPUT_DRAINING:
650 snprintf(buf, sizeof buf,
651 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cc %d)\r\n",
652 c->self, c->remote_name,
653 c->type, c->remote_id,
654 c->istate, buffer_len(&c->input),
655 c->ostate, buffer_len(&c->output),
656 c->rfd, c->wfd, c->ctl_chan);
657 buffer_append(&buffer, buf, strlen(buf));
660 fatal("channel_open_message: bad channel type %d", c->type);
664 buffer_append(&buffer, "\0", 1);
665 cp = xstrdup(buffer_ptr(&buffer));
666 buffer_free(&buffer);
671 channel_send_open(int id)
673 Channel *c = channel_lookup(id);
676 logit("channel_send_open: %d: bad id", id);
679 debug2("channel %d: send open", id);
680 packet_start(SSH2_MSG_CHANNEL_OPEN);
681 packet_put_cstring(c->ctype);
682 packet_put_int(c->self);
683 packet_put_int(c->local_window);
684 packet_put_int(c->local_maxpacket);
689 channel_request_start(int id, char *service, int wantconfirm)
691 Channel *c = channel_lookup(id);
694 logit("channel_request_start: %d: unknown channel id", id);
697 debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
698 packet_start(SSH2_MSG_CHANNEL_REQUEST);
699 packet_put_int(c->remote_id);
700 packet_put_cstring(service);
701 packet_put_char(wantconfirm);
705 channel_register_status_confirm(int id, channel_confirm_cb *cb,
706 channel_confirm_abandon_cb *abandon_cb, void *ctx)
708 struct channel_confirm *cc;
711 if ((c = channel_lookup(id)) == NULL)
712 fatal("channel_register_expect: %d: bad id", id);
714 cc = xcalloc(1, sizeof(*cc));
716 cc->abandon_cb = abandon_cb;
718 TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
722 channel_register_open_confirm(int id, channel_open_fn *fn, void *ctx)
724 Channel *c = channel_lookup(id);
727 logit("channel_register_open_confirm: %d: bad id", id);
730 c->open_confirm = fn;
731 c->open_confirm_ctx = ctx;
735 channel_register_cleanup(int id, channel_callback_fn *fn, int do_close)
737 Channel *c = channel_by_id(id);
740 logit("channel_register_cleanup: %d: bad id", id);
744 c->detach_close = do_close;
748 channel_cancel_cleanup(int id)
750 Channel *c = channel_by_id(id);
753 logit("channel_cancel_cleanup: %d: bad id", id);
756 c->detach_user = NULL;
761 channel_register_filter(int id, channel_infilter_fn *ifn,
762 channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
764 Channel *c = channel_lookup(id);
767 logit("channel_register_filter: %d: bad id", id);
770 c->input_filter = ifn;
771 c->output_filter = ofn;
773 c->filter_cleanup = cfn;
777 channel_set_fds(int id, int rfd, int wfd, int efd,
778 int extusage, int nonblock, int is_tty, u_int window_max)
780 Channel *c = channel_lookup(id);
782 if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
783 fatal("channel_activate for non-larval channel %d.", id);
784 channel_register_fds(c, rfd, wfd, efd, extusage, nonblock, is_tty);
785 c->type = SSH_CHANNEL_OPEN;
786 c->local_window = c->local_window_max = window_max;
787 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
788 packet_put_int(c->remote_id);
789 packet_put_int(c->local_window);
794 * 'channel_pre*' are called just before select() to add any bits relevant to
795 * channels in the select bitmasks.
798 * 'channel_post*': perform any appropriate operations for channels which
799 * have events pending.
801 typedef void chan_fn(Channel *c, fd_set *readset, fd_set *writeset);
802 chan_fn *channel_pre[SSH_CHANNEL_MAX_TYPE];
803 chan_fn *channel_post[SSH_CHANNEL_MAX_TYPE];
807 channel_pre_listener(Channel *c, fd_set *readset, fd_set *writeset)
809 FD_SET(c->sock, readset);
814 channel_pre_connecting(Channel *c, fd_set *readset, fd_set *writeset)
816 debug3("channel %d: waiting for connection", c->self);
817 FD_SET(c->sock, writeset);
821 channel_pre_open_13(Channel *c, fd_set *readset, fd_set *writeset)
823 if (buffer_len(&c->input) < packet_get_maxsize())
824 FD_SET(c->sock, readset);
825 if (buffer_len(&c->output) > 0)
826 FD_SET(c->sock, writeset);
830 channel_tcpwinsz(void)
837 /* If we are not on a socket return 128KB. */
838 if (!packet_connection_is_on_socket())
842 optsz = sizeof(tcpwinsz);
843 sd = packet_get_connection_in();
844 ret = getsockopt(sd, SOL_SOCKET, SO_RCVBUF, &tcpwinsz, &optsz);
846 /* Return no more than the maximum buffer size. */
847 maxlen = buffer_get_max_len();
848 if ((ret == 0) && tcpwinsz > maxlen)
850 /* In case getsockopt() failed return a minimum. */
852 tcpwinsz = CHAN_TCP_WINDOW_DEFAULT;
853 debug2("tcpwinsz: %d for connection: %d", tcpwinsz, sd);
858 channel_pre_open(Channel *c, fd_set *readset, fd_set *writeset)
862 /* Check buffer limits. */
863 if (!c->tcpwinsz || c->dynamic_window > 0)
864 c->tcpwinsz = channel_tcpwinsz();
866 limit = MIN(compat20 ? c->remote_window : packet_get_maxsize(),
869 if (c->istate == CHAN_INPUT_OPEN &&
871 buffer_len(&c->input) < limit &&
872 buffer_check_alloc(&c->input, CHAN_RBUF))
873 FD_SET(c->rfd, readset);
874 if (c->ostate == CHAN_OUTPUT_OPEN ||
875 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
876 if (buffer_len(&c->output) > 0) {
877 FD_SET(c->wfd, writeset);
878 } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
879 if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
880 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
881 c->self, c->efd, buffer_len(&c->extended));
886 /** XXX check close conditions, too */
887 if (compat20 && c->efd != -1 &&
888 !(c->istate == CHAN_INPUT_CLOSED && c->ostate == CHAN_OUTPUT_CLOSED)) {
889 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
890 buffer_len(&c->extended) > 0)
891 FD_SET(c->efd, writeset);
892 else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
893 (c->extended_usage == CHAN_EXTENDED_READ ||
894 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
895 buffer_len(&c->extended) < c->remote_window)
896 FD_SET(c->efd, readset);
898 /* XXX: What about efd? races? */
903 channel_pre_input_draining(Channel *c, fd_set *readset, fd_set *writeset)
905 if (buffer_len(&c->input) == 0) {
906 packet_start(SSH_MSG_CHANNEL_CLOSE);
907 packet_put_int(c->remote_id);
909 c->type = SSH_CHANNEL_CLOSED;
910 debug2("channel %d: closing after input drain.", c->self);
916 channel_pre_output_draining(Channel *c, fd_set *readset, fd_set *writeset)
918 if (buffer_len(&c->output) == 0)
921 FD_SET(c->sock, writeset);
925 * This is a special state for X11 authentication spoofing. An opened X11
926 * connection (when authentication spoofing is being done) remains in this
927 * state until the first packet has been completely read. The authentication
928 * data in that packet is then substituted by the real data if it matches the
929 * fake data, and the channel is put into normal mode.
930 * XXX All this happens at the client side.
931 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
934 x11_open_helper(Buffer *b)
937 u_int proto_len, data_len;
939 /* Check if the fixed size part of the packet is in buffer. */
940 if (buffer_len(b) < 12)
943 /* Parse the lengths of variable-length fields. */
945 if (ucp[0] == 0x42) { /* Byte order MSB first. */
946 proto_len = 256 * ucp[6] + ucp[7];
947 data_len = 256 * ucp[8] + ucp[9];
948 } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
949 proto_len = ucp[6] + 256 * ucp[7];
950 data_len = ucp[8] + 256 * ucp[9];
952 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
957 /* Check if the whole packet is in buffer. */
959 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
962 /* Check if authentication protocol matches. */
963 if (proto_len != strlen(x11_saved_proto) ||
964 memcmp(ucp + 12, x11_saved_proto, proto_len) != 0) {
965 debug2("X11 connection uses different authentication protocol.");
968 /* Check if authentication data matches our fake data. */
969 if (data_len != x11_fake_data_len ||
970 timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
971 x11_fake_data, x11_fake_data_len) != 0) {
972 debug2("X11 auth data does not match fake data.");
975 /* Check fake data length */
976 if (x11_fake_data_len != x11_saved_data_len) {
977 error("X11 fake_data_len %d != saved_data_len %d",
978 x11_fake_data_len, x11_saved_data_len);
982 * Received authentication protocol and data match
983 * our fake data. Substitute the fake data with real
986 memcpy(ucp + 12 + ((proto_len + 3) & ~3),
987 x11_saved_data, x11_saved_data_len);
992 channel_pre_x11_open_13(Channel *c, fd_set *readset, fd_set *writeset)
994 int ret = x11_open_helper(&c->output);
997 /* Start normal processing for the channel. */
998 c->type = SSH_CHANNEL_OPEN;
999 channel_pre_open_13(c, readset, writeset);
1000 } else if (ret == -1) {
1002 * We have received an X11 connection that has bad
1003 * authentication information.
1005 logit("X11 connection rejected because of wrong authentication.");
1006 buffer_clear(&c->input);
1007 buffer_clear(&c->output);
1008 channel_close_fd(&c->sock);
1010 c->type = SSH_CHANNEL_CLOSED;
1011 packet_start(SSH_MSG_CHANNEL_CLOSE);
1012 packet_put_int(c->remote_id);
1018 channel_pre_x11_open(Channel *c, fd_set *readset, fd_set *writeset)
1020 int ret = x11_open_helper(&c->output);
1022 /* c->force_drain = 1; */
1025 c->type = SSH_CHANNEL_OPEN;
1026 channel_pre_open(c, readset, writeset);
1027 } else if (ret == -1) {
1028 logit("X11 connection rejected because of wrong authentication.");
1029 debug2("X11 rejected %d i%d/o%d", c->self, c->istate, c->ostate);
1030 chan_read_failed(c);
1031 buffer_clear(&c->input);
1033 buffer_clear(&c->output);
1034 /* for proto v1, the peer will send an IEOF */
1036 chan_write_failed(c);
1038 c->type = SSH_CHANNEL_OPEN;
1039 debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
1044 channel_pre_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1046 if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
1047 buffer_check_alloc(&c->input, CHAN_RBUF))
1048 FD_SET(c->rfd, readset);
1049 if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
1050 /* clear buffer immediately (discard any partial packet) */
1051 buffer_clear(&c->input);
1053 /* Start output drain. XXX just kill chan? */
1054 chan_rcvd_oclose(c);
1056 if (c->ostate == CHAN_OUTPUT_OPEN ||
1057 c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
1058 if (buffer_len(&c->output) > 0)
1059 FD_SET(c->wfd, writeset);
1060 else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
1065 /* try to decode a socks4 header */
1068 channel_decode_socks4(Channel *c, fd_set *readset, fd_set *writeset)
1071 u_int len, have, i, found, need;
1076 u_int16_t dest_port;
1077 struct in_addr dest_addr;
1080 debug2("channel %d: decode socks4", c->self);
1082 have = buffer_len(&c->input);
1083 len = sizeof(s4_req);
1086 p = buffer_ptr(&c->input);
1089 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1090 if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
1091 debug2("channel %d: socks4a request", c->self);
1092 /* ... and needs an extra string (the hostname) */
1095 /* Check for terminating NUL on the string(s) */
1096 for (found = 0, i = len; i < have; i++) {
1103 /* the peer is probably sending garbage */
1104 debug("channel %d: decode socks4: too long",
1111 buffer_get(&c->input, (char *)&s4_req.version, 1);
1112 buffer_get(&c->input, (char *)&s4_req.command, 1);
1113 buffer_get(&c->input, (char *)&s4_req.dest_port, 2);
1114 buffer_get(&c->input, (char *)&s4_req.dest_addr, 4);
1115 have = buffer_len(&c->input);
1116 p = buffer_ptr(&c->input);
1118 debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
1119 len++; /* trailing '\0' */
1121 fatal("channel %d: decode socks4: len %d > have %d",
1122 c->self, len, have);
1123 strlcpy(username, p, sizeof(username));
1124 buffer_consume(&c->input, len);
1128 if (need == 1) { /* SOCKS4: one string */
1129 host = inet_ntoa(s4_req.dest_addr);
1130 c->path = xstrdup(host);
1131 } else { /* SOCKS4A: two strings */
1132 have = buffer_len(&c->input);
1133 p = buffer_ptr(&c->input);
1135 debug2("channel %d: decode socks4a: host %s/%d",
1137 len++; /* trailing '\0' */
1139 fatal("channel %d: decode socks4a: len %d > have %d",
1140 c->self, len, have);
1141 if (len > NI_MAXHOST) {
1142 error("channel %d: hostname \"%.100s\" too long",
1146 c->path = xstrdup(p);
1147 buffer_consume(&c->input, len);
1149 c->host_port = ntohs(s4_req.dest_port);
1151 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1152 c->self, c->path, c->host_port, s4_req.command);
1154 if (s4_req.command != 1) {
1155 debug("channel %d: cannot handle: %s cn %d",
1156 c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
1159 s4_rsp.version = 0; /* vn: 0 for reply */
1160 s4_rsp.command = 90; /* cd: req granted */
1161 s4_rsp.dest_port = 0; /* ignored */
1162 s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
1163 buffer_append(&c->output, &s4_rsp, sizeof(s4_rsp));
1167 /* try to decode a socks5 header */
1168 #define SSH_SOCKS5_AUTHDONE 0x1000
1169 #define SSH_SOCKS5_NOAUTH 0x00
1170 #define SSH_SOCKS5_IPV4 0x01
1171 #define SSH_SOCKS5_DOMAIN 0x03
1172 #define SSH_SOCKS5_IPV6 0x04
1173 #define SSH_SOCKS5_CONNECT 0x01
1174 #define SSH_SOCKS5_SUCCESS 0x00
1178 channel_decode_socks5(Channel *c, fd_set *readset, fd_set *writeset)
1186 u_int16_t dest_port;
1187 char 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, &dest_addr, addrlen);
1259 buffer_get(&c->input, (char *)&dest_port, 2);
1260 dest_addr[addrlen] = '\0';
1263 if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
1264 if (addrlen >= NI_MAXHOST) {
1265 error("channel %d: dynamic request: socks5 hostname "
1266 "\"%.100s\" too long", c->self, dest_addr);
1269 c->path = xstrdup(dest_addr);
1271 if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
1273 c->path = xstrdup(ntop);
1275 c->host_port = ntohs(dest_port);
1277 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1278 c->self, c->path, c->host_port, s5_req.command);
1280 s5_rsp.version = 0x05;
1281 s5_rsp.command = SSH_SOCKS5_SUCCESS;
1282 s5_rsp.reserved = 0; /* ignored */
1283 s5_rsp.atyp = SSH_SOCKS5_IPV4;
1284 dest_port = 0; /* ignored */
1286 buffer_append(&c->output, &s5_rsp, sizeof(s5_rsp));
1287 buffer_put_int(&c->output, ntohl(INADDR_ANY)); /* bind address */
1288 buffer_append(&c->output, &dest_port, sizeof(dest_port));
1293 channel_connect_stdio_fwd(const char *host_to_connect, u_short port_to_connect,
1298 debug("channel_connect_stdio_fwd %s:%d", host_to_connect,
1301 c = channel_new("stdio-forward", SSH_CHANNEL_OPENING, in, out,
1302 -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
1303 0, "stdio-forward", /*nonblock*/0);
1305 c->path = xstrdup(host_to_connect);
1306 c->host_port = port_to_connect;
1307 c->listening_port = 0;
1310 channel_register_fds(c, in, out, -1, 0, 1, 0);
1311 port_open_helper(c, "direct-tcpip");
1316 /* dynamic port forwarding */
1318 channel_pre_dynamic(Channel *c, fd_set *readset, fd_set *writeset)
1324 have = buffer_len(&c->input);
1325 debug2("channel %d: pre_dynamic: have %d", c->self, have);
1326 /* buffer_dump(&c->input); */
1327 /* check if the fixed size part of the packet is in buffer. */
1330 FD_SET(c->sock, readset);
1333 /* try to guess the protocol */
1334 p = buffer_ptr(&c->input);
1337 ret = channel_decode_socks4(c, readset, writeset);
1340 ret = channel_decode_socks5(c, readset, writeset);
1348 } else if (ret == 0) {
1349 debug2("channel %d: pre_dynamic: need more", c->self);
1351 FD_SET(c->sock, readset);
1353 /* switch to the next state */
1354 c->type = SSH_CHANNEL_OPENING;
1355 port_open_helper(c, "direct-tcpip");
1359 /* This is our fake X11 server socket. */
1362 channel_post_x11_listener(Channel *c, fd_set *readset, fd_set *writeset)
1365 struct sockaddr_storage addr;
1366 int newsock, oerrno;
1368 char buf[16384], *remote_ipaddr;
1371 if (FD_ISSET(c->sock, readset)) {
1372 debug("X11 connection requested.");
1373 addrlen = sizeof(addr);
1374 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1375 if (c->single_connection) {
1377 debug2("single_connection: closing X11 listener.");
1378 channel_close_fd(&c->sock);
1383 if (errno != EINTR && errno != EWOULDBLOCK &&
1384 errno != ECONNABORTED)
1385 error("accept: %.100s", strerror(errno));
1386 if (errno == EMFILE || errno == ENFILE)
1387 c->notbefore = monotime() + 1;
1390 set_nodelay(newsock);
1391 remote_ipaddr = get_peer_ipaddr(newsock);
1392 remote_port = get_peer_port(newsock);
1393 snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
1394 remote_ipaddr, remote_port);
1396 nc = channel_new("accepted x11 socket",
1397 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1398 c->local_window_max, c->local_maxpacket, 0, buf, 1);
1400 packet_start(SSH2_MSG_CHANNEL_OPEN);
1401 packet_put_cstring("x11");
1402 packet_put_int(nc->self);
1403 packet_put_int(nc->local_window_max);
1404 packet_put_int(nc->local_maxpacket);
1405 /* originator ipaddr and port */
1406 packet_put_cstring(remote_ipaddr);
1407 if (datafellows & SSH_BUG_X11FWD) {
1408 debug2("ssh2 x11 bug compat mode");
1410 packet_put_int(remote_port);
1414 packet_start(SSH_SMSG_X11_OPEN);
1415 packet_put_int(nc->self);
1416 if (packet_get_protocol_flags() &
1417 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1418 packet_put_cstring(buf);
1421 free(remote_ipaddr);
1426 port_open_helper(Channel *c, char *rtype)
1430 char *local_ipaddr = get_local_ipaddr(c->sock);
1431 int local_port = get_sock_port(c->sock, 1);
1432 char *remote_ipaddr = get_peer_ipaddr(c->sock);
1433 int remote_port = get_peer_port(c->sock);
1435 if (remote_port == -1) {
1436 /* Fake addr/port to appease peers that validate it (Tectia) */
1437 free(remote_ipaddr);
1438 remote_ipaddr = xstrdup("127.0.0.1");
1439 remote_port = 65535;
1442 direct = (strcmp(rtype, "direct-tcpip") == 0);
1444 snprintf(buf, sizeof buf,
1445 "%s: listening port %d for %.100s port %d, "
1446 "connect from %.200s port %d to %.100s port %d",
1447 rtype, c->listening_port, c->path, c->host_port,
1448 remote_ipaddr, remote_port, local_ipaddr, local_port);
1450 free(c->remote_name);
1451 c->remote_name = xstrdup(buf);
1454 packet_start(SSH2_MSG_CHANNEL_OPEN);
1455 packet_put_cstring(rtype);
1456 packet_put_int(c->self);
1457 packet_put_int(c->local_window_max);
1458 packet_put_int(c->local_maxpacket);
1460 /* target host, port */
1461 packet_put_cstring(c->path);
1462 packet_put_int(c->host_port);
1464 /* listen address, port */
1465 packet_put_cstring(c->path);
1466 packet_put_int(local_port);
1468 /* originator host and port */
1469 packet_put_cstring(remote_ipaddr);
1470 packet_put_int((u_int)remote_port);
1473 packet_start(SSH_MSG_PORT_OPEN);
1474 packet_put_int(c->self);
1475 packet_put_cstring(c->path);
1476 packet_put_int(c->host_port);
1477 if (packet_get_protocol_flags() &
1478 SSH_PROTOFLAG_HOST_IN_FWD_OPEN)
1479 packet_put_cstring(c->remote_name);
1482 free(remote_ipaddr);
1487 channel_set_reuseaddr(int fd)
1492 * Set socket options.
1493 * Allow local port reuse in TIME_WAIT.
1495 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1)
1496 error("setsockopt SO_REUSEADDR fd %d: %s", fd, strerror(errno));
1500 * This socket is listening for connections to a forwarded TCP/IP port.
1504 channel_post_port_listener(Channel *c, fd_set *readset, fd_set *writeset)
1507 struct sockaddr_storage addr;
1508 int newsock, nextstate;
1512 if (FD_ISSET(c->sock, readset)) {
1513 debug("Connection to port %d forwarding "
1514 "to %.100s port %d requested.",
1515 c->listening_port, c->path, c->host_port);
1517 if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
1518 nextstate = SSH_CHANNEL_OPENING;
1519 rtype = "forwarded-tcpip";
1521 if (c->host_port == 0) {
1522 nextstate = SSH_CHANNEL_DYNAMIC;
1523 rtype = "dynamic-tcpip";
1525 nextstate = SSH_CHANNEL_OPENING;
1526 rtype = "direct-tcpip";
1530 addrlen = sizeof(addr);
1531 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1533 if (errno != EINTR && errno != EWOULDBLOCK &&
1534 errno != ECONNABORTED)
1535 error("accept: %.100s", strerror(errno));
1536 if (errno == EMFILE || errno == ENFILE)
1537 c->notbefore = monotime() + 1;
1540 set_nodelay(newsock);
1541 nc = channel_new(rtype, nextstate, newsock, newsock, -1,
1542 c->local_window_max, c->local_maxpacket, 0, rtype, 1);
1543 nc->listening_port = c->listening_port;
1544 nc->host_port = c->host_port;
1545 if (c->path != NULL)
1546 nc->path = xstrdup(c->path);
1548 if (nextstate != SSH_CHANNEL_DYNAMIC)
1549 port_open_helper(nc, rtype);
1554 * This is the authentication agent socket listening for connections from
1559 channel_post_auth_listener(Channel *c, fd_set *readset, fd_set *writeset)
1563 struct sockaddr_storage addr;
1566 if (FD_ISSET(c->sock, readset)) {
1567 addrlen = sizeof(addr);
1568 newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
1570 error("accept from auth socket: %.100s",
1572 if (errno == EMFILE || errno == ENFILE)
1573 c->notbefore = monotime() + 1;
1576 nc = channel_new("accepted auth socket",
1577 SSH_CHANNEL_OPENING, newsock, newsock, -1,
1578 c->local_window_max, c->local_maxpacket,
1579 0, "accepted auth socket", 1);
1581 packet_start(SSH2_MSG_CHANNEL_OPEN);
1582 packet_put_cstring("auth-agent@openssh.com");
1583 packet_put_int(nc->self);
1584 packet_put_int(c->local_window_max);
1585 packet_put_int(c->local_maxpacket);
1587 packet_start(SSH_SMSG_AGENT_OPEN);
1588 packet_put_int(nc->self);
1596 channel_post_connecting(Channel *c, fd_set *readset, fd_set *writeset)
1599 socklen_t sz = sizeof(err);
1601 if (FD_ISSET(c->sock, writeset)) {
1602 if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) < 0) {
1604 error("getsockopt SO_ERROR failed");
1607 debug("channel %d: connected to %s port %d",
1608 c->self, c->connect_ctx.host, c->connect_ctx.port);
1609 channel_connect_ctx_free(&c->connect_ctx);
1610 c->type = SSH_CHANNEL_OPEN;
1612 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
1613 packet_put_int(c->remote_id);
1614 packet_put_int(c->self);
1615 packet_put_int(c->local_window);
1616 packet_put_int(c->local_maxpacket);
1618 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
1619 packet_put_int(c->remote_id);
1620 packet_put_int(c->self);
1623 debug("channel %d: connection failed: %s",
1624 c->self, strerror(err));
1625 /* Try next address, if any */
1626 if ((sock = connect_next(&c->connect_ctx)) > 0) {
1628 c->sock = c->rfd = c->wfd = sock;
1629 channel_max_fd = channel_find_maxfd();
1632 /* Exhausted all addresses */
1633 error("connect_to %.100s port %d: failed.",
1634 c->connect_ctx.host, c->connect_ctx.port);
1635 channel_connect_ctx_free(&c->connect_ctx);
1637 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE);
1638 packet_put_int(c->remote_id);
1639 packet_put_int(SSH2_OPEN_CONNECT_FAILED);
1640 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
1641 packet_put_cstring(strerror(err));
1642 packet_put_cstring("");
1645 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
1646 packet_put_int(c->remote_id);
1656 channel_handle_rfd(Channel *c, fd_set *readset, fd_set *writeset)
1658 char buf[CHAN_RBUF];
1661 force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
1662 if (c->rfd != -1 && (force || FD_ISSET(c->rfd, readset))) {
1664 len = read(c->rfd, buf, sizeof(buf));
1665 if (len < 0 && (errno == EINTR ||
1666 ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
1668 #ifndef PTY_ZEROREAD
1671 if ((!c->isatty && len <= 0) ||
1672 (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
1674 debug2("channel %d: read<=0 rfd %d len %d",
1675 c->self, c->rfd, len);
1676 if (c->type != SSH_CHANNEL_OPEN) {
1677 debug2("channel %d: not open", c->self);
1680 } else if (compat13) {
1681 buffer_clear(&c->output);
1682 c->type = SSH_CHANNEL_INPUT_DRAINING;
1683 debug2("channel %d: input draining.", c->self);
1685 chan_read_failed(c);
1689 if (c->input_filter != NULL) {
1690 if (c->input_filter(c, buf, len) == -1) {
1691 debug2("channel %d: filter stops", c->self);
1692 chan_read_failed(c);
1694 } else if (c->datagram) {
1695 buffer_put_string(&c->input, buf, len);
1697 buffer_append(&c->input, buf, len);
1705 channel_handle_wfd(Channel *c, fd_set *readset, fd_set *writeset)
1708 u_char *data = NULL, *buf;
1709 u_int dlen, olen = 0;
1712 /* Send buffered output data to the socket. */
1714 FD_ISSET(c->wfd, writeset) &&
1715 buffer_len(&c->output) > 0) {
1716 olen = buffer_len(&c->output);
1717 if (c->output_filter != NULL) {
1718 if ((buf = c->output_filter(c, &data, &dlen)) == NULL) {
1719 debug2("channel %d: filter stops", c->self);
1720 if (c->type != SSH_CHANNEL_OPEN)
1723 chan_write_failed(c);
1726 } else if (c->datagram) {
1727 buf = data = buffer_get_string(&c->output, &dlen);
1729 buf = data = buffer_ptr(&c->output);
1730 dlen = buffer_len(&c->output);
1734 /* ignore truncated writes, datagrams might get lost */
1735 len = write(c->wfd, buf, dlen);
1737 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1738 errno == EWOULDBLOCK))
1741 if (c->type != SSH_CHANNEL_OPEN)
1744 chan_write_failed(c);
1750 /* XXX: Later AIX versions can't push as much data to tty */
1751 if (compat20 && c->wfd_isatty)
1752 dlen = MIN(dlen, 8*1024);
1755 len = write(c->wfd, buf, dlen);
1757 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
1760 if (c->type != SSH_CHANNEL_OPEN) {
1761 debug2("channel %d: not open", c->self);
1764 } else if (compat13) {
1765 buffer_clear(&c->output);
1766 debug2("channel %d: input draining.", c->self);
1767 c->type = SSH_CHANNEL_INPUT_DRAINING;
1769 chan_write_failed(c);
1773 #ifndef BROKEN_TCGETATTR_ICANON
1774 if (compat20 && c->isatty && dlen >= 1 && buf[0] != '\r') {
1775 if (tcgetattr(c->wfd, &tio) == 0 &&
1776 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
1778 * Simulate echo to reduce the impact of
1779 * traffic analysis. We need to match the
1780 * size of a SSH2_MSG_CHANNEL_DATA message
1781 * (4 byte channel id + buf)
1783 packet_send_ignore(4 + len);
1788 buffer_consume(&c->output, len);
1791 if (compat20 && olen > 0)
1792 c->local_consumed += olen - buffer_len(&c->output);
1797 channel_handle_efd(Channel *c, fd_set *readset, fd_set *writeset)
1799 char buf[CHAN_RBUF];
1802 /** XXX handle drain efd, too */
1804 if (c->extended_usage == CHAN_EXTENDED_WRITE &&
1805 FD_ISSET(c->efd, writeset) &&
1806 buffer_len(&c->extended) > 0) {
1807 len = write(c->efd, buffer_ptr(&c->extended),
1808 buffer_len(&c->extended));
1809 debug2("channel %d: written %d to efd %d",
1810 c->self, len, c->efd);
1811 if (len < 0 && (errno == EINTR || errno == EAGAIN ||
1812 errno == EWOULDBLOCK))
1815 debug2("channel %d: closing write-efd %d",
1817 channel_close_fd(&c->efd);
1819 buffer_consume(&c->extended, len);
1820 c->local_consumed += len;
1822 } else if (c->efd != -1 &&
1823 (c->extended_usage == CHAN_EXTENDED_READ ||
1824 c->extended_usage == CHAN_EXTENDED_IGNORE) &&
1825 (c->detach_close || FD_ISSET(c->efd, readset))) {
1826 len = read(c->efd, buf, sizeof(buf));
1827 debug2("channel %d: read %d from efd %d",
1828 c->self, len, c->efd);
1829 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
1830 errno == EWOULDBLOCK) && !c->detach_close)))
1833 debug2("channel %d: closing read-efd %d",
1835 channel_close_fd(&c->efd);
1837 if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
1838 debug3("channel %d: discard efd",
1841 buffer_append(&c->extended, buf, len);
1849 channel_check_window(Channel *c)
1851 if (c->type == SSH_CHANNEL_OPEN &&
1852 !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
1853 ((c->local_window_max - c->local_window >
1854 c->local_maxpacket*3) ||
1855 c->local_window < c->local_window_max/2) &&
1856 c->local_consumed > 0) {
1859 /* Adjust max window size if we are in a dynamic environment. */
1860 if (c->dynamic_window && c->tcpwinsz > c->local_window_max) {
1862 * Grow the window somewhat aggressively to maintain
1865 addition = 1.5 * (c->tcpwinsz - c->local_window_max);
1866 c->local_window_max += addition;
1868 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
1869 packet_put_int(c->remote_id);
1870 packet_put_int(c->local_consumed + addition);
1872 debug2("channel %d: window %d sent adjust %d",
1873 c->self, c->local_window,
1875 c->local_window += c->local_consumed + addition;
1876 c->local_consumed = 0;
1882 channel_post_open(Channel *c, fd_set *readset, fd_set *writeset)
1884 channel_handle_rfd(c, readset, writeset);
1885 channel_handle_wfd(c, readset, writeset);
1888 channel_handle_efd(c, readset, writeset);
1889 channel_check_window(c);
1893 read_mux(Channel *c, u_int need)
1895 char buf[CHAN_RBUF];
1899 if (buffer_len(&c->input) < need) {
1900 rlen = need - buffer_len(&c->input);
1901 len = read(c->rfd, buf, MIN(rlen, CHAN_RBUF));
1903 if (errno != EINTR && errno != EAGAIN) {
1904 debug2("channel %d: ctl read<=0 rfd %d len %d",
1905 c->self, c->rfd, len);
1906 chan_read_failed(c);
1910 buffer_append(&c->input, buf, len);
1912 return buffer_len(&c->input);
1916 channel_post_mux_client(Channel *c, fd_set *readset, fd_set *writeset)
1922 fatal("%s: entered with !compat20", __func__);
1924 if (c->rfd != -1 && !c->mux_pause && FD_ISSET(c->rfd, readset) &&
1925 (c->istate == CHAN_INPUT_OPEN ||
1926 c->istate == CHAN_INPUT_WAIT_DRAIN)) {
1928 * Don't not read past the precise end of packets to
1929 * avoid disrupting fd passing.
1931 if (read_mux(c, 4) < 4) /* read header */
1933 need = get_u32(buffer_ptr(&c->input));
1934 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
1935 if (need > CHANNEL_MUX_MAX_PACKET) {
1936 debug2("channel %d: packet too big %u > %u",
1937 c->self, CHANNEL_MUX_MAX_PACKET, need);
1938 chan_rcvd_oclose(c);
1941 if (read_mux(c, need + 4) < need + 4) /* read body */
1943 if (c->mux_rcb(c) != 0) {
1944 debug("channel %d: mux_rcb failed", c->self);
1950 if (c->wfd != -1 && FD_ISSET(c->wfd, writeset) &&
1951 buffer_len(&c->output) > 0) {
1952 len = write(c->wfd, buffer_ptr(&c->output),
1953 buffer_len(&c->output));
1954 if (len < 0 && (errno == EINTR || errno == EAGAIN))
1960 buffer_consume(&c->output, len);
1965 channel_post_mux_listener(Channel *c, fd_set *readset, fd_set *writeset)
1968 struct sockaddr_storage addr;
1974 if (!FD_ISSET(c->sock, readset))
1977 debug("multiplexing control connection");
1980 * Accept connection on control socket
1982 memset(&addr, 0, sizeof(addr));
1983 addrlen = sizeof(addr);
1984 if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
1986 error("%s accept: %s", __func__, strerror(errno));
1987 if (errno == EMFILE || errno == ENFILE)
1988 c->notbefore = monotime() + 1;
1992 if (getpeereid(newsock, &euid, &egid) < 0) {
1993 error("%s getpeereid failed: %s", __func__,
1998 if ((euid != 0) && (getuid() != euid)) {
1999 error("multiplex uid mismatch: peer euid %u != uid %u",
2000 (u_int)euid, (u_int)getuid());
2004 nc = channel_new("multiplex client", SSH_CHANNEL_MUX_CLIENT,
2005 newsock, newsock, -1, c->local_window_max,
2006 c->local_maxpacket, 0, "mux-control", 1);
2007 nc->mux_rcb = c->mux_rcb;
2008 debug3("%s: new mux channel %d fd %d", __func__,
2009 nc->self, nc->sock);
2010 /* establish state */
2012 /* mux state transitions must not elicit protocol messages */
2013 nc->flags |= CHAN_LOCAL;
2018 channel_post_output_drain_13(Channel *c, fd_set *readset, fd_set *writeset)
2022 /* Send buffered output data to the socket. */
2023 if (FD_ISSET(c->sock, writeset) && buffer_len(&c->output) > 0) {
2024 len = write(c->sock, buffer_ptr(&c->output),
2025 buffer_len(&c->output));
2027 buffer_clear(&c->output);
2029 buffer_consume(&c->output, len);
2034 channel_handler_init_20(void)
2036 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2037 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2038 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2039 channel_pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
2040 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2041 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2042 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2043 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2044 channel_pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
2045 channel_pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
2047 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2048 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2049 channel_post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
2050 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2051 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2052 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2053 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2054 channel_post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
2055 channel_post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
2059 channel_handler_init_13(void)
2061 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open_13;
2062 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open_13;
2063 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2064 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2065 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2066 channel_pre[SSH_CHANNEL_INPUT_DRAINING] = &channel_pre_input_draining;
2067 channel_pre[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_pre_output_draining;
2068 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2069 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2071 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2072 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2073 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2074 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2075 channel_post[SSH_CHANNEL_OUTPUT_DRAINING] = &channel_post_output_drain_13;
2076 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2077 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2081 channel_handler_init_15(void)
2083 channel_pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
2084 channel_pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
2085 channel_pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
2086 channel_pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
2087 channel_pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
2088 channel_pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
2089 channel_pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
2091 channel_post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
2092 channel_post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
2093 channel_post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
2094 channel_post[SSH_CHANNEL_OPEN] = &channel_post_open;
2095 channel_post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
2096 channel_post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
2100 channel_handler_init(void)
2104 for (i = 0; i < SSH_CHANNEL_MAX_TYPE; i++) {
2105 channel_pre[i] = NULL;
2106 channel_post[i] = NULL;
2109 channel_handler_init_20();
2111 channel_handler_init_13();
2113 channel_handler_init_15();
2116 /* gc dead channels */
2118 channel_garbage_collect(Channel *c)
2122 if (c->detach_user != NULL) {
2123 if (!chan_is_dead(c, c->detach_close))
2125 debug2("channel %d: gc: notify user", c->self);
2126 c->detach_user(c->self, NULL);
2127 /* if we still have a callback */
2128 if (c->detach_user != NULL)
2130 debug2("channel %d: gc: user detached", c->self);
2132 if (!chan_is_dead(c, 1))
2134 debug2("channel %d: garbage collecting", c->self);
2139 channel_handler(chan_fn *ftab[], fd_set *readset, fd_set *writeset,
2140 time_t *unpause_secs)
2142 static int did_init = 0;
2148 channel_handler_init();
2152 if (unpause_secs != NULL)
2154 for (i = 0, oalloc = channels_alloc; i < oalloc; i++) {
2159 if (ftab == channel_pre)
2164 if (ftab[c->type] != NULL) {
2166 * Run handlers that are not paused.
2168 if (c->notbefore <= now)
2169 (*ftab[c->type])(c, readset, writeset);
2170 else if (unpause_secs != NULL) {
2172 * Collect the time that the earliest
2173 * channel comes off pause.
2175 debug3("%s: chan %d: skip for %d more seconds",
2177 (int)(c->notbefore - now));
2178 if (*unpause_secs == 0 ||
2179 (c->notbefore - now) < *unpause_secs)
2180 *unpause_secs = c->notbefore - now;
2183 channel_garbage_collect(c);
2185 if (unpause_secs != NULL && *unpause_secs != 0)
2186 debug3("%s: first channel unpauses in %d seconds",
2187 __func__, (int)*unpause_secs);
2191 * Allocate/update select bitmasks and add any bits relevant to channels in
2195 channel_prepare_select(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
2196 u_int *nallocp, time_t *minwait_secs, int rekeying)
2198 u_int n, sz, nfdset;
2200 n = MAX(*maxfdp, channel_max_fd);
2202 nfdset = howmany(n+1, NFDBITS);
2203 /* Explicitly test here, because xrealloc isn't always called */
2204 if (nfdset && SIZE_T_MAX / nfdset < sizeof(fd_mask))
2205 fatal("channel_prepare_select: max_fd (%d) is too large", n);
2206 sz = nfdset * sizeof(fd_mask);
2208 /* perhaps check sz < nalloc/2 and shrink? */
2209 if (*readsetp == NULL || sz > *nallocp) {
2210 *readsetp = xrealloc(*readsetp, nfdset, sizeof(fd_mask));
2211 *writesetp = xrealloc(*writesetp, nfdset, sizeof(fd_mask));
2215 memset(*readsetp, 0, sz);
2216 memset(*writesetp, 0, sz);
2219 channel_handler(channel_pre, *readsetp, *writesetp,
2224 * After select, perform any appropriate operations for channels which have
2228 channel_after_select(fd_set *readset, fd_set *writeset)
2230 channel_handler(channel_post, readset, writeset, NULL);
2234 /* If there is data to send to the connection, enqueue some of it now. */
2236 channel_output_poll(void)
2241 for (i = 0; i < channels_alloc; i++) {
2247 * We are only interested in channels that can have buffered
2251 if (c->type != SSH_CHANNEL_OPEN &&
2252 c->type != SSH_CHANNEL_INPUT_DRAINING)
2255 if (c->type != SSH_CHANNEL_OPEN)
2259 (c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
2260 /* XXX is this true? */
2261 debug3("channel %d: will not send data after close", c->self);
2265 /* Get the amount of buffered data for this channel. */
2266 if ((c->istate == CHAN_INPUT_OPEN ||
2267 c->istate == CHAN_INPUT_WAIT_DRAIN) &&
2268 (len = buffer_len(&c->input)) > 0) {
2274 data = buffer_get_string(&c->input,
2276 if (dlen > c->remote_window ||
2277 dlen > c->remote_maxpacket) {
2278 debug("channel %d: datagram "
2279 "too big for channel",
2284 packet_start(SSH2_MSG_CHANNEL_DATA);
2285 packet_put_int(c->remote_id);
2286 packet_put_string(data, dlen);
2288 c->remote_window -= dlen + 4;
2294 * Send some data for the other side over the secure
2298 if (len > c->remote_window)
2299 len = c->remote_window;
2300 if (len > c->remote_maxpacket)
2301 len = c->remote_maxpacket;
2303 if (packet_is_interactive()) {
2307 /* Keep the packets at reasonable size. */
2308 if (len > packet_get_maxsize()/2)
2309 len = packet_get_maxsize()/2;
2313 packet_start(compat20 ?
2314 SSH2_MSG_CHANNEL_DATA : SSH_MSG_CHANNEL_DATA);
2315 packet_put_int(c->remote_id);
2316 packet_put_string(buffer_ptr(&c->input), len);
2318 buffer_consume(&c->input, len);
2319 c->remote_window -= len;
2321 } else if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
2323 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2325 * input-buffer is empty and read-socket shutdown:
2326 * tell peer, that we will not send more data: send IEOF.
2327 * hack for extended data: delay EOF if EFD still in use.
2329 if (CHANNEL_EFD_INPUT_ACTIVE(c))
2330 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2331 c->self, c->efd, buffer_len(&c->extended));
2335 /* Send extended data, i.e. stderr */
2337 !(c->flags & CHAN_EOF_SENT) &&
2338 c->remote_window > 0 &&
2339 (len = buffer_len(&c->extended)) > 0 &&
2340 c->extended_usage == CHAN_EXTENDED_READ) {
2341 debug2("channel %d: rwin %u elen %u euse %d",
2342 c->self, c->remote_window, buffer_len(&c->extended),
2344 if (len > c->remote_window)
2345 len = c->remote_window;
2346 if (len > c->remote_maxpacket)
2347 len = c->remote_maxpacket;
2348 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA);
2349 packet_put_int(c->remote_id);
2350 packet_put_int(SSH2_EXTENDED_DATA_STDERR);
2351 packet_put_string(buffer_ptr(&c->extended), len);
2353 buffer_consume(&c->extended, len);
2354 c->remote_window -= len;
2355 debug2("channel %d: sent ext data %d", c->self, len);
2361 /* -- protocol input */
2365 channel_input_data(int type, u_int32_t seq, void *ctxt)
2369 u_int data_len, win_len;
2372 /* Get the channel number and verify it. */
2373 id = packet_get_int();
2374 c = channel_lookup(id);
2376 packet_disconnect("Received data for nonexistent channel %d.", id);
2378 /* Ignore any data for non-open channels (might happen on close) */
2379 if (c->type != SSH_CHANNEL_OPEN &&
2380 c->type != SSH_CHANNEL_X11_OPEN)
2384 data = packet_get_string_ptr(&data_len);
2387 win_len += 4; /* string length header */
2390 * Ignore data for protocol > 1.3 if output end is no longer open.
2391 * For protocol 2 the sending side is reducing its window as it sends
2392 * data, so we must 'fake' consumption of the data in order to ensure
2393 * that window updates are sent back. Otherwise the connection might
2396 if (!compat13 && c->ostate != CHAN_OUTPUT_OPEN) {
2398 c->local_window -= win_len;
2399 c->local_consumed += win_len;
2405 if (win_len > c->local_maxpacket) {
2406 logit("channel %d: rcvd big packet %d, maxpack %d",
2407 c->self, win_len, c->local_maxpacket);
2409 if (win_len > c->local_window) {
2410 logit("channel %d: rcvd too much data %d, win %d",
2411 c->self, win_len, c->local_window);
2414 c->local_window -= win_len;
2417 buffer_put_string(&c->output, data, data_len);
2419 buffer_append(&c->output, data, data_len);
2425 channel_input_extended_data(int type, u_int32_t seq, void *ctxt)
2429 u_int data_len, tcode;
2432 /* Get the channel number and verify it. */
2433 id = packet_get_int();
2434 c = channel_lookup(id);
2437 packet_disconnect("Received extended_data for bad channel %d.", id);
2438 if (c->type != SSH_CHANNEL_OPEN) {
2439 logit("channel %d: ext data for non open", id);
2442 if (c->flags & CHAN_EOF_RCVD) {
2443 if (datafellows & SSH_BUG_EXTEOF)
2444 debug("channel %d: accepting ext data after eof", id);
2446 packet_disconnect("Received extended_data after EOF "
2447 "on channel %d.", id);
2449 tcode = packet_get_int();
2451 c->extended_usage != CHAN_EXTENDED_WRITE ||
2452 tcode != SSH2_EXTENDED_DATA_STDERR) {
2453 logit("channel %d: bad ext data", c->self);
2456 data = packet_get_string(&data_len);
2458 if (data_len > c->local_window) {
2459 logit("channel %d: rcvd too much extended_data %d, win %d",
2460 c->self, data_len, c->local_window);
2464 debug2("channel %d: rcvd ext data %d", c->self, data_len);
2465 c->local_window -= data_len;
2466 buffer_append(&c->extended, data, data_len);
2472 channel_input_ieof(int type, u_int32_t seq, void *ctxt)
2477 id = packet_get_int();
2479 c = channel_lookup(id);
2481 packet_disconnect("Received ieof for nonexistent channel %d.", id);
2484 /* XXX force input close */
2485 if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
2486 debug("channel %d: FORCE input drain", c->self);
2487 c->istate = CHAN_INPUT_WAIT_DRAIN;
2488 if (buffer_len(&c->input) == 0)
2496 channel_input_close(int type, u_int32_t seq, void *ctxt)
2501 id = packet_get_int();
2503 c = channel_lookup(id);
2505 packet_disconnect("Received close for nonexistent channel %d.", id);
2508 * Send a confirmation that we have closed the channel and no more
2509 * data is coming for it.
2511 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION);
2512 packet_put_int(c->remote_id);
2516 * If the channel is in closed state, we have sent a close request,
2517 * and the other side will eventually respond with a confirmation.
2518 * Thus, we cannot free the channel here, because then there would be
2519 * no-one to receive the confirmation. The channel gets freed when
2520 * the confirmation arrives.
2522 if (c->type != SSH_CHANNEL_CLOSED) {
2524 * Not a closed channel - mark it as draining, which will
2525 * cause it to be freed later.
2527 buffer_clear(&c->input);
2528 c->type = SSH_CHANNEL_OUTPUT_DRAINING;
2532 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2535 channel_input_oclose(int type, u_int32_t seq, void *ctxt)
2537 int id = packet_get_int();
2538 Channel *c = channel_lookup(id);
2542 packet_disconnect("Received oclose for nonexistent channel %d.", id);
2543 chan_rcvd_oclose(c);
2548 channel_input_close_confirmation(int type, u_int32_t seq, void *ctxt)
2550 int id = packet_get_int();
2551 Channel *c = channel_lookup(id);
2555 packet_disconnect("Received close confirmation for "
2556 "out-of-range channel %d.", id);
2557 if (c->type != SSH_CHANNEL_CLOSED && c->type != SSH_CHANNEL_ABANDONED)
2558 packet_disconnect("Received close confirmation for "
2559 "non-closed channel %d (type %d).", id, c->type);
2565 channel_input_open_confirmation(int type, u_int32_t seq, void *ctxt)
2570 id = packet_get_int();
2571 c = channel_lookup(id);
2573 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2574 packet_disconnect("Received open confirmation for "
2575 "non-opening channel %d.", id);
2576 remote_id = packet_get_int();
2577 /* Record the remote channel number and mark that the channel is now open. */
2578 c->remote_id = remote_id;
2579 c->type = SSH_CHANNEL_OPEN;
2582 c->remote_window = packet_get_int();
2583 c->remote_maxpacket = packet_get_int();
2584 if (c->open_confirm) {
2585 debug2("callback start");
2586 c->open_confirm(c->self, 1, c->open_confirm_ctx);
2587 debug2("callback done");
2589 debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
2590 c->remote_window, c->remote_maxpacket);
2596 reason2txt(int reason)
2599 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
2600 return "administratively prohibited";
2601 case SSH2_OPEN_CONNECT_FAILED:
2602 return "connect failed";
2603 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
2604 return "unknown channel type";
2605 case SSH2_OPEN_RESOURCE_SHORTAGE:
2606 return "resource shortage";
2608 return "unknown reason";
2613 channel_input_open_failure(int type, u_int32_t seq, void *ctxt)
2616 char *msg = NULL, *lang = NULL;
2619 id = packet_get_int();
2620 c = channel_lookup(id);
2622 if (c==NULL || c->type != SSH_CHANNEL_OPENING)
2623 packet_disconnect("Received open failure for "
2624 "non-opening channel %d.", id);
2626 reason = packet_get_int();
2627 if (!(datafellows & SSH_BUG_OPENFAILURE)) {
2628 msg = packet_get_string(NULL);
2629 lang = packet_get_string(NULL);
2631 logit("channel %d: open failed: %s%s%s", id,
2632 reason2txt(reason), msg ? ": ": "", msg ? msg : "");
2635 if (c->open_confirm) {
2636 debug2("callback start");
2637 c->open_confirm(c->self, 0, c->open_confirm_ctx);
2638 debug2("callback done");
2642 /* Schedule the channel for cleanup/deletion. */
2648 channel_input_window_adjust(int type, u_int32_t seq, void *ctxt)
2657 /* Get the channel number and verify it. */
2658 id = packet_get_int();
2659 c = channel_lookup(id);
2662 logit("Received window adjust for non-open channel %d.", id);
2665 adjust = packet_get_int();
2667 debug2("channel %d: rcvd adjust %u", id, adjust);
2668 c->remote_window += adjust;
2673 channel_input_port_open(int type, u_int32_t seq, void *ctxt)
2677 char *host, *originator_string;
2680 remote_id = packet_get_int();
2681 host = packet_get_string(NULL);
2682 host_port = packet_get_int();
2684 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
2685 originator_string = packet_get_string(NULL);
2687 originator_string = xstrdup("unknown (remote did not supply name)");
2690 c = channel_connect_to(host, host_port,
2691 "connected socket", originator_string);
2692 free(originator_string);
2695 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
2696 packet_put_int(remote_id);
2699 c->remote_id = remote_id;
2704 channel_input_status_confirm(int type, u_int32_t seq, void *ctxt)
2707 struct channel_confirm *cc;
2710 /* Reset keepalive timeout */
2711 packet_set_alive_timeouts(0);
2713 id = packet_get_int();
2716 debug2("channel_input_status_confirm: type %d id %d", type, id);
2718 if ((c = channel_lookup(id)) == NULL) {
2719 logit("channel_input_status_confirm: %d: unknown", id);
2723 if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
2725 cc->cb(type, c, cc->ctx);
2726 TAILQ_REMOVE(&c->status_confirms, cc, entry);
2727 bzero(cc, sizeof(*cc));
2731 /* -- tcp forwarding */
2734 channel_set_af(int af)
2740 channel_set_hpn(int disabled, u_int buf_size)
2742 hpn_disabled = disabled;
2743 buffer_size = buf_size;
2744 debug("HPN Disabled: %d, HPN Buffer Size: %d",
2745 hpn_disabled, buffer_size);
2749 * Determine whether or not a port forward listens to loopback, the
2750 * specified address or wildcard. On the client, a specified bind
2751 * address will always override gateway_ports. On the server, a
2752 * gateway_ports of 1 (``yes'') will override the client's specification
2753 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
2754 * will bind to whatever address the client asked for.
2756 * Special-case listen_addrs are:
2758 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2759 * "" (empty string), "*" -> wildcard v4/v6
2760 * "localhost" -> loopback v4/v6
2763 channel_fwd_bind_addr(const char *listen_addr, int *wildcardp,
2764 int is_client, int gateway_ports)
2766 const char *addr = NULL;
2769 if (listen_addr == NULL) {
2770 /* No address specified: default to gateway_ports setting */
2773 } else if (gateway_ports || is_client) {
2774 if (((datafellows & SSH_OLD_FORWARD_ADDR) &&
2775 strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
2776 *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
2777 (!is_client && gateway_ports == 1)) {
2780 * Notify client if they requested a specific listen
2781 * address and it was overridden.
2783 if (*listen_addr != '\0' &&
2784 strcmp(listen_addr, "0.0.0.0") != 0 &&
2785 strcmp(listen_addr, "*") != 0) {
2786 packet_send_debug("Forwarding listen address "
2787 "\"%s\" overridden by server "
2788 "GatewayPorts", listen_addr);
2791 else if (strcmp(listen_addr, "localhost") != 0)
2794 if (wildcardp != NULL)
2795 *wildcardp = wildcard;
2800 channel_setup_fwd_listener(int type, const char *listen_addr,
2801 u_short listen_port, int *allocated_listen_port,
2802 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
2805 int sock, r, success = 0, wildcard = 0, is_client;
2806 struct addrinfo hints, *ai, *aitop;
2807 const char *host, *addr;
2808 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
2811 host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
2812 listen_addr : host_to_connect;
2813 is_client = (type == SSH_CHANNEL_PORT_LISTENER);
2816 error("No forward host name.");
2819 if (strlen(host) >= NI_MAXHOST) {
2820 error("Forward host name too long.");
2824 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
2825 addr = channel_fwd_bind_addr(listen_addr, &wildcard,
2826 is_client, gateway_ports);
2827 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2828 type, wildcard, (addr == NULL) ? "NULL" : addr);
2831 * getaddrinfo returns a loopback address if the hostname is
2832 * set to NULL and hints.ai_flags is not AI_PASSIVE
2834 memset(&hints, 0, sizeof(hints));
2835 hints.ai_family = IPv4or6;
2836 hints.ai_flags = wildcard ? AI_PASSIVE : 0;
2837 hints.ai_socktype = SOCK_STREAM;
2838 snprintf(strport, sizeof strport, "%d", listen_port);
2839 if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
2841 /* This really shouldn't happen */
2842 packet_disconnect("getaddrinfo: fatal error: %s",
2843 ssh_gai_strerror(r));
2845 error("channel_setup_fwd_listener: "
2846 "getaddrinfo(%.64s): %s", addr,
2847 ssh_gai_strerror(r));
2851 if (allocated_listen_port != NULL)
2852 *allocated_listen_port = 0;
2853 for (ai = aitop; ai; ai = ai->ai_next) {
2854 switch (ai->ai_family) {
2856 lport_p = &((struct sockaddr_in *)ai->ai_addr)->
2860 lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
2867 * If allocating a port for -R forwards, then use the
2868 * same port for all address families.
2870 if (type == SSH_CHANNEL_RPORT_LISTENER && listen_port == 0 &&
2871 allocated_listen_port != NULL && *allocated_listen_port > 0)
2872 *lport_p = htons(*allocated_listen_port);
2874 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
2875 strport, sizeof(strport), NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
2876 error("channel_setup_fwd_listener: getnameinfo failed");
2879 /* Create a port to listen for the host. */
2880 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
2882 /* this is no error since kernel may not support ipv6 */
2883 verbose("socket: %.100s", strerror(errno));
2887 channel_set_reuseaddr(sock);
2888 if (ai->ai_family == AF_INET6)
2889 sock_set_v6only(sock);
2891 debug("Local forwarding listening on %s port %s.",
2894 /* Bind the socket to the address. */
2895 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
2896 /* address can be in use ipv6 address is already bound */
2898 error("bind: %.100s", strerror(errno));
2900 verbose("bind: %.100s", strerror(errno));
2905 /* Start listening for connections on the socket. */
2906 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
2907 error("listen: %.100s", strerror(errno));
2913 * listen_port == 0 requests a dynamically allocated port -
2914 * record what we got.
2916 if (type == SSH_CHANNEL_RPORT_LISTENER && listen_port == 0 &&
2917 allocated_listen_port != NULL &&
2918 *allocated_listen_port == 0) {
2919 *allocated_listen_port = get_sock_port(sock, 1);
2920 debug("Allocated listen port %d",
2921 *allocated_listen_port);
2925 * Allocate a channel number for the socket. Explicitly test
2926 * for hpn disabled option. If true use smaller window size.
2929 c = channel_new("port listener", type, sock, sock, -1,
2930 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
2931 0, "port listener", 1);
2933 c = channel_new("port listener", type, sock, sock, -1,
2934 buffer_size, CHAN_TCP_PACKET_DEFAULT,
2935 0, "port listener", 1);
2936 c->path = xstrdup(host);
2937 c->host_port = port_to_connect;
2938 c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
2939 if (listen_port == 0 && allocated_listen_port != NULL &&
2940 !(datafellows & SSH_BUG_DYNAMIC_RPORT))
2941 c->listening_port = *allocated_listen_port;
2943 c->listening_port = listen_port;
2947 error("channel_setup_fwd_listener: cannot listen to port: %d",
2949 freeaddrinfo(aitop);
2954 channel_cancel_rport_listener(const char *host, u_short port)
2959 for (i = 0; i < channels_alloc; i++) {
2960 Channel *c = channels[i];
2961 if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
2963 if (strcmp(c->path, host) == 0 && c->listening_port == port) {
2964 debug2("%s: close channel %d", __func__, i);
2974 channel_cancel_lport_listener(const char *lhost, u_short lport,
2975 int cport, int gateway_ports)
2979 const char *addr = channel_fwd_bind_addr(lhost, NULL, 1, gateway_ports);
2981 for (i = 0; i < channels_alloc; i++) {
2982 Channel *c = channels[i];
2983 if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
2985 if (c->listening_port != lport)
2987 if (cport == CHANNEL_CANCEL_PORT_STATIC) {
2988 /* skip dynamic forwardings */
2989 if (c->host_port == 0)
2992 if (c->host_port != cport)
2995 if ((c->listening_addr == NULL && addr != NULL) ||
2996 (c->listening_addr != NULL && addr == NULL))
2998 if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
2999 debug2("%s: close channel %d", __func__, i);
3008 /* protocol local port fwd, used by ssh (and sshd in v1) */
3010 channel_setup_local_fwd_listener(const char *listen_host, u_short listen_port,
3011 const char *host_to_connect, u_short port_to_connect, int gateway_ports)
3013 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER,
3014 listen_host, listen_port, NULL, host_to_connect, port_to_connect,
3018 /* protocol v2 remote port fwd, used by sshd */
3020 channel_setup_remote_fwd_listener(const char *listen_address,
3021 u_short listen_port, int *allocated_listen_port, int gateway_ports)
3023 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER,
3024 listen_address, listen_port, allocated_listen_port,
3025 NULL, 0, gateway_ports);
3029 * Translate the requested rfwd listen host to something usable for
3033 channel_rfwd_bind_host(const char *listen_host)
3035 if (listen_host == NULL) {
3036 if (datafellows & SSH_BUG_RFWD_ADDR)
3040 } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
3041 if (datafellows & SSH_BUG_RFWD_ADDR)
3050 * Initiate forwarding of connections to port "port" on remote host through
3051 * the secure channel to host:port from local side.
3052 * Returns handle (index) for updating the dynamic listen port with
3053 * channel_update_permitted_opens().
3056 channel_request_remote_forwarding(const char *listen_host, u_short listen_port,
3057 const char *host_to_connect, u_short port_to_connect)
3059 int type, success = 0, idx = -1;
3061 /* Send the forward request to the remote side. */
3063 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3064 packet_put_cstring("tcpip-forward");
3065 packet_put_char(1); /* boolean: want reply */
3066 packet_put_cstring(channel_rfwd_bind_host(listen_host));
3067 packet_put_int(listen_port);
3069 packet_write_wait();
3070 /* Assume that server accepts the request */
3073 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST);
3074 packet_put_int(listen_port);
3075 packet_put_cstring(host_to_connect);
3076 packet_put_int(port_to_connect);
3078 packet_write_wait();
3080 /* Wait for response from the remote side. */
3081 type = packet_read();
3083 case SSH_SMSG_SUCCESS:
3086 case SSH_SMSG_FAILURE:
3089 /* Unknown packet */
3090 packet_disconnect("Protocol error for port forward request:"
3091 "received packet type %d.", type);
3095 /* Record that connection to this host/port is permitted. */
3096 permitted_opens = xrealloc(permitted_opens,
3097 num_permitted_opens + 1, sizeof(*permitted_opens));
3098 idx = num_permitted_opens++;
3099 permitted_opens[idx].host_to_connect = xstrdup(host_to_connect);
3100 permitted_opens[idx].port_to_connect = port_to_connect;
3101 permitted_opens[idx].listen_port = listen_port;
3107 * Request cancellation of remote forwarding of connection host:port from
3111 channel_request_rforward_cancel(const char *host, u_short port)
3118 for (i = 0; i < num_permitted_opens; i++) {
3119 if (permitted_opens[i].host_to_connect != NULL &&
3120 permitted_opens[i].listen_port == port)
3123 if (i >= num_permitted_opens) {
3124 debug("%s: requested forward not found", __func__);
3127 packet_start(SSH2_MSG_GLOBAL_REQUEST);
3128 packet_put_cstring("cancel-tcpip-forward");
3130 packet_put_cstring(channel_rfwd_bind_host(host));
3131 packet_put_int(port);
3134 permitted_opens[i].listen_port = 0;
3135 permitted_opens[i].port_to_connect = 0;
3136 free(permitted_opens[i].host_to_connect);
3137 permitted_opens[i].host_to_connect = NULL;
3143 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
3144 * listening for the port, and sends back a success reply (or disconnect
3145 * message if there was an error).
3148 channel_input_port_forward_request(int is_root, int gateway_ports)
3150 u_short port, host_port;
3154 /* Get arguments from the packet. */
3155 port = packet_get_int();
3156 hostname = packet_get_string(NULL);
3157 host_port = packet_get_int();
3161 * Check that an unprivileged user is not trying to forward a
3164 if (port < IPPORT_RESERVED && !is_root)
3166 "Requested forwarding of port %d but user is not root.",
3169 packet_disconnect("Dynamic forwarding denied.");
3172 /* Initiate forwarding */
3173 success = channel_setup_local_fwd_listener(NULL, port, hostname,
3174 host_port, gateway_ports);
3176 /* Free the argument string. */
3179 return (success ? 0 : -1);
3183 * Permits opening to any host/port if permitted_opens[] is empty. This is
3184 * usually called by the server, because the user could connect to any port
3185 * anyway, and the server has no way to know but to trust the client anyway.
3188 channel_permit_all_opens(void)
3190 if (num_permitted_opens == 0)
3191 all_opens_permitted = 1;
3195 channel_add_permitted_opens(char *host, int port)
3197 debug("allow port forwarding to host %s port %d", host, port);
3199 permitted_opens = xrealloc(permitted_opens,
3200 num_permitted_opens + 1, sizeof(*permitted_opens));
3201 permitted_opens[num_permitted_opens].host_to_connect = xstrdup(host);
3202 permitted_opens[num_permitted_opens].port_to_connect = port;
3203 num_permitted_opens++;
3205 all_opens_permitted = 0;
3209 * Update the listen port for a dynamic remote forward, after
3210 * the actual 'newport' has been allocated. If 'newport' < 0 is
3211 * passed then they entry will be invalidated.
3214 channel_update_permitted_opens(int idx, int newport)
3216 if (idx < 0 || idx >= num_permitted_opens) {
3217 debug("channel_update_permitted_opens: index out of range:"
3218 " %d num_permitted_opens %d", idx, num_permitted_opens);
3221 debug("%s allowed port %d for forwarding to host %s port %d",
3222 newport > 0 ? "Updating" : "Removing",
3224 permitted_opens[idx].host_to_connect,
3225 permitted_opens[idx].port_to_connect);
3227 permitted_opens[idx].listen_port =
3228 (datafellows & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
3230 permitted_opens[idx].listen_port = 0;
3231 permitted_opens[idx].port_to_connect = 0;
3232 free(permitted_opens[idx].host_to_connect);
3233 permitted_opens[idx].host_to_connect = NULL;
3238 channel_add_adm_permitted_opens(char *host, int port)
3240 debug("config allows port forwarding to host %s port %d", host, port);
3242 permitted_adm_opens = xrealloc(permitted_adm_opens,
3243 num_adm_permitted_opens + 1, sizeof(*permitted_adm_opens));
3244 permitted_adm_opens[num_adm_permitted_opens].host_to_connect
3246 permitted_adm_opens[num_adm_permitted_opens].port_to_connect = port;
3247 return ++num_adm_permitted_opens;
3251 channel_disable_adm_local_opens(void)
3253 channel_clear_adm_permitted_opens();
3254 permitted_adm_opens = xmalloc(sizeof(*permitted_adm_opens));
3255 permitted_adm_opens[num_adm_permitted_opens].host_to_connect = NULL;
3256 num_adm_permitted_opens = 1;
3260 channel_clear_permitted_opens(void)
3264 for (i = 0; i < num_permitted_opens; i++)
3265 free(permitted_opens[i].host_to_connect);
3266 free(permitted_opens);
3267 permitted_opens = NULL;
3268 num_permitted_opens = 0;
3272 channel_clear_adm_permitted_opens(void)
3276 for (i = 0; i < num_adm_permitted_opens; i++)
3277 free(permitted_adm_opens[i].host_to_connect);
3278 free(permitted_adm_opens);
3279 permitted_adm_opens = NULL;
3280 num_adm_permitted_opens = 0;
3284 channel_print_adm_permitted_opens(void)
3288 printf("permitopen");
3289 if (num_adm_permitted_opens == 0) {
3293 for (i = 0; i < num_adm_permitted_opens; i++)
3294 if (permitted_adm_opens[i].host_to_connect == NULL)
3297 printf(" %s:%d", permitted_adm_opens[i].host_to_connect,
3298 permitted_adm_opens[i].port_to_connect);
3302 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
3304 permitopen_port(const char *p)
3308 if (strcmp(p, "*") == 0)
3309 return FWD_PERMIT_ANY_PORT;
3310 if ((port = a2port(p)) > 0)
3316 port_match(u_short allowedport, u_short requestedport)
3318 if (allowedport == FWD_PERMIT_ANY_PORT ||
3319 allowedport == requestedport)
3324 /* Try to start non-blocking connect to next host in cctx list */
3326 connect_next(struct channel_connect *cctx)
3328 int sock, saved_errno;
3329 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
3331 for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
3332 if (cctx->ai->ai_family != AF_INET &&
3333 cctx->ai->ai_family != AF_INET6)
3335 if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
3336 ntop, sizeof(ntop), strport, sizeof(strport),
3337 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
3338 error("connect_next: getnameinfo failed");
3341 if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
3342 cctx->ai->ai_protocol)) == -1) {
3343 if (cctx->ai->ai_next == NULL)
3344 error("socket: %.100s", strerror(errno));
3346 verbose("socket: %.100s", strerror(errno));
3349 if (set_nonblock(sock) == -1)
3350 fatal("%s: set_nonblock(%d)", __func__, sock);
3351 if (connect(sock, cctx->ai->ai_addr,
3352 cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
3353 debug("connect_next: host %.100s ([%.100s]:%s): "
3354 "%.100s", cctx->host, ntop, strport,
3356 saved_errno = errno;
3358 errno = saved_errno;
3359 continue; /* fail -- try next */
3361 debug("connect_next: host %.100s ([%.100s]:%s) "
3362 "in progress, fd=%d", cctx->host, ntop, strport, sock);
3363 cctx->ai = cctx->ai->ai_next;
3371 channel_connect_ctx_free(struct channel_connect *cctx)
3375 freeaddrinfo(cctx->aitop);
3376 bzero(cctx, sizeof(*cctx));
3378 cctx->ai = cctx->aitop = NULL;
3381 /* Return CONNECTING channel to remote host, port */
3383 connect_to(const char *host, u_short port, char *ctype, char *rname)
3385 struct addrinfo hints;
3388 char strport[NI_MAXSERV];
3389 struct channel_connect cctx;
3392 memset(&cctx, 0, sizeof(cctx));
3393 memset(&hints, 0, sizeof(hints));
3394 hints.ai_family = IPv4or6;
3395 hints.ai_socktype = SOCK_STREAM;
3396 snprintf(strport, sizeof strport, "%d", port);
3397 if ((gaierr = getaddrinfo(host, strport, &hints, &cctx.aitop)) != 0) {
3398 error("connect_to %.100s: unknown host (%s)", host,
3399 ssh_gai_strerror(gaierr));
3403 cctx.host = xstrdup(host);
3405 cctx.ai = cctx.aitop;
3407 if ((sock = connect_next(&cctx)) == -1) {
3408 error("connect to %.100s port %d failed: %s",
3409 host, port, strerror(errno));
3410 channel_connect_ctx_free(&cctx);
3413 c = channel_new(ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
3414 CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
3415 c->connect_ctx = cctx;
3420 channel_connect_by_listen_address(u_short listen_port, char *ctype, char *rname)
3424 for (i = 0; i < num_permitted_opens; i++) {
3425 if (permitted_opens[i].host_to_connect != NULL &&
3426 port_match(permitted_opens[i].listen_port, listen_port)) {
3428 permitted_opens[i].host_to_connect,
3429 permitted_opens[i].port_to_connect, ctype, rname);
3432 error("WARNING: Server requests forwarding for unknown listen_port %d",
3437 /* Check if connecting to that port is permitted and connect. */
3439 channel_connect_to(const char *host, u_short port, char *ctype, char *rname)
3441 int i, permit, permit_adm = 1;
3443 permit = all_opens_permitted;
3445 for (i = 0; i < num_permitted_opens; i++)
3446 if (permitted_opens[i].host_to_connect != NULL &&
3447 port_match(permitted_opens[i].port_to_connect, port) &&
3448 strcmp(permitted_opens[i].host_to_connect, host) == 0)
3452 if (num_adm_permitted_opens > 0) {
3454 for (i = 0; i < num_adm_permitted_opens; i++)
3455 if (permitted_adm_opens[i].host_to_connect != NULL &&
3456 port_match(permitted_adm_opens[i].port_to_connect, port) &&
3457 strcmp(permitted_adm_opens[i].host_to_connect, host)
3462 if (!permit || !permit_adm) {
3463 logit("Received request to connect to host %.100s port %d, "
3464 "but the request was denied.", host, port);
3467 return connect_to(host, port, ctype, rname);
3471 channel_send_window_changes(void)
3476 for (i = 0; i < channels_alloc; i++) {
3477 if (channels[i] == NULL || !channels[i]->client_tty ||
3478 channels[i]->type != SSH_CHANNEL_OPEN)
3480 if (ioctl(channels[i]->rfd, TIOCGWINSZ, &ws) < 0)
3482 channel_request_start(i, "window-change", 0);
3483 packet_put_int((u_int)ws.ws_col);
3484 packet_put_int((u_int)ws.ws_row);
3485 packet_put_int((u_int)ws.ws_xpixel);
3486 packet_put_int((u_int)ws.ws_ypixel);
3491 /* -- X11 forwarding */
3494 * Creates an internet domain socket for listening for X11 connections.
3495 * Returns 0 and a suitable display number for the DISPLAY variable
3496 * stored in display_numberp , or -1 if an error occurs.
3499 x11_create_display_inet(int x11_display_offset, int x11_use_localhost,
3500 int single_connection, u_int *display_numberp, int **chanids)
3503 int display_number, sock;
3505 struct addrinfo hints, *ai, *aitop;
3506 char strport[NI_MAXSERV];
3507 int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
3509 if (chanids == NULL)
3512 for (display_number = x11_display_offset;
3513 display_number < MAX_DISPLAYS;
3515 port = 6000 + display_number;
3516 memset(&hints, 0, sizeof(hints));
3517 hints.ai_family = IPv4or6;
3518 hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
3519 hints.ai_socktype = SOCK_STREAM;
3520 snprintf(strport, sizeof strport, "%d", port);
3521 if ((gaierr = getaddrinfo(NULL, strport, &hints, &aitop)) != 0) {
3522 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
3525 for (ai = aitop; ai; ai = ai->ai_next) {
3526 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
3528 sock = socket(ai->ai_family, ai->ai_socktype,
3531 if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
3533 && (errno != EPFNOSUPPORT)
3536 error("socket: %.100s", strerror(errno));
3537 freeaddrinfo(aitop);
3540 debug("x11_create_display_inet: Socket family %d not supported",
3545 if (ai->ai_family == AF_INET6)
3546 sock_set_v6only(sock);
3547 if (x11_use_localhost)
3548 channel_set_reuseaddr(sock);
3549 if (bind(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3550 debug2("bind port %d: %.100s", port, strerror(errno));
3553 for (n = 0; n < num_socks; n++) {
3559 socks[num_socks++] = sock;
3560 if (num_socks == NUM_SOCKS)
3563 freeaddrinfo(aitop);
3567 if (display_number >= MAX_DISPLAYS) {
3568 error("Failed to allocate internet-domain X11 display socket.");
3571 /* Start listening for connections on the socket. */
3572 for (n = 0; n < num_socks; n++) {
3574 if (listen(sock, SSH_LISTEN_BACKLOG) < 0) {
3575 error("listen: %.100s", strerror(errno));
3581 /* Allocate a channel for each socket. */
3582 *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
3583 for (n = 0; n < num_socks; n++) {
3586 nc = channel_new("x11 listener",
3587 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3588 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
3589 0, "X11 inet listener", 1);
3591 nc = channel_new("x11 listener",
3592 SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
3593 buffer_size, CHAN_X11_PACKET_DEFAULT,
3594 0, "X11 inet listener", 1);
3595 nc->single_connection = single_connection;
3596 (*chanids)[n] = nc->self;
3600 /* Return the display number for the DISPLAY environment variable. */
3601 *display_numberp = display_number;
3606 connect_local_xsocket_path(const char *pathname)
3609 struct sockaddr_un addr;
3611 sock = socket(AF_UNIX, SOCK_STREAM, 0);
3613 error("socket: %.100s", strerror(errno));
3614 memset(&addr, 0, sizeof(addr));
3615 addr.sun_family = AF_UNIX;
3616 strlcpy(addr.sun_path, pathname, sizeof addr.sun_path);
3617 if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) == 0)
3620 error("connect %.100s: %.100s", addr.sun_path, strerror(errno));
3625 connect_local_xsocket(u_int dnr)
3628 snprintf(buf, sizeof buf, _PATH_UNIX_X, dnr);
3629 return connect_local_xsocket_path(buf);
3633 x11_connect_display(void)
3635 u_int display_number;
3636 const char *display;
3637 char buf[1024], *cp;
3638 struct addrinfo hints, *ai, *aitop;
3639 char strport[NI_MAXSERV];
3640 int gaierr, sock = 0;
3642 /* Try to open a socket for the local X server. */
3643 display = getenv("DISPLAY");
3645 error("DISPLAY not set.");
3649 * Now we decode the value of the DISPLAY variable and make a
3650 * connection to the real X server.
3653 /* Check if the display is from launchd. */
3655 if (strncmp(display, "/tmp/launch", 11) == 0) {
3656 sock = connect_local_xsocket_path(display);
3660 /* OK, we now have a connection to the display. */
3665 * Check if it is a unix domain socket. Unix domain displays are in
3666 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
3668 if (strncmp(display, "unix:", 5) == 0 ||
3669 display[0] == ':') {
3670 /* Connect to the unix domain socket. */
3671 if (sscanf(strrchr(display, ':') + 1, "%u", &display_number) != 1) {
3672 error("Could not parse display number from DISPLAY: %.100s",
3676 /* Create a socket. */
3677 sock = connect_local_xsocket(display_number);
3681 /* OK, we now have a connection to the display. */
3685 * Connect to an inet socket. The DISPLAY value is supposedly
3686 * hostname:d[.s], where hostname may also be numeric IP address.
3688 strlcpy(buf, display, sizeof(buf));
3689 cp = strchr(buf, ':');
3691 error("Could not find ':' in DISPLAY: %.100s", display);
3695 /* buf now contains the host name. But first we parse the display number. */
3696 if (sscanf(cp + 1, "%u", &display_number) != 1) {
3697 error("Could not parse display number from DISPLAY: %.100s",
3702 /* Look up the host address */
3703 memset(&hints, 0, sizeof(hints));
3704 hints.ai_family = IPv4or6;
3705 hints.ai_socktype = SOCK_STREAM;
3706 snprintf(strport, sizeof strport, "%u", 6000 + display_number);
3707 if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
3708 error("%.100s: unknown host. (%s)", buf,
3709 ssh_gai_strerror(gaierr));
3712 for (ai = aitop; ai; ai = ai->ai_next) {
3713 /* Create a socket. */
3714 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
3716 debug2("socket: %.100s", strerror(errno));
3719 /* Connect it to the display. */
3720 if (connect(sock, ai->ai_addr, ai->ai_addrlen) < 0) {
3721 debug2("connect %.100s port %u: %.100s", buf,
3722 6000 + display_number, strerror(errno));
3729 freeaddrinfo(aitop);
3731 error("connect %.100s port %u: %.100s", buf, 6000 + display_number,
3740 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3741 * the remote channel number. We should do whatever we want, and respond
3742 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3747 x11_input_open(int type, u_int32_t seq, void *ctxt)
3750 int remote_id, sock = 0;
3753 debug("Received X11 open request.");
3755 remote_id = packet_get_int();
3757 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN) {
3758 remote_host = packet_get_string(NULL);
3760 remote_host = xstrdup("unknown (remote did not supply name)");
3764 /* Obtain a connection to the real X display. */
3765 sock = x11_connect_display();
3767 /* Allocate a channel for this connection. */
3768 c = channel_new("connected x11 socket",
3769 SSH_CHANNEL_X11_OPEN, sock, sock, -1, 0, 0, 0,
3771 c->remote_id = remote_id;
3776 /* Send refusal to the remote host. */
3777 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3778 packet_put_int(remote_id);
3780 /* Send a confirmation to the remote host. */
3781 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION);
3782 packet_put_int(remote_id);
3783 packet_put_int(c->self);
3788 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3791 deny_input_open(int type, u_int32_t seq, void *ctxt)
3793 int rchan = packet_get_int();
3796 case SSH_SMSG_AGENT_OPEN:
3797 error("Warning: ssh server tried agent forwarding.");
3799 case SSH_SMSG_X11_OPEN:
3800 error("Warning: ssh server tried X11 forwarding.");
3803 error("deny_input_open: type %d", type);
3806 error("Warning: this is probably a break-in attempt by a malicious server.");
3807 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE);
3808 packet_put_int(rchan);
3813 * Requests forwarding of X11 connections, generates fake authentication
3814 * data, and enables authentication spoofing.
3815 * This should be called in the client only.
3818 x11_request_forwarding_with_spoofing(int client_session_id, const char *disp,
3819 const char *proto, const char *data, int want_reply)
3821 u_int data_len = (u_int) strlen(data) / 2;
3828 if (x11_saved_display == NULL)
3829 x11_saved_display = xstrdup(disp);
3830 else if (strcmp(disp, x11_saved_display) != 0) {
3831 error("x11_request_forwarding_with_spoofing: different "
3832 "$DISPLAY already forwarded");
3836 cp = strchr(disp, ':');
3838 cp = strchr(cp, '.');
3840 screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
3844 if (x11_saved_proto == NULL) {
3845 /* Save protocol name. */
3846 x11_saved_proto = xstrdup(proto);
3848 * Extract real authentication data and generate fake data
3849 * of the same length.
3851 x11_saved_data = xmalloc(data_len);
3852 x11_fake_data = xmalloc(data_len);
3853 for (i = 0; i < data_len; i++) {
3854 if (sscanf(data + 2 * i, "%2x", &value) != 1)
3855 fatal("x11_request_forwarding: bad "
3856 "authentication data: %.100s", data);
3859 x11_saved_data[i] = value;
3860 x11_fake_data[i] = rnd & 0xff;
3863 x11_saved_data_len = data_len;
3864 x11_fake_data_len = data_len;
3867 /* Convert the fake data into hex. */
3868 new_data = tohex(x11_fake_data, data_len);
3870 /* Send the request packet. */
3872 channel_request_start(client_session_id, "x11-req", want_reply);
3873 packet_put_char(0); /* XXX bool single connection */
3875 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING);
3877 packet_put_cstring(proto);
3878 packet_put_cstring(new_data);
3879 packet_put_int(screen_number);
3881 packet_write_wait();
3886 /* -- agent forwarding */
3888 /* Sends a message to the server to request authentication fd forwarding. */
3891 auth_request_forwarding(void)
3893 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING);
3895 packet_write_wait();