1 /* $OpenBSD: channels.c,v 1.251 2006/07/03 17:59:32 stevesk Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for generic socket connection forwarding.
7 * There is also code for initiating connection forwarding for X11 connections,
8 * arbitrary tcp/ip connections, and the authentication agent connection.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/ioctl.h>
45 #include <sys/types.h>
47 #include <sys/socket.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
66 #include "pathnames.h"
72 * Pointer to an array containing all allocated channels. The array is
73 * dynamically extended as needed.
75 static Channel
**channels
= NULL
;
78 * Size of the channel array. All slots of the array must always be
79 * initialized (at least the type field); unused slots set to NULL
81 static u_int channels_alloc
= 0;
84 * Maximum file descriptor value used in any of the channels. This is
85 * updated in channel_new.
87 static int channel_max_fd
= 0;
90 /* -- tcp forwarding */
93 * Data structure for storing which hosts are permitted for forward requests.
94 * The local sides of any remote forwards are stored in this array to prevent
95 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
96 * network (which might be behind a firewall).
99 char *host_to_connect
; /* Connect to 'host'. */
100 u_short port_to_connect
; /* Connect to 'port'. */
101 u_short listen_port
; /* Remote side should listen port number. */
104 /* List of all permitted host/port pairs to connect. */
105 static ForwardPermission permitted_opens
[SSH_MAX_FORWARDS_PER_DIRECTION
];
107 /* Number of permitted host/port pairs in the array. */
108 static int num_permitted_opens
= 0;
110 * If this is true, all opens are permitted. This is the case on the server
111 * on which we have to trust the client anyway, and the user could do
112 * anything after logging in anyway.
114 static int all_opens_permitted
= 0;
117 /* -- X11 forwarding */
119 /* Maximum number of fake X11 displays to try. */
120 #define MAX_DISPLAYS 1000
122 /* Saved X11 local (client) display. */
123 static char *x11_saved_display
= NULL
;
125 /* Saved X11 authentication protocol name. */
126 static char *x11_saved_proto
= NULL
;
128 /* Saved X11 authentication data. This is the real data. */
129 static char *x11_saved_data
= NULL
;
130 static u_int x11_saved_data_len
= 0;
133 * Fake X11 authentication data. This is what the server will be sending us;
134 * we should replace any occurrences of this by the real data.
136 static u_char
*x11_fake_data
= NULL
;
137 static u_int x11_fake_data_len
;
140 /* -- agent forwarding */
144 /* AF_UNSPEC or AF_INET or AF_INET6 */
145 static int IPv4or6
= AF_UNSPEC
;
148 static void port_open_helper(Channel
*c
, char *rtype
);
150 /* -- channel core */
153 channel_by_id(int id
)
157 if (id
< 0 || (u_int
)id
>= channels_alloc
) {
158 logit("channel_by_id: %d: bad id", id
);
163 logit("channel_by_id: %d: bad id: channel free", id
);
170 * Returns the channel if it is allowed to receive protocol messages.
171 * Private channels, like listening sockets, may not receive messages.
174 channel_lookup(int id
)
178 if ((c
= channel_by_id(id
)) == NULL
)
182 case SSH_CHANNEL_X11_OPEN
:
183 case SSH_CHANNEL_LARVAL
:
184 case SSH_CHANNEL_CONNECTING
:
185 case SSH_CHANNEL_DYNAMIC
:
186 case SSH_CHANNEL_OPENING
:
187 case SSH_CHANNEL_OPEN
:
188 case SSH_CHANNEL_INPUT_DRAINING
:
189 case SSH_CHANNEL_OUTPUT_DRAINING
:
192 logit("Non-public channel %d, type %d.", id
, c
->type
);
197 * Register filedescriptors for a channel, used when allocating a channel or
198 * when the channel consumer/producer is ready, e.g. shell exec'd
201 channel_register_fds(Channel
*c
, int rfd
, int wfd
, int efd
,
202 int extusage
, int nonblock
)
204 /* Update the maximum file descriptor value. */
205 channel_max_fd
= MAX(channel_max_fd
, rfd
);
206 channel_max_fd
= MAX(channel_max_fd
, wfd
);
207 channel_max_fd
= MAX(channel_max_fd
, efd
);
209 /* XXX set close-on-exec -markus */
213 c
->sock
= (rfd
== wfd
) ? rfd
: -1;
214 c
->ctl_fd
= -1; /* XXX: set elsewhere */
216 c
->extended_usage
= extusage
;
218 /* XXX ugly hack: nonblock is only set by the server */
219 if (nonblock
&& isatty(c
->rfd
)) {
220 debug2("channel %d: rfd %d isatty", c
->self
, c
->rfd
);
222 if (!isatty(c
->wfd
)) {
223 error("channel %d: wfd %d is not a tty?",
229 c
->wfd_isatty
= isatty(c
->wfd
);
231 /* enable nonblocking mode */
243 * Allocate a new channel object and set its type and socket. This will cause
244 * remote_name to be freed.
247 channel_new(char *ctype
, int type
, int rfd
, int wfd
, int efd
,
248 u_int window
, u_int maxpack
, int extusage
, char *remote_name
, int nonblock
)
254 /* Do initial allocation if this is the first call. */
255 if (channels_alloc
== 0) {
257 channels
= xcalloc(channels_alloc
, sizeof(Channel
*));
258 for (i
= 0; i
< channels_alloc
; i
++)
261 /* Try to find a free slot where to put the new channel. */
262 for (found
= -1, i
= 0; i
< channels_alloc
; i
++)
263 if (channels
[i
] == NULL
) {
264 /* Found a free slot. */
269 /* There are no free slots. Take last+1 slot and expand the array. */
270 found
= channels_alloc
;
271 if (channels_alloc
> 10000)
272 fatal("channel_new: internal error: channels_alloc %d "
273 "too big.", channels_alloc
);
274 channels
= xrealloc(channels
, channels_alloc
+ 10,
276 channels_alloc
+= 10;
277 debug2("channel: expanding %d", channels_alloc
);
278 for (i
= found
; i
< channels_alloc
; i
++)
281 /* Initialize and return new channel. */
282 c
= channels
[found
] = xcalloc(1, sizeof(Channel
));
283 buffer_init(&c
->input
);
284 buffer_init(&c
->output
);
285 buffer_init(&c
->extended
);
286 c
->ostate
= CHAN_OUTPUT_OPEN
;
287 c
->istate
= CHAN_INPUT_OPEN
;
289 channel_register_fds(c
, rfd
, wfd
, efd
, extusage
, nonblock
);
293 c
->local_window
= window
;
294 c
->local_window_max
= window
;
295 c
->local_consumed
= 0;
296 c
->local_maxpacket
= maxpack
;
298 c
->remote_name
= xstrdup(remote_name
);
299 c
->remote_window
= 0;
300 c
->remote_maxpacket
= 0;
302 c
->single_connection
= 0;
303 c
->detach_user
= NULL
;
306 c
->confirm_ctx
= NULL
;
307 c
->input_filter
= NULL
;
308 c
->output_filter
= NULL
;
309 debug("channel %d: new [%s]", found
, remote_name
);
314 channel_find_maxfd(void)
320 for (i
= 0; i
< channels_alloc
; i
++) {
323 max
= MAX(max
, c
->rfd
);
324 max
= MAX(max
, c
->wfd
);
325 max
= MAX(max
, c
->efd
);
332 channel_close_fd(int *fdp
)
334 int ret
= 0, fd
= *fdp
;
339 if (fd
== channel_max_fd
)
340 channel_max_fd
= channel_find_maxfd();
345 /* Close all channel fd/socket. */
347 channel_close_fds(Channel
*c
)
349 debug3("channel %d: close_fds r %d w %d e %d c %d",
350 c
->self
, c
->rfd
, c
->wfd
, c
->efd
, c
->ctl_fd
);
352 channel_close_fd(&c
->sock
);
353 channel_close_fd(&c
->ctl_fd
);
354 channel_close_fd(&c
->rfd
);
355 channel_close_fd(&c
->wfd
);
356 channel_close_fd(&c
->efd
);
359 /* Free the channel and close its fd/socket. */
361 channel_free(Channel
*c
)
366 for (n
= 0, i
= 0; i
< channels_alloc
; i
++)
369 debug("channel %d: free: %s, nchannels %u", c
->self
,
370 c
->remote_name
? c
->remote_name
: "???", n
);
372 s
= channel_open_message();
373 debug3("channel %d: status: %s", c
->self
, s
);
377 shutdown(c
->sock
, SHUT_RDWR
);
379 shutdown(c
->ctl_fd
, SHUT_RDWR
);
380 channel_close_fds(c
);
381 buffer_free(&c
->input
);
382 buffer_free(&c
->output
);
383 buffer_free(&c
->extended
);
384 if (c
->remote_name
) {
385 xfree(c
->remote_name
);
386 c
->remote_name
= NULL
;
388 channels
[c
->self
] = NULL
;
393 channel_free_all(void)
397 for (i
= 0; i
< channels_alloc
; i
++)
398 if (channels
[i
] != NULL
)
399 channel_free(channels
[i
]);
403 * Closes the sockets/fds of all channels. This is used to close extra file
404 * descriptors after a fork.
407 channel_close_all(void)
411 for (i
= 0; i
< channels_alloc
; i
++)
412 if (channels
[i
] != NULL
)
413 channel_close_fds(channels
[i
]);
417 * Stop listening to channels.
420 channel_stop_listening(void)
425 for (i
= 0; i
< channels_alloc
; i
++) {
429 case SSH_CHANNEL_AUTH_SOCKET
:
430 case SSH_CHANNEL_PORT_LISTENER
:
431 case SSH_CHANNEL_RPORT_LISTENER
:
432 case SSH_CHANNEL_X11_LISTENER
:
433 channel_close_fd(&c
->sock
);
442 * Returns true if no channel has too much buffered data, and false if one or
443 * more channel is overfull.
446 channel_not_very_much_buffered_data(void)
451 for (i
= 0; i
< channels_alloc
; i
++) {
453 if (c
!= NULL
&& c
->type
== SSH_CHANNEL_OPEN
) {
456 buffer_len(&c
->input
) > packet_get_maxsize()) {
457 debug2("channel %d: big input buffer %d",
458 c
->self
, buffer_len(&c
->input
));
462 if (buffer_len(&c
->output
) > packet_get_maxsize()) {
463 debug2("channel %d: big output buffer %u > %u",
464 c
->self
, buffer_len(&c
->output
),
465 packet_get_maxsize());
473 /* Returns true if any channel is still open. */
475 channel_still_open(void)
480 for (i
= 0; i
< channels_alloc
; i
++) {
485 case SSH_CHANNEL_X11_LISTENER
:
486 case SSH_CHANNEL_PORT_LISTENER
:
487 case SSH_CHANNEL_RPORT_LISTENER
:
488 case SSH_CHANNEL_CLOSED
:
489 case SSH_CHANNEL_AUTH_SOCKET
:
490 case SSH_CHANNEL_DYNAMIC
:
491 case SSH_CHANNEL_CONNECTING
:
492 case SSH_CHANNEL_ZOMBIE
:
494 case SSH_CHANNEL_LARVAL
:
496 fatal("cannot happen: SSH_CHANNEL_LARVAL");
498 case SSH_CHANNEL_OPENING
:
499 case SSH_CHANNEL_OPEN
:
500 case SSH_CHANNEL_X11_OPEN
:
502 case SSH_CHANNEL_INPUT_DRAINING
:
503 case SSH_CHANNEL_OUTPUT_DRAINING
:
505 fatal("cannot happen: OUT_DRAIN");
508 fatal("channel_still_open: bad channel type %d", c
->type
);
515 /* Returns the id of an open channel suitable for keepaliving */
517 channel_find_open(void)
522 for (i
= 0; i
< channels_alloc
; i
++) {
524 if (c
== NULL
|| c
->remote_id
< 0)
527 case SSH_CHANNEL_CLOSED
:
528 case SSH_CHANNEL_DYNAMIC
:
529 case SSH_CHANNEL_X11_LISTENER
:
530 case SSH_CHANNEL_PORT_LISTENER
:
531 case SSH_CHANNEL_RPORT_LISTENER
:
532 case SSH_CHANNEL_OPENING
:
533 case SSH_CHANNEL_CONNECTING
:
534 case SSH_CHANNEL_ZOMBIE
:
536 case SSH_CHANNEL_LARVAL
:
537 case SSH_CHANNEL_AUTH_SOCKET
:
538 case SSH_CHANNEL_OPEN
:
539 case SSH_CHANNEL_X11_OPEN
:
541 case SSH_CHANNEL_INPUT_DRAINING
:
542 case SSH_CHANNEL_OUTPUT_DRAINING
:
544 fatal("cannot happen: OUT_DRAIN");
547 fatal("channel_find_open: bad channel type %d", c
->type
);
556 * Returns a message describing the currently open forwarded connections,
557 * suitable for sending to the client. The message contains crlf pairs for
561 channel_open_message(void)
568 buffer_init(&buffer
);
569 snprintf(buf
, sizeof buf
, "The following connections are open:\r\n");
570 buffer_append(&buffer
, buf
, strlen(buf
));
571 for (i
= 0; i
< channels_alloc
; i
++) {
576 case SSH_CHANNEL_X11_LISTENER
:
577 case SSH_CHANNEL_PORT_LISTENER
:
578 case SSH_CHANNEL_RPORT_LISTENER
:
579 case SSH_CHANNEL_CLOSED
:
580 case SSH_CHANNEL_AUTH_SOCKET
:
581 case SSH_CHANNEL_ZOMBIE
:
583 case SSH_CHANNEL_LARVAL
:
584 case SSH_CHANNEL_OPENING
:
585 case SSH_CHANNEL_CONNECTING
:
586 case SSH_CHANNEL_DYNAMIC
:
587 case SSH_CHANNEL_OPEN
:
588 case SSH_CHANNEL_X11_OPEN
:
589 case SSH_CHANNEL_INPUT_DRAINING
:
590 case SSH_CHANNEL_OUTPUT_DRAINING
:
591 snprintf(buf
, sizeof buf
,
592 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
593 c
->self
, c
->remote_name
,
594 c
->type
, c
->remote_id
,
595 c
->istate
, buffer_len(&c
->input
),
596 c
->ostate
, buffer_len(&c
->output
),
597 c
->rfd
, c
->wfd
, c
->ctl_fd
);
598 buffer_append(&buffer
, buf
, strlen(buf
));
601 fatal("channel_open_message: bad channel type %d", c
->type
);
605 buffer_append(&buffer
, "\0", 1);
606 cp
= xstrdup(buffer_ptr(&buffer
));
607 buffer_free(&buffer
);
612 channel_send_open(int id
)
614 Channel
*c
= channel_lookup(id
);
617 logit("channel_send_open: %d: bad id", id
);
620 debug2("channel %d: send open", id
);
621 packet_start(SSH2_MSG_CHANNEL_OPEN
);
622 packet_put_cstring(c
->ctype
);
623 packet_put_int(c
->self
);
624 packet_put_int(c
->local_window
);
625 packet_put_int(c
->local_maxpacket
);
630 channel_request_start(int id
, char *service
, int wantconfirm
)
632 Channel
*c
= channel_lookup(id
);
635 logit("channel_request_start: %d: unknown channel id", id
);
638 debug2("channel %d: request %s confirm %d", id
, service
, wantconfirm
);
639 packet_start(SSH2_MSG_CHANNEL_REQUEST
);
640 packet_put_int(c
->remote_id
);
641 packet_put_cstring(service
);
642 packet_put_char(wantconfirm
);
646 channel_register_confirm(int id
, channel_callback_fn
*fn
, void *ctx
)
648 Channel
*c
= channel_lookup(id
);
651 logit("channel_register_comfirm: %d: bad id", id
);
655 c
->confirm_ctx
= ctx
;
659 channel_register_cleanup(int id
, channel_callback_fn
*fn
, int do_close
)
661 Channel
*c
= channel_by_id(id
);
664 logit("channel_register_cleanup: %d: bad id", id
);
668 c
->detach_close
= do_close
;
672 channel_cancel_cleanup(int id
)
674 Channel
*c
= channel_by_id(id
);
677 logit("channel_cancel_cleanup: %d: bad id", id
);
680 c
->detach_user
= NULL
;
685 channel_register_filter(int id
, channel_infilter_fn
*ifn
,
686 channel_outfilter_fn
*ofn
)
688 Channel
*c
= channel_lookup(id
);
691 logit("channel_register_filter: %d: bad id", id
);
694 c
->input_filter
= ifn
;
695 c
->output_filter
= ofn
;
699 channel_set_fds(int id
, int rfd
, int wfd
, int efd
,
700 int extusage
, int nonblock
, u_int window_max
)
702 Channel
*c
= channel_lookup(id
);
704 if (c
== NULL
|| c
->type
!= SSH_CHANNEL_LARVAL
)
705 fatal("channel_activate for non-larval channel %d.", id
);
706 channel_register_fds(c
, rfd
, wfd
, efd
, extusage
, nonblock
);
707 c
->type
= SSH_CHANNEL_OPEN
;
708 c
->local_window
= c
->local_window_max
= window_max
;
709 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
710 packet_put_int(c
->remote_id
);
711 packet_put_int(c
->local_window
);
716 * 'channel_pre*' are called just before select() to add any bits relevant to
717 * channels in the select bitmasks.
720 * 'channel_post*': perform any appropriate operations for channels which
721 * have events pending.
723 typedef void chan_fn(Channel
*c
, fd_set
*readset
, fd_set
*writeset
);
724 chan_fn
*channel_pre
[SSH_CHANNEL_MAX_TYPE
];
725 chan_fn
*channel_post
[SSH_CHANNEL_MAX_TYPE
];
728 channel_pre_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
730 FD_SET(c
->sock
, readset
);
734 channel_pre_connecting(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
736 debug3("channel %d: waiting for connection", c
->self
);
737 FD_SET(c
->sock
, writeset
);
741 channel_pre_open_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
743 if (buffer_len(&c
->input
) < packet_get_maxsize())
744 FD_SET(c
->sock
, readset
);
745 if (buffer_len(&c
->output
) > 0)
746 FD_SET(c
->sock
, writeset
);
750 channel_pre_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
752 u_int limit
= compat20
? c
->remote_window
: packet_get_maxsize();
754 if (c
->istate
== CHAN_INPUT_OPEN
&&
756 buffer_len(&c
->input
) < limit
&&
757 buffer_check_alloc(&c
->input
, CHAN_RBUF
))
758 FD_SET(c
->rfd
, readset
);
759 if (c
->ostate
== CHAN_OUTPUT_OPEN
||
760 c
->ostate
== CHAN_OUTPUT_WAIT_DRAIN
) {
761 if (buffer_len(&c
->output
) > 0) {
762 FD_SET(c
->wfd
, writeset
);
763 } else if (c
->ostate
== CHAN_OUTPUT_WAIT_DRAIN
) {
764 if (CHANNEL_EFD_OUTPUT_ACTIVE(c
))
765 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
766 c
->self
, c
->efd
, buffer_len(&c
->extended
));
771 /** XXX check close conditions, too */
772 if (compat20
&& c
->efd
!= -1) {
773 if (c
->extended_usage
== CHAN_EXTENDED_WRITE
&&
774 buffer_len(&c
->extended
) > 0)
775 FD_SET(c
->efd
, writeset
);
776 else if (!(c
->flags
& CHAN_EOF_SENT
) &&
777 c
->extended_usage
== CHAN_EXTENDED_READ
&&
778 buffer_len(&c
->extended
) < c
->remote_window
)
779 FD_SET(c
->efd
, readset
);
781 /* XXX: What about efd? races? */
782 if (compat20
&& c
->ctl_fd
!= -1 &&
783 c
->istate
== CHAN_INPUT_OPEN
&& c
->ostate
== CHAN_OUTPUT_OPEN
)
784 FD_SET(c
->ctl_fd
, readset
);
788 channel_pre_input_draining(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
790 if (buffer_len(&c
->input
) == 0) {
791 packet_start(SSH_MSG_CHANNEL_CLOSE
);
792 packet_put_int(c
->remote_id
);
794 c
->type
= SSH_CHANNEL_CLOSED
;
795 debug2("channel %d: closing after input drain.", c
->self
);
800 channel_pre_output_draining(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
802 if (buffer_len(&c
->output
) == 0)
805 FD_SET(c
->sock
, writeset
);
809 * This is a special state for X11 authentication spoofing. An opened X11
810 * connection (when authentication spoofing is being done) remains in this
811 * state until the first packet has been completely read. The authentication
812 * data in that packet is then substituted by the real data if it matches the
813 * fake data, and the channel is put into normal mode.
814 * XXX All this happens at the client side.
815 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
818 x11_open_helper(Buffer
*b
)
821 u_int proto_len
, data_len
;
823 /* Check if the fixed size part of the packet is in buffer. */
824 if (buffer_len(b
) < 12)
827 /* Parse the lengths of variable-length fields. */
829 if (ucp
[0] == 0x42) { /* Byte order MSB first. */
830 proto_len
= 256 * ucp
[6] + ucp
[7];
831 data_len
= 256 * ucp
[8] + ucp
[9];
832 } else if (ucp
[0] == 0x6c) { /* Byte order LSB first. */
833 proto_len
= ucp
[6] + 256 * ucp
[7];
834 data_len
= ucp
[8] + 256 * ucp
[9];
836 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
841 /* Check if the whole packet is in buffer. */
843 12 + ((proto_len
+ 3) & ~3) + ((data_len
+ 3) & ~3))
846 /* Check if authentication protocol matches. */
847 if (proto_len
!= strlen(x11_saved_proto
) ||
848 memcmp(ucp
+ 12, x11_saved_proto
, proto_len
) != 0) {
849 debug2("X11 connection uses different authentication protocol.");
852 /* Check if authentication data matches our fake data. */
853 if (data_len
!= x11_fake_data_len
||
854 memcmp(ucp
+ 12 + ((proto_len
+ 3) & ~3),
855 x11_fake_data
, x11_fake_data_len
) != 0) {
856 debug2("X11 auth data does not match fake data.");
859 /* Check fake data length */
860 if (x11_fake_data_len
!= x11_saved_data_len
) {
861 error("X11 fake_data_len %d != saved_data_len %d",
862 x11_fake_data_len
, x11_saved_data_len
);
866 * Received authentication protocol and data match
867 * our fake data. Substitute the fake data with real
870 memcpy(ucp
+ 12 + ((proto_len
+ 3) & ~3),
871 x11_saved_data
, x11_saved_data_len
);
876 channel_pre_x11_open_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
878 int ret
= x11_open_helper(&c
->output
);
881 /* Start normal processing for the channel. */
882 c
->type
= SSH_CHANNEL_OPEN
;
883 channel_pre_open_13(c
, readset
, writeset
);
884 } else if (ret
== -1) {
886 * We have received an X11 connection that has bad
887 * authentication information.
889 logit("X11 connection rejected because of wrong authentication.");
890 buffer_clear(&c
->input
);
891 buffer_clear(&c
->output
);
892 channel_close_fd(&c
->sock
);
894 c
->type
= SSH_CHANNEL_CLOSED
;
895 packet_start(SSH_MSG_CHANNEL_CLOSE
);
896 packet_put_int(c
->remote_id
);
902 channel_pre_x11_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
904 int ret
= x11_open_helper(&c
->output
);
906 /* c->force_drain = 1; */
909 c
->type
= SSH_CHANNEL_OPEN
;
910 channel_pre_open(c
, readset
, writeset
);
911 } else if (ret
== -1) {
912 logit("X11 connection rejected because of wrong authentication.");
913 debug2("X11 rejected %d i%d/o%d", c
->self
, c
->istate
, c
->ostate
);
915 buffer_clear(&c
->input
);
917 buffer_clear(&c
->output
);
918 /* for proto v1, the peer will send an IEOF */
920 chan_write_failed(c
);
922 c
->type
= SSH_CHANNEL_OPEN
;
923 debug2("X11 closed %d i%d/o%d", c
->self
, c
->istate
, c
->ostate
);
927 /* try to decode a socks4 header */
929 channel_decode_socks4(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
932 u_int len
, have
, i
, found
;
938 struct in_addr dest_addr
;
941 debug2("channel %d: decode socks4", c
->self
);
943 have
= buffer_len(&c
->input
);
944 len
= sizeof(s4_req
);
947 p
= buffer_ptr(&c
->input
);
948 for (found
= 0, i
= len
; i
< have
; i
++) {
954 /* the peer is probably sending garbage */
955 debug("channel %d: decode socks4: too long",
962 buffer_get(&c
->input
, (char *)&s4_req
.version
, 1);
963 buffer_get(&c
->input
, (char *)&s4_req
.command
, 1);
964 buffer_get(&c
->input
, (char *)&s4_req
.dest_port
, 2);
965 buffer_get(&c
->input
, (char *)&s4_req
.dest_addr
, 4);
966 have
= buffer_len(&c
->input
);
967 p
= buffer_ptr(&c
->input
);
969 debug2("channel %d: decode socks4: user %s/%d", c
->self
, p
, len
);
971 fatal("channel %d: decode socks4: len %d > have %d",
973 strlcpy(username
, p
, sizeof(username
));
974 buffer_consume(&c
->input
, len
);
975 buffer_consume(&c
->input
, 1); /* trailing '\0' */
977 host
= inet_ntoa(s4_req
.dest_addr
);
978 strlcpy(c
->path
, host
, sizeof(c
->path
));
979 c
->host_port
= ntohs(s4_req
.dest_port
);
981 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
982 c
->self
, host
, c
->host_port
, s4_req
.command
);
984 if (s4_req
.command
!= 1) {
985 debug("channel %d: cannot handle: socks4 cn %d",
986 c
->self
, s4_req
.command
);
989 s4_rsp
.version
= 0; /* vn: 0 for reply */
990 s4_rsp
.command
= 90; /* cd: req granted */
991 s4_rsp
.dest_port
= 0; /* ignored */
992 s4_rsp
.dest_addr
.s_addr
= INADDR_ANY
; /* ignored */
993 buffer_append(&c
->output
, &s4_rsp
, sizeof(s4_rsp
));
997 /* try to decode a socks5 header */
998 #define SSH_SOCKS5_AUTHDONE 0x1000
999 #define SSH_SOCKS5_NOAUTH 0x00
1000 #define SSH_SOCKS5_IPV4 0x01
1001 #define SSH_SOCKS5_DOMAIN 0x03
1002 #define SSH_SOCKS5_IPV6 0x04
1003 #define SSH_SOCKS5_CONNECT 0x01
1004 #define SSH_SOCKS5_SUCCESS 0x00
1007 channel_decode_socks5(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1015 u_int16_t dest_port
;
1016 u_char
*p
, dest_addr
[255+1];
1017 u_int have
, i
, found
, nmethods
, addrlen
, af
;
1019 debug2("channel %d: decode socks5", c
->self
);
1020 p
= buffer_ptr(&c
->input
);
1023 have
= buffer_len(&c
->input
);
1024 if (!(c
->flags
& SSH_SOCKS5_AUTHDONE
)) {
1025 /* format: ver | nmethods | methods */
1029 if (have
< nmethods
+ 2)
1031 /* look for method: "NO AUTHENTICATION REQUIRED" */
1032 for (found
= 0, i
= 2 ; i
< nmethods
+ 2; i
++) {
1033 if (p
[i
] == SSH_SOCKS5_NOAUTH
) {
1039 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1043 buffer_consume(&c
->input
, nmethods
+ 2);
1044 buffer_put_char(&c
->output
, 0x05); /* version */
1045 buffer_put_char(&c
->output
, SSH_SOCKS5_NOAUTH
); /* method */
1046 FD_SET(c
->sock
, writeset
);
1047 c
->flags
|= SSH_SOCKS5_AUTHDONE
;
1048 debug2("channel %d: socks5 auth done", c
->self
);
1049 return 0; /* need more */
1051 debug2("channel %d: socks5 post auth", c
->self
);
1052 if (have
< sizeof(s5_req
)+1)
1053 return 0; /* need more */
1054 memcpy(&s5_req
, p
, sizeof(s5_req
));
1055 if (s5_req
.version
!= 0x05 ||
1056 s5_req
.command
!= SSH_SOCKS5_CONNECT
||
1057 s5_req
.reserved
!= 0x00) {
1058 debug2("channel %d: only socks5 connect supported", c
->self
);
1061 switch (s5_req
.atyp
){
1062 case SSH_SOCKS5_IPV4
:
1066 case SSH_SOCKS5_DOMAIN
:
1067 addrlen
= p
[sizeof(s5_req
)];
1070 case SSH_SOCKS5_IPV6
:
1075 debug2("channel %d: bad socks5 atyp %d", c
->self
, s5_req
.atyp
);
1078 if (have
< 4 + addrlen
+ 2)
1080 buffer_consume(&c
->input
, sizeof(s5_req
));
1081 if (s5_req
.atyp
== SSH_SOCKS5_DOMAIN
)
1082 buffer_consume(&c
->input
, 1); /* host string length */
1083 buffer_get(&c
->input
, (char *)&dest_addr
, addrlen
);
1084 buffer_get(&c
->input
, (char *)&dest_port
, 2);
1085 dest_addr
[addrlen
] = '\0';
1086 if (s5_req
.atyp
== SSH_SOCKS5_DOMAIN
)
1087 strlcpy(c
->path
, (char *)dest_addr
, sizeof(c
->path
));
1088 else if (inet_ntop(af
, dest_addr
, c
->path
, sizeof(c
->path
)) == NULL
)
1090 c
->host_port
= ntohs(dest_port
);
1092 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1093 c
->self
, c
->path
, c
->host_port
, s5_req
.command
);
1095 s5_rsp
.version
= 0x05;
1096 s5_rsp
.command
= SSH_SOCKS5_SUCCESS
;
1097 s5_rsp
.reserved
= 0; /* ignored */
1098 s5_rsp
.atyp
= SSH_SOCKS5_IPV4
;
1099 ((struct in_addr
*)&dest_addr
)->s_addr
= INADDR_ANY
;
1100 dest_port
= 0; /* ignored */
1102 buffer_append(&c
->output
, &s5_rsp
, sizeof(s5_rsp
));
1103 buffer_append(&c
->output
, &dest_addr
, sizeof(struct in_addr
));
1104 buffer_append(&c
->output
, &dest_port
, sizeof(dest_port
));
1108 /* dynamic port forwarding */
1110 channel_pre_dynamic(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1116 have
= buffer_len(&c
->input
);
1118 debug2("channel %d: pre_dynamic: have %d", c
->self
, have
);
1119 /* buffer_dump(&c->input); */
1120 /* check if the fixed size part of the packet is in buffer. */
1123 FD_SET(c
->sock
, readset
);
1126 /* try to guess the protocol */
1127 p
= buffer_ptr(&c
->input
);
1130 ret
= channel_decode_socks4(c
, readset
, writeset
);
1133 ret
= channel_decode_socks5(c
, readset
, writeset
);
1141 } else if (ret
== 0) {
1142 debug2("channel %d: pre_dynamic: need more", c
->self
);
1144 FD_SET(c
->sock
, readset
);
1146 /* switch to the next state */
1147 c
->type
= SSH_CHANNEL_OPENING
;
1148 port_open_helper(c
, "direct-tcpip");
1152 /* This is our fake X11 server socket. */
1154 channel_post_x11_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1157 struct sockaddr addr
;
1160 char buf
[16384], *remote_ipaddr
;
1163 if (FD_ISSET(c
->sock
, readset
)) {
1164 debug("X11 connection requested.");
1165 addrlen
= sizeof(addr
);
1166 newsock
= accept(c
->sock
, &addr
, &addrlen
);
1167 if (c
->single_connection
) {
1168 debug2("single_connection: closing X11 listener.");
1169 channel_close_fd(&c
->sock
);
1173 error("accept: %.100s", strerror(errno
));
1176 set_nodelay(newsock
);
1177 remote_ipaddr
= get_peer_ipaddr(newsock
);
1178 remote_port
= get_peer_port(newsock
);
1179 snprintf(buf
, sizeof buf
, "X11 connection from %.200s port %d",
1180 remote_ipaddr
, remote_port
);
1182 nc
= channel_new("accepted x11 socket",
1183 SSH_CHANNEL_OPENING
, newsock
, newsock
, -1,
1184 c
->local_window_max
, c
->local_maxpacket
, 0, buf
, 1);
1186 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1187 packet_put_cstring("x11");
1188 packet_put_int(nc
->self
);
1189 packet_put_int(nc
->local_window_max
);
1190 packet_put_int(nc
->local_maxpacket
);
1191 /* originator ipaddr and port */
1192 packet_put_cstring(remote_ipaddr
);
1193 if (datafellows
& SSH_BUG_X11FWD
) {
1194 debug2("ssh2 x11 bug compat mode");
1196 packet_put_int(remote_port
);
1200 packet_start(SSH_SMSG_X11_OPEN
);
1201 packet_put_int(nc
->self
);
1202 if (packet_get_protocol_flags() &
1203 SSH_PROTOFLAG_HOST_IN_FWD_OPEN
)
1204 packet_put_cstring(buf
);
1207 xfree(remote_ipaddr
);
1212 port_open_helper(Channel
*c
, char *rtype
)
1216 char *remote_ipaddr
= get_peer_ipaddr(c
->sock
);
1217 int remote_port
= get_peer_port(c
->sock
);
1219 direct
= (strcmp(rtype
, "direct-tcpip") == 0);
1221 snprintf(buf
, sizeof buf
,
1222 "%s: listening port %d for %.100s port %d, "
1223 "connect from %.200s port %d",
1224 rtype
, c
->listening_port
, c
->path
, c
->host_port
,
1225 remote_ipaddr
, remote_port
);
1227 xfree(c
->remote_name
);
1228 c
->remote_name
= xstrdup(buf
);
1231 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1232 packet_put_cstring(rtype
);
1233 packet_put_int(c
->self
);
1234 packet_put_int(c
->local_window_max
);
1235 packet_put_int(c
->local_maxpacket
);
1237 /* target host, port */
1238 packet_put_cstring(c
->path
);
1239 packet_put_int(c
->host_port
);
1241 /* listen address, port */
1242 packet_put_cstring(c
->path
);
1243 packet_put_int(c
->listening_port
);
1245 /* originator host and port */
1246 packet_put_cstring(remote_ipaddr
);
1247 packet_put_int((u_int
)remote_port
);
1250 packet_start(SSH_MSG_PORT_OPEN
);
1251 packet_put_int(c
->self
);
1252 packet_put_cstring(c
->path
);
1253 packet_put_int(c
->host_port
);
1254 if (packet_get_protocol_flags() &
1255 SSH_PROTOFLAG_HOST_IN_FWD_OPEN
)
1256 packet_put_cstring(c
->remote_name
);
1259 xfree(remote_ipaddr
);
1263 channel_set_reuseaddr(int fd
)
1268 * Set socket options.
1269 * Allow local port reuse in TIME_WAIT.
1271 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) == -1)
1272 error("setsockopt SO_REUSEADDR fd %d: %s", fd
, strerror(errno
));
1276 * This socket is listening for connections to a forwarded TCP/IP port.
1279 channel_post_port_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1282 struct sockaddr addr
;
1283 int newsock
, nextstate
;
1287 if (FD_ISSET(c
->sock
, readset
)) {
1288 debug("Connection to port %d forwarding "
1289 "to %.100s port %d requested.",
1290 c
->listening_port
, c
->path
, c
->host_port
);
1292 if (c
->type
== SSH_CHANNEL_RPORT_LISTENER
) {
1293 nextstate
= SSH_CHANNEL_OPENING
;
1294 rtype
= "forwarded-tcpip";
1296 if (c
->host_port
== 0) {
1297 nextstate
= SSH_CHANNEL_DYNAMIC
;
1298 rtype
= "dynamic-tcpip";
1300 nextstate
= SSH_CHANNEL_OPENING
;
1301 rtype
= "direct-tcpip";
1305 addrlen
= sizeof(addr
);
1306 newsock
= accept(c
->sock
, &addr
, &addrlen
);
1308 error("accept: %.100s", strerror(errno
));
1311 set_nodelay(newsock
);
1312 nc
= channel_new(rtype
, nextstate
, newsock
, newsock
, -1,
1313 c
->local_window_max
, c
->local_maxpacket
, 0, rtype
, 1);
1314 nc
->listening_port
= c
->listening_port
;
1315 nc
->host_port
= c
->host_port
;
1316 strlcpy(nc
->path
, c
->path
, sizeof(nc
->path
));
1318 if (nextstate
== SSH_CHANNEL_DYNAMIC
) {
1320 * do not call the channel_post handler until
1321 * this flag has been reset by a pre-handler.
1322 * otherwise the FD_ISSET calls might overflow
1326 port_open_helper(nc
, rtype
);
1332 * This is the authentication agent socket listening for connections from
1336 channel_post_auth_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1340 struct sockaddr addr
;
1343 if (FD_ISSET(c
->sock
, readset
)) {
1344 addrlen
= sizeof(addr
);
1345 newsock
= accept(c
->sock
, &addr
, &addrlen
);
1347 error("accept from auth socket: %.100s", strerror(errno
));
1350 nc
= channel_new("accepted auth socket",
1351 SSH_CHANNEL_OPENING
, newsock
, newsock
, -1,
1352 c
->local_window_max
, c
->local_maxpacket
,
1353 0, "accepted auth socket", 1);
1355 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1356 packet_put_cstring("auth-agent@openssh.com");
1357 packet_put_int(nc
->self
);
1358 packet_put_int(c
->local_window_max
);
1359 packet_put_int(c
->local_maxpacket
);
1361 packet_start(SSH_SMSG_AGENT_OPEN
);
1362 packet_put_int(nc
->self
);
1369 channel_post_connecting(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1372 socklen_t sz
= sizeof(err
);
1374 if (FD_ISSET(c
->sock
, writeset
)) {
1375 if (getsockopt(c
->sock
, SOL_SOCKET
, SO_ERROR
, &err
, &sz
) < 0) {
1377 error("getsockopt SO_ERROR failed");
1380 debug("channel %d: connected", c
->self
);
1381 c
->type
= SSH_CHANNEL_OPEN
;
1383 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
1384 packet_put_int(c
->remote_id
);
1385 packet_put_int(c
->self
);
1386 packet_put_int(c
->local_window
);
1387 packet_put_int(c
->local_maxpacket
);
1389 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
1390 packet_put_int(c
->remote_id
);
1391 packet_put_int(c
->self
);
1394 debug("channel %d: not connected: %s",
1395 c
->self
, strerror(err
));
1397 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
1398 packet_put_int(c
->remote_id
);
1399 packet_put_int(SSH2_OPEN_CONNECT_FAILED
);
1400 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
1401 packet_put_cstring(strerror(err
));
1402 packet_put_cstring("");
1405 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
1406 packet_put_int(c
->remote_id
);
1415 channel_handle_rfd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1417 char buf
[CHAN_RBUF
];
1421 FD_ISSET(c
->rfd
, readset
)) {
1423 len
= read(c
->rfd
, buf
, sizeof(buf
));
1424 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1426 #ifndef PTY_ZEROREAD
1429 if ((!c
->isatty
&& len
<= 0) ||
1430 (c
->isatty
&& (len
< 0 || (len
== 0 && errno
!= 0)))) {
1432 debug2("channel %d: read<=0 rfd %d len %d",
1433 c
->self
, c
->rfd
, len
);
1434 if (c
->type
!= SSH_CHANNEL_OPEN
) {
1435 debug2("channel %d: not open", c
->self
);
1438 } else if (compat13
) {
1439 buffer_clear(&c
->output
);
1440 c
->type
= SSH_CHANNEL_INPUT_DRAINING
;
1441 debug2("channel %d: input draining.", c
->self
);
1443 chan_read_failed(c
);
1447 if (c
->input_filter
!= NULL
) {
1448 if (c
->input_filter(c
, buf
, len
) == -1) {
1449 debug2("channel %d: filter stops", c
->self
);
1450 chan_read_failed(c
);
1452 } else if (c
->datagram
) {
1453 buffer_put_string(&c
->input
, buf
, len
);
1455 buffer_append(&c
->input
, buf
, len
);
1462 channel_handle_wfd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1465 u_char
*data
= NULL
, *buf
;
1469 /* Send buffered output data to the socket. */
1471 FD_ISSET(c
->wfd
, writeset
) &&
1472 buffer_len(&c
->output
) > 0) {
1473 if (c
->output_filter
!= NULL
) {
1474 if ((buf
= c
->output_filter(c
, &data
, &dlen
)) == NULL
) {
1475 debug2("channel %d: filter stops", c
->self
);
1476 if (c
->type
!= SSH_CHANNEL_OPEN
)
1479 chan_write_failed(c
);
1482 } else if (c
->datagram
) {
1483 buf
= data
= buffer_get_string(&c
->output
, &dlen
);
1485 buf
= data
= buffer_ptr(&c
->output
);
1486 dlen
= buffer_len(&c
->output
);
1490 /* ignore truncated writes, datagrams might get lost */
1491 c
->local_consumed
+= dlen
+ 4;
1492 len
= write(c
->wfd
, buf
, dlen
);
1494 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1497 if (c
->type
!= SSH_CHANNEL_OPEN
)
1500 chan_write_failed(c
);
1506 /* XXX: Later AIX versions can't push as much data to tty */
1507 if (compat20
&& c
->wfd_isatty
)
1508 dlen
= MIN(dlen
, 8*1024);
1511 len
= write(c
->wfd
, buf
, dlen
);
1512 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1515 if (c
->type
!= SSH_CHANNEL_OPEN
) {
1516 debug2("channel %d: not open", c
->self
);
1519 } else if (compat13
) {
1520 buffer_clear(&c
->output
);
1521 debug2("channel %d: input draining.", c
->self
);
1522 c
->type
= SSH_CHANNEL_INPUT_DRAINING
;
1524 chan_write_failed(c
);
1528 if (compat20
&& c
->isatty
&& dlen
>= 1 && buf
[0] != '\r') {
1529 if (tcgetattr(c
->wfd
, &tio
) == 0 &&
1530 !(tio
.c_lflag
& ECHO
) && (tio
.c_lflag
& ICANON
)) {
1532 * Simulate echo to reduce the impact of
1533 * traffic analysis. We need to match the
1534 * size of a SSH2_MSG_CHANNEL_DATA message
1535 * (4 byte channel id + buf)
1537 packet_send_ignore(4 + len
);
1541 buffer_consume(&c
->output
, len
);
1542 if (compat20
&& len
> 0) {
1543 c
->local_consumed
+= len
;
1550 channel_handle_efd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1552 char buf
[CHAN_RBUF
];
1555 /** XXX handle drain efd, too */
1557 if (c
->extended_usage
== CHAN_EXTENDED_WRITE
&&
1558 FD_ISSET(c
->efd
, writeset
) &&
1559 buffer_len(&c
->extended
) > 0) {
1560 len
= write(c
->efd
, buffer_ptr(&c
->extended
),
1561 buffer_len(&c
->extended
));
1562 debug2("channel %d: written %d to efd %d",
1563 c
->self
, len
, c
->efd
);
1564 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1567 debug2("channel %d: closing write-efd %d",
1569 channel_close_fd(&c
->efd
);
1571 buffer_consume(&c
->extended
, len
);
1572 c
->local_consumed
+= len
;
1574 } else if (c
->extended_usage
== CHAN_EXTENDED_READ
&&
1575 FD_ISSET(c
->efd
, readset
)) {
1576 len
= read(c
->efd
, buf
, sizeof(buf
));
1577 debug2("channel %d: read %d from efd %d",
1578 c
->self
, len
, c
->efd
);
1579 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1582 debug2("channel %d: closing read-efd %d",
1584 channel_close_fd(&c
->efd
);
1586 buffer_append(&c
->extended
, buf
, len
);
1594 channel_handle_ctl(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1599 /* Monitor control fd to detect if the slave client exits */
1600 if (c
->ctl_fd
!= -1 && FD_ISSET(c
->ctl_fd
, readset
)) {
1601 len
= read(c
->ctl_fd
, buf
, sizeof(buf
));
1602 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1605 debug2("channel %d: ctl read<=0", c
->self
);
1606 if (c
->type
!= SSH_CHANNEL_OPEN
) {
1607 debug2("channel %d: not open", c
->self
);
1611 chan_read_failed(c
);
1612 chan_write_failed(c
);
1616 fatal("%s: unexpected data on ctl fd", __func__
);
1622 channel_check_window(Channel
*c
)
1624 if (c
->type
== SSH_CHANNEL_OPEN
&&
1625 !(c
->flags
& (CHAN_CLOSE_SENT
|CHAN_CLOSE_RCVD
)) &&
1626 c
->local_window
< c
->local_window_max
/2 &&
1627 c
->local_consumed
> 0) {
1628 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
1629 packet_put_int(c
->remote_id
);
1630 packet_put_int(c
->local_consumed
);
1632 debug2("channel %d: window %d sent adjust %d",
1633 c
->self
, c
->local_window
,
1635 c
->local_window
+= c
->local_consumed
;
1636 c
->local_consumed
= 0;
1642 channel_post_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1646 channel_handle_rfd(c
, readset
, writeset
);
1647 channel_handle_wfd(c
, readset
, writeset
);
1650 channel_handle_efd(c
, readset
, writeset
);
1651 channel_handle_ctl(c
, readset
, writeset
);
1652 channel_check_window(c
);
1656 channel_post_output_drain_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1660 /* Send buffered output data to the socket. */
1661 if (FD_ISSET(c
->sock
, writeset
) && buffer_len(&c
->output
) > 0) {
1662 len
= write(c
->sock
, buffer_ptr(&c
->output
),
1663 buffer_len(&c
->output
));
1665 buffer_clear(&c
->output
);
1667 buffer_consume(&c
->output
, len
);
1672 channel_handler_init_20(void)
1674 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open
;
1675 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open
;
1676 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
1677 channel_pre
[SSH_CHANNEL_RPORT_LISTENER
] = &channel_pre_listener
;
1678 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
1679 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
1680 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
1681 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
1683 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
1684 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
1685 channel_post
[SSH_CHANNEL_RPORT_LISTENER
] = &channel_post_port_listener
;
1686 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
1687 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
1688 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
1689 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
1693 channel_handler_init_13(void)
1695 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open_13
;
1696 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open_13
;
1697 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
1698 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
1699 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
1700 channel_pre
[SSH_CHANNEL_INPUT_DRAINING
] = &channel_pre_input_draining
;
1701 channel_pre
[SSH_CHANNEL_OUTPUT_DRAINING
] = &channel_pre_output_draining
;
1702 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
1703 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
1705 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
1706 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
1707 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
1708 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
1709 channel_post
[SSH_CHANNEL_OUTPUT_DRAINING
] = &channel_post_output_drain_13
;
1710 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
1711 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
1715 channel_handler_init_15(void)
1717 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open
;
1718 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open
;
1719 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
1720 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
1721 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
1722 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
1723 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
1725 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
1726 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
1727 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
1728 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
1729 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
1730 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
1734 channel_handler_init(void)
1738 for (i
= 0; i
< SSH_CHANNEL_MAX_TYPE
; i
++) {
1739 channel_pre
[i
] = NULL
;
1740 channel_post
[i
] = NULL
;
1743 channel_handler_init_20();
1745 channel_handler_init_13();
1747 channel_handler_init_15();
1750 /* gc dead channels */
1752 channel_garbage_collect(Channel
*c
)
1756 if (c
->detach_user
!= NULL
) {
1757 if (!chan_is_dead(c
, c
->detach_close
))
1759 debug2("channel %d: gc: notify user", c
->self
);
1760 c
->detach_user(c
->self
, NULL
);
1761 /* if we still have a callback */
1762 if (c
->detach_user
!= NULL
)
1764 debug2("channel %d: gc: user detached", c
->self
);
1766 if (!chan_is_dead(c
, 1))
1768 debug2("channel %d: garbage collecting", c
->self
);
1773 channel_handler(chan_fn
*ftab
[], fd_set
*readset
, fd_set
*writeset
)
1775 static int did_init
= 0;
1780 channel_handler_init();
1783 for (i
= 0; i
< channels_alloc
; i
++) {
1787 if (ftab
[c
->type
] != NULL
)
1788 (*ftab
[c
->type
])(c
, readset
, writeset
);
1789 channel_garbage_collect(c
);
1794 * Allocate/update select bitmasks and add any bits relevant to channels in
1798 channel_prepare_select(fd_set
**readsetp
, fd_set
**writesetp
, int *maxfdp
,
1799 u_int
*nallocp
, int rekeying
)
1801 u_int n
, sz
, nfdset
;
1803 n
= MAX(*maxfdp
, channel_max_fd
);
1805 nfdset
= howmany(n
+1, NFDBITS
);
1806 /* Explicitly test here, because xrealloc isn't always called */
1807 if (nfdset
&& SIZE_T_MAX
/ nfdset
< sizeof(fd_mask
))
1808 fatal("channel_prepare_select: max_fd (%d) is too large", n
);
1809 sz
= nfdset
* sizeof(fd_mask
);
1811 /* perhaps check sz < nalloc/2 and shrink? */
1812 if (*readsetp
== NULL
|| sz
> *nallocp
) {
1813 *readsetp
= xrealloc(*readsetp
, nfdset
, sizeof(fd_mask
));
1814 *writesetp
= xrealloc(*writesetp
, nfdset
, sizeof(fd_mask
));
1818 memset(*readsetp
, 0, sz
);
1819 memset(*writesetp
, 0, sz
);
1822 channel_handler(channel_pre
, *readsetp
, *writesetp
);
1826 * After select, perform any appropriate operations for channels which have
1830 channel_after_select(fd_set
*readset
, fd_set
*writeset
)
1832 channel_handler(channel_post
, readset
, writeset
);
1836 /* If there is data to send to the connection, enqueue some of it now. */
1838 channel_output_poll(void)
1843 for (i
= 0; i
< channels_alloc
; i
++) {
1849 * We are only interested in channels that can have buffered
1853 if (c
->type
!= SSH_CHANNEL_OPEN
&&
1854 c
->type
!= SSH_CHANNEL_INPUT_DRAINING
)
1857 if (c
->type
!= SSH_CHANNEL_OPEN
)
1861 (c
->flags
& (CHAN_CLOSE_SENT
|CHAN_CLOSE_RCVD
))) {
1862 /* XXX is this true? */
1863 debug3("channel %d: will not send data after close", c
->self
);
1867 /* Get the amount of buffered data for this channel. */
1868 if ((c
->istate
== CHAN_INPUT_OPEN
||
1869 c
->istate
== CHAN_INPUT_WAIT_DRAIN
) &&
1870 (len
= buffer_len(&c
->input
)) > 0) {
1876 data
= buffer_get_string(&c
->input
,
1878 packet_start(SSH2_MSG_CHANNEL_DATA
);
1879 packet_put_int(c
->remote_id
);
1880 packet_put_string(data
, dlen
);
1882 c
->remote_window
-= dlen
+ 4;
1888 * Send some data for the other side over the secure
1892 if (len
> c
->remote_window
)
1893 len
= c
->remote_window
;
1894 if (len
> c
->remote_maxpacket
)
1895 len
= c
->remote_maxpacket
;
1897 if (packet_is_interactive()) {
1901 /* Keep the packets at reasonable size. */
1902 if (len
> packet_get_maxsize()/2)
1903 len
= packet_get_maxsize()/2;
1907 packet_start(compat20
?
1908 SSH2_MSG_CHANNEL_DATA
: SSH_MSG_CHANNEL_DATA
);
1909 packet_put_int(c
->remote_id
);
1910 packet_put_string(buffer_ptr(&c
->input
), len
);
1912 buffer_consume(&c
->input
, len
);
1913 c
->remote_window
-= len
;
1915 } else if (c
->istate
== CHAN_INPUT_WAIT_DRAIN
) {
1917 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
1919 * input-buffer is empty and read-socket shutdown:
1920 * tell peer, that we will not send more data: send IEOF.
1921 * hack for extended data: delay EOF if EFD still in use.
1923 if (CHANNEL_EFD_INPUT_ACTIVE(c
))
1924 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
1925 c
->self
, c
->efd
, buffer_len(&c
->extended
));
1929 /* Send extended data, i.e. stderr */
1931 !(c
->flags
& CHAN_EOF_SENT
) &&
1932 c
->remote_window
> 0 &&
1933 (len
= buffer_len(&c
->extended
)) > 0 &&
1934 c
->extended_usage
== CHAN_EXTENDED_READ
) {
1935 debug2("channel %d: rwin %u elen %u euse %d",
1936 c
->self
, c
->remote_window
, buffer_len(&c
->extended
),
1938 if (len
> c
->remote_window
)
1939 len
= c
->remote_window
;
1940 if (len
> c
->remote_maxpacket
)
1941 len
= c
->remote_maxpacket
;
1942 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
1943 packet_put_int(c
->remote_id
);
1944 packet_put_int(SSH2_EXTENDED_DATA_STDERR
);
1945 packet_put_string(buffer_ptr(&c
->extended
), len
);
1947 buffer_consume(&c
->extended
, len
);
1948 c
->remote_window
-= len
;
1949 debug2("channel %d: sent ext data %d", c
->self
, len
);
1955 /* -- protocol input */
1959 channel_input_data(int type
, u_int32_t seq
, void *ctxt
)
1966 /* Get the channel number and verify it. */
1967 id
= packet_get_int();
1968 c
= channel_lookup(id
);
1970 packet_disconnect("Received data for nonexistent channel %d.", id
);
1972 /* Ignore any data for non-open channels (might happen on close) */
1973 if (c
->type
!= SSH_CHANNEL_OPEN
&&
1974 c
->type
!= SSH_CHANNEL_X11_OPEN
)
1978 data
= packet_get_string(&data_len
);
1981 * Ignore data for protocol > 1.3 if output end is no longer open.
1982 * For protocol 2 the sending side is reducing its window as it sends
1983 * data, so we must 'fake' consumption of the data in order to ensure
1984 * that window updates are sent back. Otherwise the connection might
1987 if (!compat13
&& c
->ostate
!= CHAN_OUTPUT_OPEN
) {
1989 c
->local_window
-= data_len
;
1990 c
->local_consumed
+= data_len
;
1997 if (data_len
> c
->local_maxpacket
) {
1998 logit("channel %d: rcvd big packet %d, maxpack %d",
1999 c
->self
, data_len
, c
->local_maxpacket
);
2001 if (data_len
> c
->local_window
) {
2002 logit("channel %d: rcvd too much data %d, win %d",
2003 c
->self
, data_len
, c
->local_window
);
2007 c
->local_window
-= data_len
;
2011 buffer_put_string(&c
->output
, data
, data_len
);
2013 buffer_append(&c
->output
, data
, data_len
);
2019 channel_input_extended_data(int type
, u_int32_t seq
, void *ctxt
)
2023 u_int data_len
, tcode
;
2026 /* Get the channel number and verify it. */
2027 id
= packet_get_int();
2028 c
= channel_lookup(id
);
2031 packet_disconnect("Received extended_data for bad channel %d.", id
);
2032 if (c
->type
!= SSH_CHANNEL_OPEN
) {
2033 logit("channel %d: ext data for non open", id
);
2036 if (c
->flags
& CHAN_EOF_RCVD
) {
2037 if (datafellows
& SSH_BUG_EXTEOF
)
2038 debug("channel %d: accepting ext data after eof", id
);
2040 packet_disconnect("Received extended_data after EOF "
2041 "on channel %d.", id
);
2043 tcode
= packet_get_int();
2045 c
->extended_usage
!= CHAN_EXTENDED_WRITE
||
2046 tcode
!= SSH2_EXTENDED_DATA_STDERR
) {
2047 logit("channel %d: bad ext data", c
->self
);
2050 data
= packet_get_string(&data_len
);
2052 if (data_len
> c
->local_window
) {
2053 logit("channel %d: rcvd too much extended_data %d, win %d",
2054 c
->self
, data_len
, c
->local_window
);
2058 debug2("channel %d: rcvd ext data %d", c
->self
, data_len
);
2059 c
->local_window
-= data_len
;
2060 buffer_append(&c
->extended
, data
, data_len
);
2066 channel_input_ieof(int type
, u_int32_t seq
, void *ctxt
)
2071 id
= packet_get_int();
2073 c
= channel_lookup(id
);
2075 packet_disconnect("Received ieof for nonexistent channel %d.", id
);
2078 /* XXX force input close */
2079 if (c
->force_drain
&& c
->istate
== CHAN_INPUT_OPEN
) {
2080 debug("channel %d: FORCE input drain", c
->self
);
2081 c
->istate
= CHAN_INPUT_WAIT_DRAIN
;
2082 if (buffer_len(&c
->input
) == 0)
2090 channel_input_close(int type
, u_int32_t seq
, void *ctxt
)
2095 id
= packet_get_int();
2097 c
= channel_lookup(id
);
2099 packet_disconnect("Received close for nonexistent channel %d.", id
);
2102 * Send a confirmation that we have closed the channel and no more
2103 * data is coming for it.
2105 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
);
2106 packet_put_int(c
->remote_id
);
2110 * If the channel is in closed state, we have sent a close request,
2111 * and the other side will eventually respond with a confirmation.
2112 * Thus, we cannot free the channel here, because then there would be
2113 * no-one to receive the confirmation. The channel gets freed when
2114 * the confirmation arrives.
2116 if (c
->type
!= SSH_CHANNEL_CLOSED
) {
2118 * Not a closed channel - mark it as draining, which will
2119 * cause it to be freed later.
2121 buffer_clear(&c
->input
);
2122 c
->type
= SSH_CHANNEL_OUTPUT_DRAINING
;
2126 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2129 channel_input_oclose(int type
, u_int32_t seq
, void *ctxt
)
2131 int id
= packet_get_int();
2132 Channel
*c
= channel_lookup(id
);
2136 packet_disconnect("Received oclose for nonexistent channel %d.", id
);
2137 chan_rcvd_oclose(c
);
2142 channel_input_close_confirmation(int type
, u_int32_t seq
, void *ctxt
)
2144 int id
= packet_get_int();
2145 Channel
*c
= channel_lookup(id
);
2149 packet_disconnect("Received close confirmation for "
2150 "out-of-range channel %d.", id
);
2151 if (c
->type
!= SSH_CHANNEL_CLOSED
)
2152 packet_disconnect("Received close confirmation for "
2153 "non-closed channel %d (type %d).", id
, c
->type
);
2159 channel_input_open_confirmation(int type
, u_int32_t seq
, void *ctxt
)
2164 id
= packet_get_int();
2165 c
= channel_lookup(id
);
2167 if (c
==NULL
|| c
->type
!= SSH_CHANNEL_OPENING
)
2168 packet_disconnect("Received open confirmation for "
2169 "non-opening channel %d.", id
);
2170 remote_id
= packet_get_int();
2171 /* Record the remote channel number and mark that the channel is now open. */
2172 c
->remote_id
= remote_id
;
2173 c
->type
= SSH_CHANNEL_OPEN
;
2176 c
->remote_window
= packet_get_int();
2177 c
->remote_maxpacket
= packet_get_int();
2179 debug2("callback start");
2180 c
->confirm(c
->self
, c
->confirm_ctx
);
2181 debug2("callback done");
2183 debug2("channel %d: open confirm rwindow %u rmax %u", c
->self
,
2184 c
->remote_window
, c
->remote_maxpacket
);
2190 reason2txt(int reason
)
2193 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED
:
2194 return "administratively prohibited";
2195 case SSH2_OPEN_CONNECT_FAILED
:
2196 return "connect failed";
2197 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE
:
2198 return "unknown channel type";
2199 case SSH2_OPEN_RESOURCE_SHORTAGE
:
2200 return "resource shortage";
2202 return "unknown reason";
2207 channel_input_open_failure(int type
, u_int32_t seq
, void *ctxt
)
2210 char *msg
= NULL
, *lang
= NULL
;
2213 id
= packet_get_int();
2214 c
= channel_lookup(id
);
2216 if (c
==NULL
|| c
->type
!= SSH_CHANNEL_OPENING
)
2217 packet_disconnect("Received open failure for "
2218 "non-opening channel %d.", id
);
2220 reason
= packet_get_int();
2221 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
2222 msg
= packet_get_string(NULL
);
2223 lang
= packet_get_string(NULL
);
2225 logit("channel %d: open failed: %s%s%s", id
,
2226 reason2txt(reason
), msg
? ": ": "", msg
? msg
: "");
2233 /* Free the channel. This will also close the socket. */
2239 channel_input_window_adjust(int type
, u_int32_t seq
, void *ctxt
)
2248 /* Get the channel number and verify it. */
2249 id
= packet_get_int();
2250 c
= channel_lookup(id
);
2253 logit("Received window adjust for non-open channel %d.", id
);
2256 adjust
= packet_get_int();
2258 debug2("channel %d: rcvd adjust %u", id
, adjust
);
2259 c
->remote_window
+= adjust
;
2264 channel_input_port_open(int type
, u_int32_t seq
, void *ctxt
)
2268 char *host
, *originator_string
;
2269 int remote_id
, sock
= -1;
2271 remote_id
= packet_get_int();
2272 host
= packet_get_string(NULL
);
2273 host_port
= packet_get_int();
2275 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN
) {
2276 originator_string
= packet_get_string(NULL
);
2278 originator_string
= xstrdup("unknown (remote did not supply name)");
2281 sock
= channel_connect_to(host
, host_port
);
2283 c
= channel_new("connected socket",
2284 SSH_CHANNEL_CONNECTING
, sock
, sock
, -1, 0, 0, 0,
2285 originator_string
, 1);
2286 c
->remote_id
= remote_id
;
2288 xfree(originator_string
);
2290 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
2291 packet_put_int(remote_id
);
2298 /* -- tcp forwarding */
2301 channel_set_af(int af
)
2307 channel_setup_fwd_listener(int type
, const char *listen_addr
, u_short listen_port
,
2308 const char *host_to_connect
, u_short port_to_connect
, int gateway_ports
)
2311 int sock
, r
, success
= 0, wildcard
= 0, is_client
;
2312 struct addrinfo hints
, *ai
, *aitop
;
2313 const char *host
, *addr
;
2314 char ntop
[NI_MAXHOST
], strport
[NI_MAXSERV
];
2316 host
= (type
== SSH_CHANNEL_RPORT_LISTENER
) ?
2317 listen_addr
: host_to_connect
;
2318 is_client
= (type
== SSH_CHANNEL_PORT_LISTENER
);
2321 error("No forward host name.");
2324 if (strlen(host
) > SSH_CHANNEL_PATH_LEN
- 1) {
2325 error("Forward host name too long.");
2330 * Determine whether or not a port forward listens to loopback,
2331 * specified address or wildcard. On the client, a specified bind
2332 * address will always override gateway_ports. On the server, a
2333 * gateway_ports of 1 (``yes'') will override the client's
2334 * specification and force a wildcard bind, whereas a value of 2
2335 * (``clientspecified'') will bind to whatever address the client
2338 * Special-case listen_addrs are:
2340 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2341 * "" (empty string), "*" -> wildcard v4/v6
2342 * "localhost" -> loopback v4/v6
2345 if (listen_addr
== NULL
) {
2346 /* No address specified: default to gateway_ports setting */
2349 } else if (gateway_ports
|| is_client
) {
2350 if (((datafellows
& SSH_OLD_FORWARD_ADDR
) &&
2351 strcmp(listen_addr
, "0.0.0.0") == 0) ||
2352 *listen_addr
== '\0' || strcmp(listen_addr
, "*") == 0 ||
2353 (!is_client
&& gateway_ports
== 1))
2355 else if (strcmp(listen_addr
, "localhost") != 0)
2359 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2360 type
, wildcard
, (addr
== NULL
) ? "NULL" : addr
);
2363 * getaddrinfo returns a loopback address if the hostname is
2364 * set to NULL and hints.ai_flags is not AI_PASSIVE
2366 memset(&hints
, 0, sizeof(hints
));
2367 hints
.ai_family
= IPv4or6
;
2368 hints
.ai_flags
= wildcard
? AI_PASSIVE
: 0;
2369 hints
.ai_socktype
= SOCK_STREAM
;
2370 snprintf(strport
, sizeof strport
, "%d", listen_port
);
2371 if ((r
= getaddrinfo(addr
, strport
, &hints
, &aitop
)) != 0) {
2373 /* This really shouldn't happen */
2374 packet_disconnect("getaddrinfo: fatal error: %s",
2377 error("channel_setup_fwd_listener: "
2378 "getaddrinfo(%.64s): %s", addr
, gai_strerror(r
));
2383 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
2384 if (ai
->ai_family
!= AF_INET
&& ai
->ai_family
!= AF_INET6
)
2386 if (getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, ntop
, sizeof(ntop
),
2387 strport
, sizeof(strport
), NI_NUMERICHOST
|NI_NUMERICSERV
) != 0) {
2388 error("channel_setup_fwd_listener: getnameinfo failed");
2391 /* Create a port to listen for the host. */
2392 sock
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
2394 /* this is no error since kernel may not support ipv6 */
2395 verbose("socket: %.100s", strerror(errno
));
2399 channel_set_reuseaddr(sock
);
2401 debug("Local forwarding listening on %s port %s.", ntop
, strport
);
2403 /* Bind the socket to the address. */
2404 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
2405 /* address can be in use ipv6 address is already bound */
2407 error("bind: %.100s", strerror(errno
));
2409 verbose("bind: %.100s", strerror(errno
));
2414 /* Start listening for connections on the socket. */
2415 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0) {
2416 error("listen: %.100s", strerror(errno
));
2420 /* Allocate a channel number for the socket. */
2421 c
= channel_new("port listener", type
, sock
, sock
, -1,
2422 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
2423 0, "port listener", 1);
2424 strlcpy(c
->path
, host
, sizeof(c
->path
));
2425 c
->host_port
= port_to_connect
;
2426 c
->listening_port
= listen_port
;
2430 error("channel_setup_fwd_listener: cannot listen to port: %d",
2432 freeaddrinfo(aitop
);
2437 channel_cancel_rport_listener(const char *host
, u_short port
)
2442 for (i
= 0; i
< channels_alloc
; i
++) {
2443 Channel
*c
= channels
[i
];
2445 if (c
!= NULL
&& c
->type
== SSH_CHANNEL_RPORT_LISTENER
&&
2446 strncmp(c
->path
, host
, sizeof(c
->path
)) == 0 &&
2447 c
->listening_port
== port
) {
2448 debug2("%s: close channel %d", __func__
, i
);
2457 /* protocol local port fwd, used by ssh (and sshd in v1) */
2459 channel_setup_local_fwd_listener(const char *listen_host
, u_short listen_port
,
2460 const char *host_to_connect
, u_short port_to_connect
, int gateway_ports
)
2462 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER
,
2463 listen_host
, listen_port
, host_to_connect
, port_to_connect
,
2467 /* protocol v2 remote port fwd, used by sshd */
2469 channel_setup_remote_fwd_listener(const char *listen_address
,
2470 u_short listen_port
, int gateway_ports
)
2472 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER
,
2473 listen_address
, listen_port
, NULL
, 0, gateway_ports
);
2477 * Initiate forwarding of connections to port "port" on remote host through
2478 * the secure channel to host:port from local side.
2482 channel_request_remote_forwarding(const char *listen_host
, u_short listen_port
,
2483 const char *host_to_connect
, u_short port_to_connect
)
2485 int type
, success
= 0;
2487 /* Record locally that connection to this host/port is permitted. */
2488 if (num_permitted_opens
>= SSH_MAX_FORWARDS_PER_DIRECTION
)
2489 fatal("channel_request_remote_forwarding: too many forwards");
2491 /* Send the forward request to the remote side. */
2493 const char *address_to_bind
;
2494 if (listen_host
== NULL
)
2495 address_to_bind
= "localhost";
2496 else if (*listen_host
== '\0' || strcmp(listen_host
, "*") == 0)
2497 address_to_bind
= "";
2499 address_to_bind
= listen_host
;
2501 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
2502 packet_put_cstring("tcpip-forward");
2503 packet_put_char(1); /* boolean: want reply */
2504 packet_put_cstring(address_to_bind
);
2505 packet_put_int(listen_port
);
2507 packet_write_wait();
2508 /* Assume that server accepts the request */
2511 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST
);
2512 packet_put_int(listen_port
);
2513 packet_put_cstring(host_to_connect
);
2514 packet_put_int(port_to_connect
);
2516 packet_write_wait();
2518 /* Wait for response from the remote side. */
2519 type
= packet_read();
2521 case SSH_SMSG_SUCCESS
:
2524 case SSH_SMSG_FAILURE
:
2525 logit("Warning: Server denied remote port forwarding.");
2528 /* Unknown packet */
2529 packet_disconnect("Protocol error for port forward request:"
2530 "received packet type %d.", type
);
2534 permitted_opens
[num_permitted_opens
].host_to_connect
= xstrdup(host_to_connect
);
2535 permitted_opens
[num_permitted_opens
].port_to_connect
= port_to_connect
;
2536 permitted_opens
[num_permitted_opens
].listen_port
= listen_port
;
2537 num_permitted_opens
++;
2542 * Request cancellation of remote forwarding of connection host:port from
2546 channel_request_rforward_cancel(const char *host
, u_short port
)
2553 for (i
= 0; i
< num_permitted_opens
; i
++) {
2554 if (permitted_opens
[i
].host_to_connect
!= NULL
&&
2555 permitted_opens
[i
].listen_port
== port
)
2558 if (i
>= num_permitted_opens
) {
2559 debug("%s: requested forward not found", __func__
);
2562 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
2563 packet_put_cstring("cancel-tcpip-forward");
2565 packet_put_cstring(host
== NULL
? "" : host
);
2566 packet_put_int(port
);
2569 permitted_opens
[i
].listen_port
= 0;
2570 permitted_opens
[i
].port_to_connect
= 0;
2571 xfree(permitted_opens
[i
].host_to_connect
);
2572 permitted_opens
[i
].host_to_connect
= NULL
;
2576 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2577 * listening for the port, and sends back a success reply (or disconnect
2578 * message if there was an error). This never returns if there was an error.
2581 channel_input_port_forward_request(int is_root
, int gateway_ports
)
2583 u_short port
, host_port
;
2586 /* Get arguments from the packet. */
2587 port
= packet_get_int();
2588 hostname
= packet_get_string(NULL
);
2589 host_port
= packet_get_int();
2593 * Check that an unprivileged user is not trying to forward a
2596 if (port
< IPPORT_RESERVED
&& !is_root
)
2598 "Requested forwarding of port %d but user is not root.",
2601 packet_disconnect("Dynamic forwarding denied.");
2604 /* Initiate forwarding */
2605 channel_setup_local_fwd_listener(NULL
, port
, hostname
,
2606 host_port
, gateway_ports
);
2608 /* Free the argument string. */
2613 * Permits opening to any host/port if permitted_opens[] is empty. This is
2614 * usually called by the server, because the user could connect to any port
2615 * anyway, and the server has no way to know but to trust the client anyway.
2618 channel_permit_all_opens(void)
2620 if (num_permitted_opens
== 0)
2621 all_opens_permitted
= 1;
2625 channel_add_permitted_opens(char *host
, int port
)
2627 if (num_permitted_opens
>= SSH_MAX_FORWARDS_PER_DIRECTION
)
2628 fatal("channel_request_remote_forwarding: too many forwards");
2629 debug("allow port forwarding to host %s port %d", host
, port
);
2631 permitted_opens
[num_permitted_opens
].host_to_connect
= xstrdup(host
);
2632 permitted_opens
[num_permitted_opens
].port_to_connect
= port
;
2633 num_permitted_opens
++;
2635 all_opens_permitted
= 0;
2639 channel_clear_permitted_opens(void)
2643 for (i
= 0; i
< num_permitted_opens
; i
++)
2644 if (permitted_opens
[i
].host_to_connect
!= NULL
)
2645 xfree(permitted_opens
[i
].host_to_connect
);
2646 num_permitted_opens
= 0;
2650 /* return socket to remote host, port */
2652 connect_to(const char *host
, u_short port
)
2654 struct addrinfo hints
, *ai
, *aitop
;
2655 char ntop
[NI_MAXHOST
], strport
[NI_MAXSERV
];
2659 memset(&hints
, 0, sizeof(hints
));
2660 hints
.ai_family
= IPv4or6
;
2661 hints
.ai_socktype
= SOCK_STREAM
;
2662 snprintf(strport
, sizeof strport
, "%d", port
);
2663 if ((gaierr
= getaddrinfo(host
, strport
, &hints
, &aitop
)) != 0) {
2664 error("connect_to %.100s: unknown host (%s)", host
,
2665 gai_strerror(gaierr
));
2668 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
2669 if (ai
->ai_family
!= AF_INET
&& ai
->ai_family
!= AF_INET6
)
2671 if (getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, ntop
, sizeof(ntop
),
2672 strport
, sizeof(strport
), NI_NUMERICHOST
|NI_NUMERICSERV
) != 0) {
2673 error("connect_to: getnameinfo failed");
2676 sock
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
2678 if (ai
->ai_next
== NULL
)
2679 error("socket: %.100s", strerror(errno
));
2681 verbose("socket: %.100s", strerror(errno
));
2684 if (set_nonblock(sock
) == -1)
2685 fatal("%s: set_nonblock(%d)", __func__
, sock
);
2686 if (connect(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0 &&
2687 errno
!= EINPROGRESS
) {
2688 error("connect_to %.100s port %s: %.100s", ntop
, strport
,
2691 continue; /* fail -- try next */
2693 break; /* success */
2696 freeaddrinfo(aitop
);
2698 error("connect_to %.100s port %d: failed.", host
, port
);
2707 channel_connect_by_listen_address(u_short listen_port
)
2711 for (i
= 0; i
< num_permitted_opens
; i
++)
2712 if (permitted_opens
[i
].host_to_connect
!= NULL
&&
2713 permitted_opens
[i
].listen_port
== listen_port
)
2715 permitted_opens
[i
].host_to_connect
,
2716 permitted_opens
[i
].port_to_connect
);
2717 error("WARNING: Server requests forwarding for unknown listen_port %d",
2722 /* Check if connecting to that port is permitted and connect. */
2724 channel_connect_to(const char *host
, u_short port
)
2728 permit
= all_opens_permitted
;
2730 for (i
= 0; i
< num_permitted_opens
; i
++)
2731 if (permitted_opens
[i
].host_to_connect
!= NULL
&&
2732 permitted_opens
[i
].port_to_connect
== port
&&
2733 strcmp(permitted_opens
[i
].host_to_connect
, host
) == 0)
2738 logit("Received request to connect to host %.100s port %d, "
2739 "but the request was denied.", host
, port
);
2742 return connect_to(host
, port
);
2746 channel_send_window_changes(void)
2751 for (i
= 0; i
< channels_alloc
; i
++) {
2752 if (channels
[i
] == NULL
|| !channels
[i
]->client_tty
||
2753 channels
[i
]->type
!= SSH_CHANNEL_OPEN
)
2755 if (ioctl(channels
[i
]->rfd
, TIOCGWINSZ
, &ws
) < 0)
2757 channel_request_start(i
, "window-change", 0);
2758 packet_put_int((u_int
)ws
.ws_col
);
2759 packet_put_int((u_int
)ws
.ws_row
);
2760 packet_put_int((u_int
)ws
.ws_xpixel
);
2761 packet_put_int((u_int
)ws
.ws_ypixel
);
2766 /* -- X11 forwarding */
2769 * Creates an internet domain socket for listening for X11 connections.
2770 * Returns 0 and a suitable display number for the DISPLAY variable
2771 * stored in display_numberp , or -1 if an error occurs.
2774 x11_create_display_inet(int x11_display_offset
, int x11_use_localhost
,
2775 int single_connection
, u_int
*display_numberp
, int **chanids
)
2778 int display_number
, sock
;
2780 struct addrinfo hints
, *ai
, *aitop
;
2781 char strport
[NI_MAXSERV
];
2782 int gaierr
, n
, num_socks
= 0, socks
[NUM_SOCKS
];
2784 if (chanids
== NULL
)
2787 for (display_number
= x11_display_offset
;
2788 display_number
< MAX_DISPLAYS
;
2790 port
= 6000 + display_number
;
2791 memset(&hints
, 0, sizeof(hints
));
2792 hints
.ai_family
= IPv4or6
;
2793 hints
.ai_flags
= x11_use_localhost
? 0: AI_PASSIVE
;
2794 hints
.ai_socktype
= SOCK_STREAM
;
2795 snprintf(strport
, sizeof strport
, "%d", port
);
2796 if ((gaierr
= getaddrinfo(NULL
, strport
, &hints
, &aitop
)) != 0) {
2797 error("getaddrinfo: %.100s", gai_strerror(gaierr
));
2800 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
2801 if (ai
->ai_family
!= AF_INET
&& ai
->ai_family
!= AF_INET6
)
2803 sock
= socket(ai
->ai_family
, ai
->ai_socktype
,
2806 if ((errno
!= EINVAL
) && (errno
!= EAFNOSUPPORT
)) {
2807 error("socket: %.100s", strerror(errno
));
2808 freeaddrinfo(aitop
);
2811 debug("x11_create_display_inet: Socket family %d not supported",
2817 if (ai
->ai_family
== AF_INET6
) {
2819 if (setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &on
, sizeof(on
)) < 0)
2820 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno
));
2823 channel_set_reuseaddr(sock
);
2824 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
2825 debug2("bind port %d: %.100s", port
, strerror(errno
));
2831 for (n
= 0; n
< num_socks
; n
++) {
2837 socks
[num_socks
++] = sock
;
2838 #ifndef DONT_TRY_OTHER_AF
2839 if (num_socks
== NUM_SOCKS
)
2842 if (x11_use_localhost
) {
2843 if (num_socks
== NUM_SOCKS
)
2850 freeaddrinfo(aitop
);
2854 if (display_number
>= MAX_DISPLAYS
) {
2855 error("Failed to allocate internet-domain X11 display socket.");
2858 /* Start listening for connections on the socket. */
2859 for (n
= 0; n
< num_socks
; n
++) {
2861 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0) {
2862 error("listen: %.100s", strerror(errno
));
2868 /* Allocate a channel for each socket. */
2869 *chanids
= xcalloc(num_socks
+ 1, sizeof(**chanids
));
2870 for (n
= 0; n
< num_socks
; n
++) {
2872 nc
= channel_new("x11 listener",
2873 SSH_CHANNEL_X11_LISTENER
, sock
, sock
, -1,
2874 CHAN_X11_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
,
2875 0, "X11 inet listener", 1);
2876 nc
->single_connection
= single_connection
;
2877 (*chanids
)[n
] = nc
->self
;
2881 /* Return the display number for the DISPLAY environment variable. */
2882 *display_numberp
= display_number
;
2887 connect_local_xsocket(u_int dnr
)
2890 struct sockaddr_un addr
;
2892 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
2894 error("socket: %.100s", strerror(errno
));
2895 memset(&addr
, 0, sizeof(addr
));
2896 addr
.sun_family
= AF_UNIX
;
2897 snprintf(addr
.sun_path
, sizeof addr
.sun_path
, _PATH_UNIX_X
, dnr
);
2898 if (connect(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)) == 0)
2901 error("connect %.100s: %.100s", addr
.sun_path
, strerror(errno
));
2906 x11_connect_display(void)
2908 u_int display_number
;
2909 const char *display
;
2910 char buf
[1024], *cp
;
2911 struct addrinfo hints
, *ai
, *aitop
;
2912 char strport
[NI_MAXSERV
];
2913 int gaierr
, sock
= 0;
2915 /* Try to open a socket for the local X server. */
2916 display
= getenv("DISPLAY");
2918 error("DISPLAY not set.");
2922 * Now we decode the value of the DISPLAY variable and make a
2923 * connection to the real X server.
2927 * Check if it is a unix domain socket. Unix domain displays are in
2928 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
2930 if (strncmp(display
, "unix:", 5) == 0 ||
2931 display
[0] == ':') {
2932 /* Connect to the unix domain socket. */
2933 if (sscanf(strrchr(display
, ':') + 1, "%u", &display_number
) != 1) {
2934 error("Could not parse display number from DISPLAY: %.100s",
2938 /* Create a socket. */
2939 sock
= connect_local_xsocket(display_number
);
2943 /* OK, we now have a connection to the display. */
2947 * Connect to an inet socket. The DISPLAY value is supposedly
2948 * hostname:d[.s], where hostname may also be numeric IP address.
2950 strlcpy(buf
, display
, sizeof(buf
));
2951 cp
= strchr(buf
, ':');
2953 error("Could not find ':' in DISPLAY: %.100s", display
);
2957 /* buf now contains the host name. But first we parse the display number. */
2958 if (sscanf(cp
+ 1, "%u", &display_number
) != 1) {
2959 error("Could not parse display number from DISPLAY: %.100s",
2964 /* Look up the host address */
2965 memset(&hints
, 0, sizeof(hints
));
2966 hints
.ai_family
= IPv4or6
;
2967 hints
.ai_socktype
= SOCK_STREAM
;
2968 snprintf(strport
, sizeof strport
, "%u", 6000 + display_number
);
2969 if ((gaierr
= getaddrinfo(buf
, strport
, &hints
, &aitop
)) != 0) {
2970 error("%.100s: unknown host. (%s)", buf
, gai_strerror(gaierr
));
2973 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
2974 /* Create a socket. */
2975 sock
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
2977 debug2("socket: %.100s", strerror(errno
));
2980 /* Connect it to the display. */
2981 if (connect(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
2982 debug2("connect %.100s port %u: %.100s", buf
,
2983 6000 + display_number
, strerror(errno
));
2990 freeaddrinfo(aitop
);
2992 error("connect %.100s port %u: %.100s", buf
, 6000 + display_number
,
3001 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3002 * the remote channel number. We should do whatever we want, and respond
3003 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3007 x11_input_open(int type
, u_int32_t seq
, void *ctxt
)
3010 int remote_id
, sock
= 0;
3013 debug("Received X11 open request.");
3015 remote_id
= packet_get_int();
3017 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN
) {
3018 remote_host
= packet_get_string(NULL
);
3020 remote_host
= xstrdup("unknown (remote did not supply name)");
3024 /* Obtain a connection to the real X display. */
3025 sock
= x11_connect_display();
3027 /* Allocate a channel for this connection. */
3028 c
= channel_new("connected x11 socket",
3029 SSH_CHANNEL_X11_OPEN
, sock
, sock
, -1, 0, 0, 0,
3031 c
->remote_id
= remote_id
;
3036 /* Send refusal to the remote host. */
3037 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
3038 packet_put_int(remote_id
);
3040 /* Send a confirmation to the remote host. */
3041 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
3042 packet_put_int(remote_id
);
3043 packet_put_int(c
->self
);
3048 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3050 deny_input_open(int type
, u_int32_t seq
, void *ctxt
)
3052 int rchan
= packet_get_int();
3055 case SSH_SMSG_AGENT_OPEN
:
3056 error("Warning: ssh server tried agent forwarding.");
3058 case SSH_SMSG_X11_OPEN
:
3059 error("Warning: ssh server tried X11 forwarding.");
3062 error("deny_input_open: type %d", type
);
3065 error("Warning: this is probably a break-in attempt by a malicious server.");
3066 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
3067 packet_put_int(rchan
);
3072 * Requests forwarding of X11 connections, generates fake authentication
3073 * data, and enables authentication spoofing.
3074 * This should be called in the client only.
3077 x11_request_forwarding_with_spoofing(int client_session_id
, const char *disp
,
3078 const char *proto
, const char *data
)
3080 u_int data_len
= (u_int
) strlen(data
) / 2;
3087 if (x11_saved_display
== NULL
)
3088 x11_saved_display
= xstrdup(disp
);
3089 else if (strcmp(disp
, x11_saved_display
) != 0) {
3090 error("x11_request_forwarding_with_spoofing: different "
3091 "$DISPLAY already forwarded");
3097 cp
= strchr(disp
, ':');
3099 cp
= strchr(cp
, '.');
3101 screen_number
= (u_int
)strtonum(cp
+ 1, 0, 400, NULL
);
3105 if (x11_saved_proto
== NULL
) {
3106 /* Save protocol name. */
3107 x11_saved_proto
= xstrdup(proto
);
3109 * Extract real authentication data and generate fake data
3110 * of the same length.
3112 x11_saved_data
= xmalloc(data_len
);
3113 x11_fake_data
= xmalloc(data_len
);
3114 for (i
= 0; i
< data_len
; i
++) {
3115 if (sscanf(data
+ 2 * i
, "%2x", &value
) != 1)
3116 fatal("x11_request_forwarding: bad "
3117 "authentication data: %.100s", data
);
3120 x11_saved_data
[i
] = value
;
3121 x11_fake_data
[i
] = rnd
& 0xff;
3124 x11_saved_data_len
= data_len
;
3125 x11_fake_data_len
= data_len
;
3128 /* Convert the fake data into hex. */
3129 new_data
= tohex(x11_fake_data
, data_len
);
3131 /* Send the request packet. */
3133 channel_request_start(client_session_id
, "x11-req", 0);
3134 packet_put_char(0); /* XXX bool single connection */
3136 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING
);
3138 packet_put_cstring(proto
);
3139 packet_put_cstring(new_data
);
3140 packet_put_int(screen_number
);
3142 packet_write_wait();
3147 /* -- agent forwarding */
3149 /* Sends a message to the server to request authentication fd forwarding. */
3152 auth_request_forwarding(void)
3154 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING
);
3156 packet_write_wait();