1 /* $OpenBSD: channels.c,v 1.296 2009/05/25 06:48:00 andreas Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * This file contains functions for generic socket connection forwarding.
7 * There is also code for initiating connection forwarding for X11 connections,
8 * arbitrary tcp/ip connections, and the authentication agent connection.
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
16 * SSH2 support added by Markus Friedl.
17 * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
18 * Copyright (c) 1999 Dug Song. All rights reserved.
19 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
45 #include <sys/ioctl.h>
47 #include <sys/socket.h>
48 #ifdef HAVE_SYS_TIME_H
49 # include <sys/time.h>
52 #include <netinet/in.h>
53 #include <arpa/inet.h>
64 #include "openbsd-compat/sys-queue.h"
78 #include "pathnames.h"
83 * Pointer to an array containing all allocated channels. The array is
84 * dynamically extended as needed.
86 static Channel
**channels
= NULL
;
89 * Size of the channel array. All slots of the array must always be
90 * initialized (at least the type field); unused slots set to NULL
92 static u_int channels_alloc
= 0;
95 * Maximum file descriptor value used in any of the channels. This is
96 * updated in channel_new.
98 static int channel_max_fd
= 0;
101 /* -- tcp forwarding */
104 * Data structure for storing which hosts are permitted for forward requests.
105 * The local sides of any remote forwards are stored in this array to prevent
106 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
107 * network (which might be behind a firewall).
110 char *host_to_connect
; /* Connect to 'host'. */
111 u_short port_to_connect
; /* Connect to 'port'. */
112 u_short listen_port
; /* Remote side should listen port number. */
115 /* List of all permitted host/port pairs to connect by the user. */
116 static ForwardPermission permitted_opens
[SSH_MAX_FORWARDS_PER_DIRECTION
];
118 /* List of all permitted host/port pairs to connect by the admin. */
119 static ForwardPermission permitted_adm_opens
[SSH_MAX_FORWARDS_PER_DIRECTION
];
121 /* Number of permitted host/port pairs in the array permitted by the user. */
122 static int num_permitted_opens
= 0;
124 /* Number of permitted host/port pair in the array permitted by the admin. */
125 static int num_adm_permitted_opens
= 0;
128 * If this is true, all opens are permitted. This is the case on the server
129 * on which we have to trust the client anyway, and the user could do
130 * anything after logging in anyway.
132 static int all_opens_permitted
= 0;
135 /* -- X11 forwarding */
137 /* Maximum number of fake X11 displays to try. */
138 #define MAX_DISPLAYS 1000
140 /* Saved X11 local (client) display. */
141 static char *x11_saved_display
= NULL
;
143 /* Saved X11 authentication protocol name. */
144 static char *x11_saved_proto
= NULL
;
146 /* Saved X11 authentication data. This is the real data. */
147 static char *x11_saved_data
= NULL
;
148 static u_int x11_saved_data_len
= 0;
151 * Fake X11 authentication data. This is what the server will be sending us;
152 * we should replace any occurrences of this by the real data.
154 static u_char
*x11_fake_data
= NULL
;
155 static u_int x11_fake_data_len
;
158 /* -- agent forwarding */
162 /* AF_UNSPEC or AF_INET or AF_INET6 */
163 static int IPv4or6
= AF_UNSPEC
;
166 static void port_open_helper(Channel
*c
, char *rtype
);
168 /* non-blocking connect helpers */
169 static int connect_next(struct channel_connect
*);
170 static void channel_connect_ctx_free(struct channel_connect
*);
173 static int hpn_disabled
= 0;
174 static int hpn_buffer_size
= 2 * 1024 * 1024;
176 /* -- channel core */
181 channel_by_id(int id
)
185 if (id
< 0 || (u_int
)id
>= channels_alloc
) {
186 logit("channel_by_id: %d: bad id", id
);
191 logit("channel_by_id: %d: bad id: channel free", id
);
198 * Returns the channel if it is allowed to receive protocol messages.
199 * Private channels, like listening sockets, may not receive messages.
202 channel_lookup(int id
)
206 if ((c
= channel_by_id(id
)) == NULL
)
210 case SSH_CHANNEL_X11_OPEN
:
211 case SSH_CHANNEL_LARVAL
:
212 case SSH_CHANNEL_CONNECTING
:
213 case SSH_CHANNEL_DYNAMIC
:
214 case SSH_CHANNEL_OPENING
:
215 case SSH_CHANNEL_OPEN
:
216 case SSH_CHANNEL_INPUT_DRAINING
:
217 case SSH_CHANNEL_OUTPUT_DRAINING
:
220 logit("Non-public channel %d, type %d.", id
, c
->type
);
225 * Register filedescriptors for a channel, used when allocating a channel or
226 * when the channel consumer/producer is ready, e.g. shell exec'd
229 channel_register_fds(Channel
*c
, int rfd
, int wfd
, int efd
,
230 int extusage
, int nonblock
, int is_tty
)
232 /* Update the maximum file descriptor value. */
233 channel_max_fd
= MAX(channel_max_fd
, rfd
);
234 channel_max_fd
= MAX(channel_max_fd
, wfd
);
235 channel_max_fd
= MAX(channel_max_fd
, efd
);
237 /* XXX set close-on-exec -markus */
241 c
->sock
= (rfd
== wfd
) ? rfd
: -1;
242 c
->ctl_fd
= -1; /* XXX: set elsewhere */
244 c
->extended_usage
= extusage
;
246 if ((c
->isatty
= is_tty
) != 0)
247 debug2("channel %d: rfd %d isatty", c
->self
, c
->rfd
);
248 c
->wfd_isatty
= is_tty
|| isatty(c
->wfd
);
250 /* enable nonblocking mode */
262 * Allocate a new channel object and set its type and socket. This will cause
263 * remote_name to be freed.
266 channel_new(char *ctype
, int type
, int rfd
, int wfd
, int efd
,
267 u_int window
, u_int maxpack
, int extusage
, char *remote_name
, int nonblock
)
273 /* Do initial allocation if this is the first call. */
274 if (channels_alloc
== 0) {
276 channels
= xcalloc(channels_alloc
, sizeof(Channel
*));
277 for (i
= 0; i
< channels_alloc
; i
++)
280 /* Try to find a free slot where to put the new channel. */
281 for (found
= -1, i
= 0; i
< channels_alloc
; i
++)
282 if (channels
[i
] == NULL
) {
283 /* Found a free slot. */
288 /* There are no free slots. Take last+1 slot and expand the array. */
289 found
= channels_alloc
;
290 if (channels_alloc
> 10000)
291 fatal("channel_new: internal error: channels_alloc %d "
292 "too big.", channels_alloc
);
293 channels
= xrealloc(channels
, channels_alloc
+ 10,
295 channels_alloc
+= 10;
296 debug2("channel: expanding %d", channels_alloc
);
297 for (i
= found
; i
< channels_alloc
; i
++)
300 /* Initialize and return new channel. */
301 c
= channels
[found
] = xcalloc(1, sizeof(Channel
));
302 buffer_init(&c
->input
);
303 buffer_init(&c
->output
);
304 buffer_init(&c
->extended
);
306 c
->ostate
= CHAN_OUTPUT_OPEN
;
307 c
->istate
= CHAN_INPUT_OPEN
;
309 channel_register_fds(c
, rfd
, wfd
, efd
, extusage
, nonblock
, 0);
313 c
->local_window
= window
;
314 c
->local_window_max
= window
;
315 c
->local_consumed
= 0;
316 c
->local_maxpacket
= maxpack
;
317 c
->dynamic_window
= 0;
319 c
->remote_name
= xstrdup(remote_name
);
320 c
->remote_window
= 0;
321 c
->remote_maxpacket
= 0;
323 c
->single_connection
= 0;
324 c
->detach_user
= NULL
;
326 c
->open_confirm
= NULL
;
327 c
->open_confirm_ctx
= NULL
;
328 c
->input_filter
= NULL
;
329 c
->output_filter
= NULL
;
330 c
->filter_ctx
= NULL
;
331 c
->filter_cleanup
= NULL
;
332 TAILQ_INIT(&c
->status_confirms
);
333 debug("channel %d: new [%s]", found
, remote_name
);
338 channel_find_maxfd(void)
344 for (i
= 0; i
< channels_alloc
; i
++) {
347 max
= MAX(max
, c
->rfd
);
348 max
= MAX(max
, c
->wfd
);
349 max
= MAX(max
, c
->efd
);
356 channel_close_fd(int *fdp
)
358 int ret
= 0, fd
= *fdp
;
363 if (fd
== channel_max_fd
)
364 channel_max_fd
= channel_find_maxfd();
369 /* Close all channel fd/socket. */
371 channel_close_fds(Channel
*c
)
373 debug3("channel %d: close_fds r %d w %d e %d c %d",
374 c
->self
, c
->rfd
, c
->wfd
, c
->efd
, c
->ctl_fd
);
376 channel_close_fd(&c
->sock
);
377 channel_close_fd(&c
->ctl_fd
);
378 channel_close_fd(&c
->rfd
);
379 channel_close_fd(&c
->wfd
);
380 channel_close_fd(&c
->efd
);
383 /* Free the channel and close its fd/socket. */
385 channel_free(Channel
*c
)
389 struct channel_confirm
*cc
;
391 for (n
= 0, i
= 0; i
< channels_alloc
; i
++)
394 debug("channel %d: free: %s, nchannels %u", c
->self
,
395 c
->remote_name
? c
->remote_name
: "???", n
);
397 s
= channel_open_message();
398 debug3("channel %d: status: %s", c
->self
, s
);
402 shutdown(c
->sock
, SHUT_RDWR
);
404 shutdown(c
->ctl_fd
, SHUT_RDWR
);
405 channel_close_fds(c
);
406 buffer_free(&c
->input
);
407 buffer_free(&c
->output
);
408 buffer_free(&c
->extended
);
409 if (c
->remote_name
) {
410 xfree(c
->remote_name
);
411 c
->remote_name
= NULL
;
417 while ((cc
= TAILQ_FIRST(&c
->status_confirms
)) != NULL
) {
418 if (cc
->abandon_cb
!= NULL
)
419 cc
->abandon_cb(c
, cc
->ctx
);
420 TAILQ_REMOVE(&c
->status_confirms
, cc
, entry
);
421 bzero(cc
, sizeof(*cc
));
424 if (c
->filter_cleanup
!= NULL
&& c
->filter_ctx
!= NULL
)
425 c
->filter_cleanup(c
->self
, c
->filter_ctx
);
426 channels
[c
->self
] = NULL
;
431 channel_free_all(void)
435 for (i
= 0; i
< channels_alloc
; i
++)
436 if (channels
[i
] != NULL
)
437 channel_free(channels
[i
]);
441 * Closes the sockets/fds of all channels. This is used to close extra file
442 * descriptors after a fork.
445 channel_close_all(void)
449 for (i
= 0; i
< channels_alloc
; i
++)
450 if (channels
[i
] != NULL
)
451 channel_close_fds(channels
[i
]);
455 * Stop listening to channels.
458 channel_stop_listening(void)
463 for (i
= 0; i
< channels_alloc
; i
++) {
467 case SSH_CHANNEL_AUTH_SOCKET
:
468 case SSH_CHANNEL_PORT_LISTENER
:
469 case SSH_CHANNEL_RPORT_LISTENER
:
470 case SSH_CHANNEL_X11_LISTENER
:
471 channel_close_fd(&c
->sock
);
480 * Returns true if no channel has too much buffered data, and false if one or
481 * more channel is overfull.
484 channel_not_very_much_buffered_data(void)
489 for (i
= 0; i
< channels_alloc
; i
++) {
491 if (c
!= NULL
&& c
->type
== SSH_CHANNEL_OPEN
) {
494 buffer_len(&c
->input
) > packet_get_maxsize()) {
495 debug2("channel %d: big input buffer %d",
496 c
->self
, buffer_len(&c
->input
));
500 if (buffer_len(&c
->output
) > packet_get_maxsize()) {
501 debug2("channel %d: big output buffer %u > %u",
502 c
->self
, buffer_len(&c
->output
),
503 packet_get_maxsize());
511 /* Returns true if any channel is still open. */
513 channel_still_open(void)
518 for (i
= 0; i
< channels_alloc
; i
++) {
523 case SSH_CHANNEL_X11_LISTENER
:
524 case SSH_CHANNEL_PORT_LISTENER
:
525 case SSH_CHANNEL_RPORT_LISTENER
:
526 case SSH_CHANNEL_CLOSED
:
527 case SSH_CHANNEL_AUTH_SOCKET
:
528 case SSH_CHANNEL_DYNAMIC
:
529 case SSH_CHANNEL_CONNECTING
:
530 case SSH_CHANNEL_ZOMBIE
:
532 case SSH_CHANNEL_LARVAL
:
534 fatal("cannot happen: SSH_CHANNEL_LARVAL");
536 case SSH_CHANNEL_OPENING
:
537 case SSH_CHANNEL_OPEN
:
538 case SSH_CHANNEL_X11_OPEN
:
540 case SSH_CHANNEL_INPUT_DRAINING
:
541 case SSH_CHANNEL_OUTPUT_DRAINING
:
543 fatal("cannot happen: OUT_DRAIN");
546 fatal("channel_still_open: bad channel type %d", c
->type
);
553 /* Returns the id of an open channel suitable for keepaliving */
555 channel_find_open(void)
560 for (i
= 0; i
< channels_alloc
; i
++) {
562 if (c
== NULL
|| c
->remote_id
< 0)
565 case SSH_CHANNEL_CLOSED
:
566 case SSH_CHANNEL_DYNAMIC
:
567 case SSH_CHANNEL_X11_LISTENER
:
568 case SSH_CHANNEL_PORT_LISTENER
:
569 case SSH_CHANNEL_RPORT_LISTENER
:
570 case SSH_CHANNEL_OPENING
:
571 case SSH_CHANNEL_CONNECTING
:
572 case SSH_CHANNEL_ZOMBIE
:
574 case SSH_CHANNEL_LARVAL
:
575 case SSH_CHANNEL_AUTH_SOCKET
:
576 case SSH_CHANNEL_OPEN
:
577 case SSH_CHANNEL_X11_OPEN
:
579 case SSH_CHANNEL_INPUT_DRAINING
:
580 case SSH_CHANNEL_OUTPUT_DRAINING
:
582 fatal("cannot happen: OUT_DRAIN");
585 fatal("channel_find_open: bad channel type %d", c
->type
);
594 * Returns a message describing the currently open forwarded connections,
595 * suitable for sending to the client. The message contains crlf pairs for
599 channel_open_message(void)
606 buffer_init(&buffer
);
607 snprintf(buf
, sizeof buf
, "The following connections are open:\r\n");
608 buffer_append(&buffer
, buf
, strlen(buf
));
609 for (i
= 0; i
< channels_alloc
; i
++) {
614 case SSH_CHANNEL_X11_LISTENER
:
615 case SSH_CHANNEL_PORT_LISTENER
:
616 case SSH_CHANNEL_RPORT_LISTENER
:
617 case SSH_CHANNEL_CLOSED
:
618 case SSH_CHANNEL_AUTH_SOCKET
:
619 case SSH_CHANNEL_ZOMBIE
:
621 case SSH_CHANNEL_LARVAL
:
622 case SSH_CHANNEL_OPENING
:
623 case SSH_CHANNEL_CONNECTING
:
624 case SSH_CHANNEL_DYNAMIC
:
625 case SSH_CHANNEL_OPEN
:
626 case SSH_CHANNEL_X11_OPEN
:
627 case SSH_CHANNEL_INPUT_DRAINING
:
628 case SSH_CHANNEL_OUTPUT_DRAINING
:
629 snprintf(buf
, sizeof buf
,
630 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cfd %d)\r\n",
631 c
->self
, c
->remote_name
,
632 c
->type
, c
->remote_id
,
633 c
->istate
, buffer_len(&c
->input
),
634 c
->ostate
, buffer_len(&c
->output
),
635 c
->rfd
, c
->wfd
, c
->ctl_fd
);
636 buffer_append(&buffer
, buf
, strlen(buf
));
639 fatal("channel_open_message: bad channel type %d", c
->type
);
643 buffer_append(&buffer
, "\0", 1);
644 cp
= xstrdup(buffer_ptr(&buffer
));
645 buffer_free(&buffer
);
650 channel_send_open(int id
)
652 Channel
*c
= channel_lookup(id
);
655 logit("channel_send_open: %d: bad id", id
);
658 debug2("channel %d: send open", id
);
659 packet_start(SSH2_MSG_CHANNEL_OPEN
);
660 packet_put_cstring(c
->ctype
);
661 packet_put_int(c
->self
);
662 packet_put_int(c
->local_window
);
663 packet_put_int(c
->local_maxpacket
);
668 channel_request_start(int id
, char *service
, int wantconfirm
)
670 Channel
*c
= channel_lookup(id
);
673 logit("channel_request_start: %d: unknown channel id", id
);
676 debug2("channel %d: request %s confirm %d", id
, service
, wantconfirm
);
677 packet_start(SSH2_MSG_CHANNEL_REQUEST
);
678 packet_put_int(c
->remote_id
);
679 packet_put_cstring(service
);
680 packet_put_char(wantconfirm
);
684 channel_register_status_confirm(int id
, channel_confirm_cb
*cb
,
685 channel_confirm_abandon_cb
*abandon_cb
, void *ctx
)
687 struct channel_confirm
*cc
;
690 if ((c
= channel_lookup(id
)) == NULL
)
691 fatal("channel_register_expect: %d: bad id", id
);
693 cc
= xmalloc(sizeof(*cc
));
695 cc
->abandon_cb
= abandon_cb
;
697 TAILQ_INSERT_TAIL(&c
->status_confirms
, cc
, entry
);
701 channel_register_open_confirm(int id
, channel_callback_fn
*fn
, void *ctx
)
703 Channel
*c
= channel_lookup(id
);
706 logit("channel_register_open_confirm: %d: bad id", id
);
709 c
->open_confirm
= fn
;
710 c
->open_confirm_ctx
= ctx
;
714 channel_register_cleanup(int id
, channel_callback_fn
*fn
, int do_close
)
716 Channel
*c
= channel_by_id(id
);
719 logit("channel_register_cleanup: %d: bad id", id
);
723 c
->detach_close
= do_close
;
727 channel_cancel_cleanup(int id
)
729 Channel
*c
= channel_by_id(id
);
732 logit("channel_cancel_cleanup: %d: bad id", id
);
735 c
->detach_user
= NULL
;
740 channel_register_filter(int id
, channel_infilter_fn
*ifn
,
741 channel_outfilter_fn
*ofn
, channel_filter_cleanup_fn
*cfn
, void *ctx
)
743 Channel
*c
= channel_lookup(id
);
746 logit("channel_register_filter: %d: bad id", id
);
749 c
->input_filter
= ifn
;
750 c
->output_filter
= ofn
;
752 c
->filter_cleanup
= cfn
;
756 channel_set_fds(int id
, int rfd
, int wfd
, int efd
,
757 int extusage
, int nonblock
, int is_tty
, u_int window_max
)
759 Channel
*c
= channel_lookup(id
);
761 if (c
== NULL
|| c
->type
!= SSH_CHANNEL_LARVAL
)
762 fatal("channel_activate for non-larval channel %d.", id
);
763 channel_register_fds(c
, rfd
, wfd
, efd
, extusage
, nonblock
, is_tty
);
764 c
->type
= SSH_CHANNEL_OPEN
;
765 c
->local_window
= c
->local_window_max
= window_max
;
766 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
767 packet_put_int(c
->remote_id
);
768 packet_put_int(c
->local_window
);
773 * 'channel_pre*' are called just before select() to add any bits relevant to
774 * channels in the select bitmasks.
777 * 'channel_post*': perform any appropriate operations for channels which
778 * have events pending.
780 typedef void chan_fn(Channel
*c
, fd_set
*readset
, fd_set
*writeset
);
781 chan_fn
*channel_pre
[SSH_CHANNEL_MAX_TYPE
];
782 chan_fn
*channel_post
[SSH_CHANNEL_MAX_TYPE
];
786 channel_pre_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
788 FD_SET(c
->sock
, readset
);
793 channel_pre_connecting(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
795 debug3("channel %d: waiting for connection", c
->self
);
796 FD_SET(c
->sock
, writeset
);
800 channel_pre_open_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
802 if (buffer_len(&c
->input
) < packet_get_maxsize())
803 FD_SET(c
->sock
, readset
);
804 if (buffer_len(&c
->output
) > 0)
805 FD_SET(c
->sock
, writeset
);
808 int channel_tcpwinsz () {
809 u_int32_t tcpwinsz
= 0;
810 socklen_t optsz
= sizeof(tcpwinsz
);
813 /* if we aren't on a socket return 128KB*/
814 if(!packet_connection_is_on_socket())
816 ret
= getsockopt(packet_get_connection_in(),
817 SOL_SOCKET
, SO_RCVBUF
, &tcpwinsz
, &optsz
);
818 /* return no more than 64MB */
819 if ((ret
== 0) && tcpwinsz
> BUFFER_MAX_LEN_HPN
)
820 tcpwinsz
= BUFFER_MAX_LEN_HPN
;
821 debug2("tcpwinsz: %d for connection: %d", tcpwinsz
,
822 packet_get_connection_in());
827 channel_pre_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
829 u_int limit
= compat20
? c
->remote_window
: packet_get_maxsize();
831 /* check buffer limits */
832 if ((!c
->tcpwinsz
) || (c
->dynamic_window
> 0))
833 c
->tcpwinsz
= channel_tcpwinsz();
835 limit
= MIN(limit
, 2 * c
->tcpwinsz
);
837 if (c
->istate
== CHAN_INPUT_OPEN
&&
839 buffer_len(&c
->input
) < limit
&&
840 buffer_check_alloc(&c
->input
, CHAN_RBUF
))
841 FD_SET(c
->rfd
, readset
);
842 if (c
->ostate
== CHAN_OUTPUT_OPEN
||
843 c
->ostate
== CHAN_OUTPUT_WAIT_DRAIN
) {
844 if (buffer_len(&c
->output
) > 0) {
845 FD_SET(c
->wfd
, writeset
);
846 } else if (c
->ostate
== CHAN_OUTPUT_WAIT_DRAIN
) {
847 if (CHANNEL_EFD_OUTPUT_ACTIVE(c
))
848 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
849 c
->self
, c
->efd
, buffer_len(&c
->extended
));
854 /** XXX check close conditions, too */
855 if (compat20
&& c
->efd
!= -1 &&
856 !(c
->istate
== CHAN_INPUT_CLOSED
&& c
->ostate
== CHAN_OUTPUT_CLOSED
)) {
857 if (c
->extended_usage
== CHAN_EXTENDED_WRITE
&&
858 buffer_len(&c
->extended
) > 0)
859 FD_SET(c
->efd
, writeset
);
860 else if (!(c
->flags
& CHAN_EOF_SENT
) &&
861 c
->extended_usage
== CHAN_EXTENDED_READ
&&
862 buffer_len(&c
->extended
) < c
->remote_window
)
863 FD_SET(c
->efd
, readset
);
865 /* XXX: What about efd? races? */
866 if (compat20
&& c
->ctl_fd
!= -1 &&
867 c
->istate
== CHAN_INPUT_OPEN
&& c
->ostate
== CHAN_OUTPUT_OPEN
)
868 FD_SET(c
->ctl_fd
, readset
);
873 channel_pre_input_draining(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
875 if (buffer_len(&c
->input
) == 0) {
876 packet_start(SSH_MSG_CHANNEL_CLOSE
);
877 packet_put_int(c
->remote_id
);
879 c
->type
= SSH_CHANNEL_CLOSED
;
880 debug2("channel %d: closing after input drain.", c
->self
);
886 channel_pre_output_draining(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
888 if (buffer_len(&c
->output
) == 0)
891 FD_SET(c
->sock
, writeset
);
895 * This is a special state for X11 authentication spoofing. An opened X11
896 * connection (when authentication spoofing is being done) remains in this
897 * state until the first packet has been completely read. The authentication
898 * data in that packet is then substituted by the real data if it matches the
899 * fake data, and the channel is put into normal mode.
900 * XXX All this happens at the client side.
901 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
904 x11_open_helper(Buffer
*b
)
907 u_int proto_len
, data_len
;
909 /* Check if the fixed size part of the packet is in buffer. */
910 if (buffer_len(b
) < 12)
913 /* Parse the lengths of variable-length fields. */
915 if (ucp
[0] == 0x42) { /* Byte order MSB first. */
916 proto_len
= 256 * ucp
[6] + ucp
[7];
917 data_len
= 256 * ucp
[8] + ucp
[9];
918 } else if (ucp
[0] == 0x6c) { /* Byte order LSB first. */
919 proto_len
= ucp
[6] + 256 * ucp
[7];
920 data_len
= ucp
[8] + 256 * ucp
[9];
922 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
927 /* Check if the whole packet is in buffer. */
929 12 + ((proto_len
+ 3) & ~3) + ((data_len
+ 3) & ~3))
932 /* Check if authentication protocol matches. */
933 if (proto_len
!= strlen(x11_saved_proto
) ||
934 memcmp(ucp
+ 12, x11_saved_proto
, proto_len
) != 0) {
935 debug2("X11 connection uses different authentication protocol.");
938 /* Check if authentication data matches our fake data. */
939 if (data_len
!= x11_fake_data_len
||
940 memcmp(ucp
+ 12 + ((proto_len
+ 3) & ~3),
941 x11_fake_data
, x11_fake_data_len
) != 0) {
942 debug2("X11 auth data does not match fake data.");
945 /* Check fake data length */
946 if (x11_fake_data_len
!= x11_saved_data_len
) {
947 error("X11 fake_data_len %d != saved_data_len %d",
948 x11_fake_data_len
, x11_saved_data_len
);
952 * Received authentication protocol and data match
953 * our fake data. Substitute the fake data with real
956 memcpy(ucp
+ 12 + ((proto_len
+ 3) & ~3),
957 x11_saved_data
, x11_saved_data_len
);
962 channel_pre_x11_open_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
964 int ret
= x11_open_helper(&c
->output
);
967 /* Start normal processing for the channel. */
968 c
->type
= SSH_CHANNEL_OPEN
;
969 channel_pre_open_13(c
, readset
, writeset
);
970 } else if (ret
== -1) {
972 * We have received an X11 connection that has bad
973 * authentication information.
975 logit("X11 connection rejected because of wrong authentication.");
976 buffer_clear(&c
->input
);
977 buffer_clear(&c
->output
);
978 channel_close_fd(&c
->sock
);
980 c
->type
= SSH_CHANNEL_CLOSED
;
981 packet_start(SSH_MSG_CHANNEL_CLOSE
);
982 packet_put_int(c
->remote_id
);
988 channel_pre_x11_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
990 int ret
= x11_open_helper(&c
->output
);
992 /* c->force_drain = 1; */
995 c
->type
= SSH_CHANNEL_OPEN
;
996 channel_pre_open(c
, readset
, writeset
);
997 } else if (ret
== -1) {
998 logit("X11 connection rejected because of wrong authentication.");
999 debug2("X11 rejected %d i%d/o%d", c
->self
, c
->istate
, c
->ostate
);
1000 chan_read_failed(c
);
1001 buffer_clear(&c
->input
);
1003 buffer_clear(&c
->output
);
1004 /* for proto v1, the peer will send an IEOF */
1006 chan_write_failed(c
);
1008 c
->type
= SSH_CHANNEL_OPEN
;
1009 debug2("X11 closed %d i%d/o%d", c
->self
, c
->istate
, c
->ostate
);
1013 /* try to decode a socks4 header */
1016 channel_decode_socks4(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1019 u_int len
, have
, i
, found
, need
;
1024 u_int16_t dest_port
;
1025 struct in_addr dest_addr
;
1028 debug2("channel %d: decode socks4", c
->self
);
1030 have
= buffer_len(&c
->input
);
1031 len
= sizeof(s4_req
);
1034 p
= buffer_ptr(&c
->input
);
1037 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1038 if (p
[4] == 0 && p
[5] == 0 && p
[6] == 0 && p
[7] != 0) {
1039 debug2("channel %d: socks4a request", c
->self
);
1040 /* ... and needs an extra string (the hostname) */
1043 /* Check for terminating NUL on the string(s) */
1044 for (found
= 0, i
= len
; i
< have
; i
++) {
1051 /* the peer is probably sending garbage */
1052 debug("channel %d: decode socks4: too long",
1059 buffer_get(&c
->input
, (char *)&s4_req
.version
, 1);
1060 buffer_get(&c
->input
, (char *)&s4_req
.command
, 1);
1061 buffer_get(&c
->input
, (char *)&s4_req
.dest_port
, 2);
1062 buffer_get(&c
->input
, (char *)&s4_req
.dest_addr
, 4);
1063 have
= buffer_len(&c
->input
);
1064 p
= buffer_ptr(&c
->input
);
1066 debug2("channel %d: decode socks4: user %s/%d", c
->self
, p
, len
);
1067 len
++; /* trailing '\0' */
1069 fatal("channel %d: decode socks4: len %d > have %d",
1070 c
->self
, len
, have
);
1071 strlcpy(username
, p
, sizeof(username
));
1072 buffer_consume(&c
->input
, len
);
1074 if (c
->path
!= NULL
) {
1078 if (need
== 1) { /* SOCKS4: one string */
1079 host
= inet_ntoa(s4_req
.dest_addr
);
1080 c
->path
= xstrdup(host
);
1081 } else { /* SOCKS4A: two strings */
1082 have
= buffer_len(&c
->input
);
1083 p
= buffer_ptr(&c
->input
);
1085 debug2("channel %d: decode socks4a: host %s/%d",
1087 len
++; /* trailing '\0' */
1089 fatal("channel %d: decode socks4a: len %d > have %d",
1090 c
->self
, len
, have
);
1091 if (len
> NI_MAXHOST
) {
1092 error("channel %d: hostname \"%.100s\" too long",
1096 c
->path
= xstrdup(p
);
1097 buffer_consume(&c
->input
, len
);
1099 c
->host_port
= ntohs(s4_req
.dest_port
);
1101 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1102 c
->self
, c
->path
, c
->host_port
, s4_req
.command
);
1104 if (s4_req
.command
!= 1) {
1105 debug("channel %d: cannot handle: %s cn %d",
1106 c
->self
, need
== 1 ? "SOCKS4" : "SOCKS4A", s4_req
.command
);
1109 s4_rsp
.version
= 0; /* vn: 0 for reply */
1110 s4_rsp
.command
= 90; /* cd: req granted */
1111 s4_rsp
.dest_port
= 0; /* ignored */
1112 s4_rsp
.dest_addr
.s_addr
= INADDR_ANY
; /* ignored */
1113 buffer_append(&c
->output
, &s4_rsp
, sizeof(s4_rsp
));
1117 /* try to decode a socks5 header */
1118 #define SSH_SOCKS5_AUTHDONE 0x1000
1119 #define SSH_SOCKS5_NOAUTH 0x00
1120 #define SSH_SOCKS5_IPV4 0x01
1121 #define SSH_SOCKS5_DOMAIN 0x03
1122 #define SSH_SOCKS5_IPV6 0x04
1123 #define SSH_SOCKS5_CONNECT 0x01
1124 #define SSH_SOCKS5_SUCCESS 0x00
1128 channel_decode_socks5(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1136 u_int16_t dest_port
;
1137 u_char
*p
, dest_addr
[255+1], ntop
[INET6_ADDRSTRLEN
];
1138 u_int have
, need
, i
, found
, nmethods
, addrlen
, af
;
1140 debug2("channel %d: decode socks5", c
->self
);
1141 p
= buffer_ptr(&c
->input
);
1144 have
= buffer_len(&c
->input
);
1145 if (!(c
->flags
& SSH_SOCKS5_AUTHDONE
)) {
1146 /* format: ver | nmethods | methods */
1150 if (have
< nmethods
+ 2)
1152 /* look for method: "NO AUTHENTICATION REQUIRED" */
1153 for (found
= 0, i
= 2; i
< nmethods
+ 2; i
++) {
1154 if (p
[i
] == SSH_SOCKS5_NOAUTH
) {
1160 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1164 buffer_consume(&c
->input
, nmethods
+ 2);
1165 buffer_put_char(&c
->output
, 0x05); /* version */
1166 buffer_put_char(&c
->output
, SSH_SOCKS5_NOAUTH
); /* method */
1167 FD_SET(c
->sock
, writeset
);
1168 c
->flags
|= SSH_SOCKS5_AUTHDONE
;
1169 debug2("channel %d: socks5 auth done", c
->self
);
1170 return 0; /* need more */
1172 debug2("channel %d: socks5 post auth", c
->self
);
1173 if (have
< sizeof(s5_req
)+1)
1174 return 0; /* need more */
1175 memcpy(&s5_req
, p
, sizeof(s5_req
));
1176 if (s5_req
.version
!= 0x05 ||
1177 s5_req
.command
!= SSH_SOCKS5_CONNECT
||
1178 s5_req
.reserved
!= 0x00) {
1179 debug2("channel %d: only socks5 connect supported", c
->self
);
1182 switch (s5_req
.atyp
){
1183 case SSH_SOCKS5_IPV4
:
1187 case SSH_SOCKS5_DOMAIN
:
1188 addrlen
= p
[sizeof(s5_req
)];
1191 case SSH_SOCKS5_IPV6
:
1196 debug2("channel %d: bad socks5 atyp %d", c
->self
, s5_req
.atyp
);
1199 need
= sizeof(s5_req
) + addrlen
+ 2;
1200 if (s5_req
.atyp
== SSH_SOCKS5_DOMAIN
)
1204 buffer_consume(&c
->input
, sizeof(s5_req
));
1205 if (s5_req
.atyp
== SSH_SOCKS5_DOMAIN
)
1206 buffer_consume(&c
->input
, 1); /* host string length */
1207 buffer_get(&c
->input
, (char *)&dest_addr
, addrlen
);
1208 buffer_get(&c
->input
, (char *)&dest_port
, 2);
1209 dest_addr
[addrlen
] = '\0';
1210 if (c
->path
!= NULL
) {
1214 if (s5_req
.atyp
== SSH_SOCKS5_DOMAIN
) {
1215 if (addrlen
>= NI_MAXHOST
) {
1216 error("channel %d: dynamic request: socks5 hostname "
1217 "\"%.100s\" too long", c
->self
, dest_addr
);
1220 c
->path
= xstrdup(dest_addr
);
1222 if (inet_ntop(af
, dest_addr
, ntop
, sizeof(ntop
)) == NULL
)
1224 c
->path
= xstrdup(ntop
);
1226 c
->host_port
= ntohs(dest_port
);
1228 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1229 c
->self
, c
->path
, c
->host_port
, s5_req
.command
);
1231 s5_rsp
.version
= 0x05;
1232 s5_rsp
.command
= SSH_SOCKS5_SUCCESS
;
1233 s5_rsp
.reserved
= 0; /* ignored */
1234 s5_rsp
.atyp
= SSH_SOCKS5_IPV4
;
1235 ((struct in_addr
*)&dest_addr
)->s_addr
= INADDR_ANY
;
1236 dest_port
= 0; /* ignored */
1238 buffer_append(&c
->output
, &s5_rsp
, sizeof(s5_rsp
));
1239 buffer_append(&c
->output
, &dest_addr
, sizeof(struct in_addr
));
1240 buffer_append(&c
->output
, &dest_port
, sizeof(dest_port
));
1244 /* dynamic port forwarding */
1246 channel_pre_dynamic(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1252 have
= buffer_len(&c
->input
);
1254 debug2("channel %d: pre_dynamic: have %d", c
->self
, have
);
1255 /* buffer_dump(&c->input); */
1256 /* check if the fixed size part of the packet is in buffer. */
1259 FD_SET(c
->sock
, readset
);
1262 /* try to guess the protocol */
1263 p
= buffer_ptr(&c
->input
);
1266 ret
= channel_decode_socks4(c
, readset
, writeset
);
1269 ret
= channel_decode_socks5(c
, readset
, writeset
);
1277 } else if (ret
== 0) {
1278 debug2("channel %d: pre_dynamic: need more", c
->self
);
1280 FD_SET(c
->sock
, readset
);
1282 /* switch to the next state */
1283 c
->type
= SSH_CHANNEL_OPENING
;
1284 port_open_helper(c
, "direct-tcpip");
1288 /* This is our fake X11 server socket. */
1291 channel_post_x11_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1294 struct sockaddr_storage addr
;
1297 char buf
[16384], *remote_ipaddr
;
1300 if (FD_ISSET(c
->sock
, readset
)) {
1301 debug("X11 connection requested.");
1302 addrlen
= sizeof(addr
);
1303 newsock
= accept(c
->sock
, (struct sockaddr
*)&addr
, &addrlen
);
1304 if (c
->single_connection
) {
1305 debug2("single_connection: closing X11 listener.");
1306 channel_close_fd(&c
->sock
);
1310 error("accept: %.100s", strerror(errno
));
1313 set_nodelay(newsock
);
1314 remote_ipaddr
= get_peer_ipaddr(newsock
);
1315 remote_port
= get_peer_port(newsock
);
1316 snprintf(buf
, sizeof buf
, "X11 connection from %.200s port %d",
1317 remote_ipaddr
, remote_port
);
1319 nc
= channel_new("accepted x11 socket",
1320 SSH_CHANNEL_OPENING
, newsock
, newsock
, -1,
1321 c
->local_window_max
, c
->local_maxpacket
, 0, buf
, 1);
1323 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1324 packet_put_cstring("x11");
1325 packet_put_int(nc
->self
);
1326 packet_put_int(nc
->local_window_max
);
1327 packet_put_int(nc
->local_maxpacket
);
1328 /* originator ipaddr and port */
1329 packet_put_cstring(remote_ipaddr
);
1330 if (datafellows
& SSH_BUG_X11FWD
) {
1331 debug2("ssh2 x11 bug compat mode");
1333 packet_put_int(remote_port
);
1337 packet_start(SSH_SMSG_X11_OPEN
);
1338 packet_put_int(nc
->self
);
1339 if (packet_get_protocol_flags() &
1340 SSH_PROTOFLAG_HOST_IN_FWD_OPEN
)
1341 packet_put_cstring(buf
);
1344 xfree(remote_ipaddr
);
1349 port_open_helper(Channel
*c
, char *rtype
)
1353 char *remote_ipaddr
= get_peer_ipaddr(c
->sock
);
1354 int remote_port
= get_peer_port(c
->sock
);
1356 direct
= (strcmp(rtype
, "direct-tcpip") == 0);
1358 snprintf(buf
, sizeof buf
,
1359 "%s: listening port %d for %.100s port %d, "
1360 "connect from %.200s port %d",
1361 rtype
, c
->listening_port
, c
->path
, c
->host_port
,
1362 remote_ipaddr
, remote_port
);
1364 xfree(c
->remote_name
);
1365 c
->remote_name
= xstrdup(buf
);
1368 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1369 packet_put_cstring(rtype
);
1370 packet_put_int(c
->self
);
1371 packet_put_int(c
->local_window_max
);
1372 packet_put_int(c
->local_maxpacket
);
1374 /* target host, port */
1375 packet_put_cstring(c
->path
);
1376 packet_put_int(c
->host_port
);
1378 /* listen address, port */
1379 packet_put_cstring(c
->path
);
1380 packet_put_int(c
->listening_port
);
1382 /* originator host and port */
1383 packet_put_cstring(remote_ipaddr
);
1384 packet_put_int((u_int
)remote_port
);
1387 packet_start(SSH_MSG_PORT_OPEN
);
1388 packet_put_int(c
->self
);
1389 packet_put_cstring(c
->path
);
1390 packet_put_int(c
->host_port
);
1391 if (packet_get_protocol_flags() &
1392 SSH_PROTOFLAG_HOST_IN_FWD_OPEN
)
1393 packet_put_cstring(c
->remote_name
);
1396 xfree(remote_ipaddr
);
1400 channel_set_reuseaddr(int fd
)
1405 * Set socket options.
1406 * Allow local port reuse in TIME_WAIT.
1408 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) == -1)
1409 error("setsockopt SO_REUSEADDR fd %d: %s", fd
, strerror(errno
));
1413 * This socket is listening for connections to a forwarded TCP/IP port.
1417 channel_post_port_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1420 struct sockaddr_storage addr
;
1421 int newsock
, nextstate
;
1425 if (FD_ISSET(c
->sock
, readset
)) {
1426 debug("Connection to port %d forwarding "
1427 "to %.100s port %d requested.",
1428 c
->listening_port
, c
->path
, c
->host_port
);
1430 if (c
->type
== SSH_CHANNEL_RPORT_LISTENER
) {
1431 nextstate
= SSH_CHANNEL_OPENING
;
1432 rtype
= "forwarded-tcpip";
1434 if (c
->host_port
== 0) {
1435 nextstate
= SSH_CHANNEL_DYNAMIC
;
1436 rtype
= "dynamic-tcpip";
1438 nextstate
= SSH_CHANNEL_OPENING
;
1439 rtype
= "direct-tcpip";
1443 addrlen
= sizeof(addr
);
1444 newsock
= accept(c
->sock
, (struct sockaddr
*)&addr
, &addrlen
);
1446 error("accept: %.100s", strerror(errno
));
1449 set_nodelay(newsock
);
1450 nc
= channel_new(rtype
, nextstate
, newsock
, newsock
, -1,
1451 c
->local_window_max
, c
->local_maxpacket
, 0, rtype
, 1);
1452 nc
->listening_port
= c
->listening_port
;
1453 nc
->host_port
= c
->host_port
;
1454 if (c
->path
!= NULL
)
1455 nc
->path
= xstrdup(c
->path
);
1457 if (nextstate
== SSH_CHANNEL_DYNAMIC
) {
1459 * do not call the channel_post handler until
1460 * this flag has been reset by a pre-handler.
1461 * otherwise the FD_ISSET calls might overflow
1465 port_open_helper(nc
, rtype
);
1471 * This is the authentication agent socket listening for connections from
1476 channel_post_auth_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1480 struct sockaddr_storage addr
;
1483 if (FD_ISSET(c
->sock
, readset
)) {
1484 addrlen
= sizeof(addr
);
1485 newsock
= accept(c
->sock
, (struct sockaddr
*)&addr
, &addrlen
);
1487 error("accept from auth socket: %.100s", strerror(errno
));
1490 nc
= channel_new("accepted auth socket",
1491 SSH_CHANNEL_OPENING
, newsock
, newsock
, -1,
1492 c
->local_window_max
, c
->local_maxpacket
,
1493 0, "accepted auth socket", 1);
1495 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1496 packet_put_cstring("auth-agent@openssh.com");
1497 packet_put_int(nc
->self
);
1498 packet_put_int(c
->local_window_max
);
1499 packet_put_int(c
->local_maxpacket
);
1501 packet_start(SSH_SMSG_AGENT_OPEN
);
1502 packet_put_int(nc
->self
);
1510 channel_post_connecting(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1513 socklen_t sz
= sizeof(err
);
1515 if (FD_ISSET(c
->sock
, writeset
)) {
1516 if (getsockopt(c
->sock
, SOL_SOCKET
, SO_ERROR
, &err
, &sz
) < 0) {
1518 error("getsockopt SO_ERROR failed");
1521 debug("channel %d: connected to %s port %d",
1522 c
->self
, c
->connect_ctx
.host
, c
->connect_ctx
.port
);
1523 channel_connect_ctx_free(&c
->connect_ctx
);
1524 c
->type
= SSH_CHANNEL_OPEN
;
1526 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
1527 packet_put_int(c
->remote_id
);
1528 packet_put_int(c
->self
);
1529 packet_put_int(c
->local_window
);
1530 packet_put_int(c
->local_maxpacket
);
1532 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
1533 packet_put_int(c
->remote_id
);
1534 packet_put_int(c
->self
);
1537 debug("channel %d: connection failed: %s",
1538 c
->self
, strerror(err
));
1539 /* Try next address, if any */
1540 if ((sock
= connect_next(&c
->connect_ctx
)) > 0) {
1542 c
->sock
= c
->rfd
= c
->wfd
= sock
;
1543 channel_max_fd
= channel_find_maxfd();
1546 /* Exhausted all addresses */
1547 error("connect_to %.100s port %d: failed.",
1548 c
->connect_ctx
.host
, c
->connect_ctx
.port
);
1549 channel_connect_ctx_free(&c
->connect_ctx
);
1551 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
1552 packet_put_int(c
->remote_id
);
1553 packet_put_int(SSH2_OPEN_CONNECT_FAILED
);
1554 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
1555 packet_put_cstring(strerror(err
));
1556 packet_put_cstring("");
1559 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
1560 packet_put_int(c
->remote_id
);
1570 channel_handle_rfd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1572 char buf
[CHAN_RBUF
];
1575 force
= c
->isatty
&& c
->detach_close
&& c
->istate
!= CHAN_INPUT_CLOSED
;
1576 if (c
->rfd
!= -1 && (force
|| FD_ISSET(c
->rfd
, readset
))) {
1578 len
= read(c
->rfd
, buf
, sizeof(buf
));
1579 if (len
< 0 && (errno
== EINTR
||
1580 ((errno
== EAGAIN
|| errno
== EWOULDBLOCK
) && !force
)))
1582 #ifndef PTY_ZEROREAD
1585 if ((!c
->isatty
&& len
<= 0) ||
1586 (c
->isatty
&& (len
< 0 || (len
== 0 && errno
!= 0)))) {
1588 debug2("channel %d: read<=0 rfd %d len %d",
1589 c
->self
, c
->rfd
, len
);
1590 if (c
->type
!= SSH_CHANNEL_OPEN
) {
1591 debug2("channel %d: not open", c
->self
);
1594 } else if (compat13
) {
1595 buffer_clear(&c
->output
);
1596 c
->type
= SSH_CHANNEL_INPUT_DRAINING
;
1597 debug2("channel %d: input draining.", c
->self
);
1599 chan_read_failed(c
);
1603 if (c
->input_filter
!= NULL
) {
1604 if (c
->input_filter(c
, buf
, len
) == -1) {
1605 debug2("channel %d: filter stops", c
->self
);
1606 chan_read_failed(c
);
1608 } else if (c
->datagram
) {
1609 buffer_put_string(&c
->input
, buf
, len
);
1611 buffer_append(&c
->input
, buf
, len
);
1619 channel_handle_wfd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1622 u_char
*data
= NULL
, *buf
;
1626 /* Send buffered output data to the socket. */
1628 FD_ISSET(c
->wfd
, writeset
) &&
1629 buffer_len(&c
->output
) > 0) {
1630 if (c
->output_filter
!= NULL
) {
1631 if ((buf
= c
->output_filter(c
, &data
, &dlen
)) == NULL
) {
1632 debug2("channel %d: filter stops", c
->self
);
1633 if (c
->type
!= SSH_CHANNEL_OPEN
)
1636 chan_write_failed(c
);
1639 } else if (c
->datagram
) {
1640 buf
= data
= buffer_get_string(&c
->output
, &dlen
);
1642 buf
= data
= buffer_ptr(&c
->output
);
1643 dlen
= buffer_len(&c
->output
);
1647 /* ignore truncated writes, datagrams might get lost */
1648 c
->local_consumed
+= dlen
+ 4;
1649 len
= write(c
->wfd
, buf
, dlen
);
1651 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
||
1652 errno
== EWOULDBLOCK
))
1655 if (c
->type
!= SSH_CHANNEL_OPEN
)
1658 chan_write_failed(c
);
1664 /* XXX: Later AIX versions can't push as much data to tty */
1665 if (compat20
&& c
->wfd_isatty
)
1666 dlen
= MIN(dlen
, 8*1024);
1669 len
= write(c
->wfd
, buf
, dlen
);
1671 (errno
== EINTR
|| errno
== EAGAIN
|| errno
== EWOULDBLOCK
))
1674 if (c
->type
!= SSH_CHANNEL_OPEN
) {
1675 debug2("channel %d: not open", c
->self
);
1678 } else if (compat13
) {
1679 buffer_clear(&c
->output
);
1680 debug2("channel %d: input draining.", c
->self
);
1681 c
->type
= SSH_CHANNEL_INPUT_DRAINING
;
1683 chan_write_failed(c
);
1687 #ifndef BROKEN_TCGETATTR_ICANON
1688 if (compat20
&& c
->isatty
&& dlen
>= 1 && buf
[0] != '\r') {
1689 if (tcgetattr(c
->wfd
, &tio
) == 0 &&
1690 !(tio
.c_lflag
& ECHO
) && (tio
.c_lflag
& ICANON
)) {
1692 * Simulate echo to reduce the impact of
1693 * traffic analysis. We need to match the
1694 * size of a SSH2_MSG_CHANNEL_DATA message
1695 * (4 byte channel id + buf)
1697 packet_send_ignore(4 + len
);
1702 buffer_consume(&c
->output
, len
);
1703 if (compat20
&& len
> 0) {
1704 c
->local_consumed
+= len
;
1711 channel_handle_efd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1713 char buf
[CHAN_RBUF
];
1716 /** XXX handle drain efd, too */
1718 if (c
->extended_usage
== CHAN_EXTENDED_WRITE
&&
1719 FD_ISSET(c
->efd
, writeset
) &&
1720 buffer_len(&c
->extended
) > 0) {
1721 len
= write(c
->efd
, buffer_ptr(&c
->extended
),
1722 buffer_len(&c
->extended
));
1723 debug2("channel %d: written %d to efd %d",
1724 c
->self
, len
, c
->efd
);
1725 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
||
1726 errno
== EWOULDBLOCK
))
1729 debug2("channel %d: closing write-efd %d",
1731 channel_close_fd(&c
->efd
);
1733 buffer_consume(&c
->extended
, len
);
1734 c
->local_consumed
+= len
;
1736 } else if (c
->extended_usage
== CHAN_EXTENDED_READ
&&
1737 (c
->detach_close
|| FD_ISSET(c
->efd
, readset
))) {
1738 len
= read(c
->efd
, buf
, sizeof(buf
));
1739 debug2("channel %d: read %d from efd %d",
1740 c
->self
, len
, c
->efd
);
1741 if (len
< 0 && (errno
== EINTR
|| ((errno
== EAGAIN
||
1742 errno
== EWOULDBLOCK
) && !c
->detach_close
)))
1745 debug2("channel %d: closing read-efd %d",
1747 channel_close_fd(&c
->efd
);
1749 buffer_append(&c
->extended
, buf
, len
);
1758 channel_handle_ctl(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1763 /* Monitor control fd to detect if the slave client exits */
1764 if (c
->ctl_fd
!= -1 && FD_ISSET(c
->ctl_fd
, readset
)) {
1765 len
= read(c
->ctl_fd
, buf
, sizeof(buf
));
1767 (errno
== EINTR
|| errno
== EAGAIN
|| errno
== EWOULDBLOCK
))
1770 debug2("channel %d: ctl read<=0", c
->self
);
1771 if (c
->type
!= SSH_CHANNEL_OPEN
) {
1772 debug2("channel %d: not open", c
->self
);
1776 chan_read_failed(c
);
1777 chan_write_failed(c
);
1781 fatal("%s: unexpected data on ctl fd", __func__
);
1787 channel_check_window(Channel
*c
)
1789 if (c
->type
== SSH_CHANNEL_OPEN
&&
1790 !(c
->flags
& (CHAN_CLOSE_SENT
|CHAN_CLOSE_RCVD
)) &&
1791 ((c
->local_window_max
- c
->local_window
>
1792 c
->local_maxpacket
*3) ||
1793 c
->local_window
< c
->local_window_max
/2) &&
1794 c
->local_consumed
> 0) {
1796 /* adjust max window size if we are in a dynamic environment */
1797 if (c
->dynamic_window
&& (c
->tcpwinsz
> c
->local_window_max
)) {
1798 /* grow the window somewhat aggressively to maintain pressure */
1799 addition
= 1.5*(c
->tcpwinsz
- c
->local_window_max
);
1800 c
->local_window_max
+= addition
;
1802 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
1803 packet_put_int(c
->remote_id
);
1804 packet_put_int(c
->local_consumed
+ addition
);
1806 debug2("channel %d: window %d sent adjust %d",
1807 c
->self
, c
->local_window
,
1809 c
->local_window
+= c
->local_consumed
+ addition
;
1810 c
->local_consumed
= 0;
1816 channel_post_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1820 channel_handle_rfd(c
, readset
, writeset
);
1821 channel_handle_wfd(c
, readset
, writeset
);
1824 channel_handle_efd(c
, readset
, writeset
);
1825 channel_handle_ctl(c
, readset
, writeset
);
1826 channel_check_window(c
);
1831 channel_post_output_drain_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1835 /* Send buffered output data to the socket. */
1836 if (FD_ISSET(c
->sock
, writeset
) && buffer_len(&c
->output
) > 0) {
1837 len
= write(c
->sock
, buffer_ptr(&c
->output
),
1838 buffer_len(&c
->output
));
1840 buffer_clear(&c
->output
);
1842 buffer_consume(&c
->output
, len
);
1847 channel_handler_init_20(void)
1849 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open
;
1850 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open
;
1851 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
1852 channel_pre
[SSH_CHANNEL_RPORT_LISTENER
] = &channel_pre_listener
;
1853 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
1854 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
1855 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
1856 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
1858 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
1859 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
1860 channel_post
[SSH_CHANNEL_RPORT_LISTENER
] = &channel_post_port_listener
;
1861 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
1862 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
1863 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
1864 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
1868 channel_handler_init_13(void)
1870 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open_13
;
1871 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open_13
;
1872 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
1873 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
1874 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
1875 channel_pre
[SSH_CHANNEL_INPUT_DRAINING
] = &channel_pre_input_draining
;
1876 channel_pre
[SSH_CHANNEL_OUTPUT_DRAINING
] = &channel_pre_output_draining
;
1877 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
1878 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
1880 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
1881 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
1882 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
1883 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
1884 channel_post
[SSH_CHANNEL_OUTPUT_DRAINING
] = &channel_post_output_drain_13
;
1885 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
1886 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
1890 channel_handler_init_15(void)
1892 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open
;
1893 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open
;
1894 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
1895 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
1896 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
1897 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
1898 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
1900 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
1901 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
1902 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
1903 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
1904 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
1905 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
1909 channel_handler_init(void)
1913 for (i
= 0; i
< SSH_CHANNEL_MAX_TYPE
; i
++) {
1914 channel_pre
[i
] = NULL
;
1915 channel_post
[i
] = NULL
;
1918 channel_handler_init_20();
1920 channel_handler_init_13();
1922 channel_handler_init_15();
1925 /* gc dead channels */
1927 channel_garbage_collect(Channel
*c
)
1931 if (c
->detach_user
!= NULL
) {
1932 if (!chan_is_dead(c
, c
->detach_close
))
1934 debug2("channel %d: gc: notify user", c
->self
);
1935 c
->detach_user(c
->self
, NULL
);
1936 /* if we still have a callback */
1937 if (c
->detach_user
!= NULL
)
1939 debug2("channel %d: gc: user detached", c
->self
);
1941 if (!chan_is_dead(c
, 1))
1943 debug2("channel %d: garbage collecting", c
->self
);
1948 channel_handler(chan_fn
*ftab
[], fd_set
*readset
, fd_set
*writeset
)
1950 static int did_init
= 0;
1955 channel_handler_init();
1958 for (i
= 0; i
< channels_alloc
; i
++) {
1962 if (ftab
[c
->type
] != NULL
)
1963 (*ftab
[c
->type
])(c
, readset
, writeset
);
1964 channel_garbage_collect(c
);
1969 * Allocate/update select bitmasks and add any bits relevant to channels in
1973 channel_prepare_select(fd_set
**readsetp
, fd_set
**writesetp
, int *maxfdp
,
1974 u_int
*nallocp
, int rekeying
)
1976 u_int n
, sz
, nfdset
;
1978 n
= MAX(*maxfdp
, channel_max_fd
);
1980 nfdset
= howmany(n
+1, NFDBITS
);
1981 /* Explicitly test here, because xrealloc isn't always called */
1982 if (nfdset
&& SIZE_T_MAX
/ nfdset
< sizeof(fd_mask
))
1983 fatal("channel_prepare_select: max_fd (%d) is too large", n
);
1984 sz
= nfdset
* sizeof(fd_mask
);
1986 /* perhaps check sz < nalloc/2 and shrink? */
1987 if (*readsetp
== NULL
|| sz
> *nallocp
) {
1988 *readsetp
= xrealloc(*readsetp
, nfdset
, sizeof(fd_mask
));
1989 *writesetp
= xrealloc(*writesetp
, nfdset
, sizeof(fd_mask
));
1993 memset(*readsetp
, 0, sz
);
1994 memset(*writesetp
, 0, sz
);
1997 channel_handler(channel_pre
, *readsetp
, *writesetp
);
2001 * After select, perform any appropriate operations for channels which have
2005 channel_after_select(fd_set
*readset
, fd_set
*writeset
)
2007 channel_handler(channel_post
, readset
, writeset
);
2011 /* If there is data to send to the connection, enqueue some of it now. */
2013 channel_output_poll(void)
2017 int packet_length
= 0;
2019 for (i
= 0; i
< channels_alloc
; i
++) {
2025 * We are only interested in channels that can have buffered
2029 if (c
->type
!= SSH_CHANNEL_OPEN
&&
2030 c
->type
!= SSH_CHANNEL_INPUT_DRAINING
)
2033 if (c
->type
!= SSH_CHANNEL_OPEN
)
2037 (c
->flags
& (CHAN_CLOSE_SENT
|CHAN_CLOSE_RCVD
))) {
2038 /* XXX is this true? */
2039 debug3("channel %d: will not send data after close", c
->self
);
2043 /* Get the amount of buffered data for this channel. */
2044 if ((c
->istate
== CHAN_INPUT_OPEN
||
2045 c
->istate
== CHAN_INPUT_WAIT_DRAIN
) &&
2046 (len
= buffer_len(&c
->input
)) > 0) {
2052 data
= buffer_get_string(&c
->input
,
2054 packet_start(SSH2_MSG_CHANNEL_DATA
);
2055 packet_put_int(c
->remote_id
);
2056 packet_put_string(data
, dlen
);
2057 packet_length
= packet_send();
2058 c
->remote_window
-= dlen
+ 4;
2064 * Send some data for the other side over the secure
2068 if (len
> c
->remote_window
)
2069 len
= c
->remote_window
;
2070 if (len
> c
->remote_maxpacket
)
2071 len
= c
->remote_maxpacket
;
2073 if (packet_is_interactive()) {
2077 /* Keep the packets at reasonable size. */
2078 if (len
> packet_get_maxsize()/2)
2079 len
= packet_get_maxsize()/2;
2083 packet_start(compat20
?
2084 SSH2_MSG_CHANNEL_DATA
: SSH_MSG_CHANNEL_DATA
);
2085 packet_put_int(c
->remote_id
);
2086 packet_put_string(buffer_ptr(&c
->input
), len
);
2087 packet_length
= packet_send();
2088 buffer_consume(&c
->input
, len
);
2089 c
->remote_window
-= len
;
2091 } else if (c
->istate
== CHAN_INPUT_WAIT_DRAIN
) {
2093 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2095 * input-buffer is empty and read-socket shutdown:
2096 * tell peer, that we will not send more data: send IEOF.
2097 * hack for extended data: delay EOF if EFD still in use.
2099 if (CHANNEL_EFD_INPUT_ACTIVE(c
))
2100 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2101 c
->self
, c
->efd
, buffer_len(&c
->extended
));
2105 /* Send extended data, i.e. stderr */
2107 !(c
->flags
& CHAN_EOF_SENT
) &&
2108 c
->remote_window
> 0 &&
2109 (len
= buffer_len(&c
->extended
)) > 0 &&
2110 c
->extended_usage
== CHAN_EXTENDED_READ
) {
2111 debug2("channel %d: rwin %u elen %u euse %d",
2112 c
->self
, c
->remote_window
, buffer_len(&c
->extended
),
2114 if (len
> c
->remote_window
)
2115 len
= c
->remote_window
;
2116 if (len
> c
->remote_maxpacket
)
2117 len
= c
->remote_maxpacket
;
2118 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
2119 packet_put_int(c
->remote_id
);
2120 packet_put_int(SSH2_EXTENDED_DATA_STDERR
);
2121 packet_put_string(buffer_ptr(&c
->extended
), len
);
2122 packet_length
= packet_send();
2123 buffer_consume(&c
->extended
, len
);
2124 c
->remote_window
-= len
;
2125 debug2("channel %d: sent ext data %d", c
->self
, len
);
2128 return (packet_length
);
2132 /* -- protocol input */
2136 channel_input_data(int type
, u_int32_t seq
, void *ctxt
)
2143 /* Get the channel number and verify it. */
2144 id
= packet_get_int();
2145 c
= channel_lookup(id
);
2147 packet_disconnect("Received data for nonexistent channel %d.", id
);
2149 /* Ignore any data for non-open channels (might happen on close) */
2150 if (c
->type
!= SSH_CHANNEL_OPEN
&&
2151 c
->type
!= SSH_CHANNEL_X11_OPEN
)
2155 data
= packet_get_string_ptr(&data_len
);
2158 * Ignore data for protocol > 1.3 if output end is no longer open.
2159 * For protocol 2 the sending side is reducing its window as it sends
2160 * data, so we must 'fake' consumption of the data in order to ensure
2161 * that window updates are sent back. Otherwise the connection might
2164 if (!compat13
&& c
->ostate
!= CHAN_OUTPUT_OPEN
) {
2166 c
->local_window
-= data_len
;
2167 c
->local_consumed
+= data_len
;
2173 if (data_len
> c
->local_maxpacket
) {
2174 logit("channel %d: rcvd big packet %d, maxpack %d",
2175 c
->self
, data_len
, c
->local_maxpacket
);
2177 if (data_len
> c
->local_window
) {
2178 logit("channel %d: rcvd too much data %d, win %d",
2179 c
->self
, data_len
, c
->local_window
);
2182 c
->local_window
-= data_len
;
2185 buffer_put_string(&c
->output
, data
, data_len
);
2187 buffer_append(&c
->output
, data
, data_len
);
2193 channel_input_extended_data(int type
, u_int32_t seq
, void *ctxt
)
2197 u_int data_len
, tcode
;
2200 /* Get the channel number and verify it. */
2201 id
= packet_get_int();
2202 c
= channel_lookup(id
);
2205 packet_disconnect("Received extended_data for bad channel %d.", id
);
2206 if (c
->type
!= SSH_CHANNEL_OPEN
) {
2207 logit("channel %d: ext data for non open", id
);
2210 if (c
->flags
& CHAN_EOF_RCVD
) {
2211 if (datafellows
& SSH_BUG_EXTEOF
)
2212 debug("channel %d: accepting ext data after eof", id
);
2214 packet_disconnect("Received extended_data after EOF "
2215 "on channel %d.", id
);
2217 tcode
= packet_get_int();
2219 c
->extended_usage
!= CHAN_EXTENDED_WRITE
||
2220 tcode
!= SSH2_EXTENDED_DATA_STDERR
) {
2221 logit("channel %d: bad ext data", c
->self
);
2224 data
= packet_get_string(&data_len
);
2226 if (data_len
> c
->local_window
) {
2227 logit("channel %d: rcvd too much extended_data %d, win %d",
2228 c
->self
, data_len
, c
->local_window
);
2232 debug2("channel %d: rcvd ext data %d", c
->self
, data_len
);
2233 c
->local_window
-= data_len
;
2234 buffer_append(&c
->extended
, data
, data_len
);
2240 channel_input_ieof(int type
, u_int32_t seq
, void *ctxt
)
2245 id
= packet_get_int();
2247 c
= channel_lookup(id
);
2249 packet_disconnect("Received ieof for nonexistent channel %d.", id
);
2252 /* XXX force input close */
2253 if (c
->force_drain
&& c
->istate
== CHAN_INPUT_OPEN
) {
2254 debug("channel %d: FORCE input drain", c
->self
);
2255 c
->istate
= CHAN_INPUT_WAIT_DRAIN
;
2256 if (buffer_len(&c
->input
) == 0)
2264 channel_input_close(int type
, u_int32_t seq
, void *ctxt
)
2269 id
= packet_get_int();
2271 c
= channel_lookup(id
);
2273 packet_disconnect("Received close for nonexistent channel %d.", id
);
2276 * Send a confirmation that we have closed the channel and no more
2277 * data is coming for it.
2279 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
);
2280 packet_put_int(c
->remote_id
);
2284 * If the channel is in closed state, we have sent a close request,
2285 * and the other side will eventually respond with a confirmation.
2286 * Thus, we cannot free the channel here, because then there would be
2287 * no-one to receive the confirmation. The channel gets freed when
2288 * the confirmation arrives.
2290 if (c
->type
!= SSH_CHANNEL_CLOSED
) {
2292 * Not a closed channel - mark it as draining, which will
2293 * cause it to be freed later.
2295 buffer_clear(&c
->input
);
2296 c
->type
= SSH_CHANNEL_OUTPUT_DRAINING
;
2300 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2303 channel_input_oclose(int type
, u_int32_t seq
, void *ctxt
)
2305 int id
= packet_get_int();
2306 Channel
*c
= channel_lookup(id
);
2310 packet_disconnect("Received oclose for nonexistent channel %d.", id
);
2311 chan_rcvd_oclose(c
);
2316 channel_input_close_confirmation(int type
, u_int32_t seq
, void *ctxt
)
2318 int id
= packet_get_int();
2319 Channel
*c
= channel_lookup(id
);
2323 packet_disconnect("Received close confirmation for "
2324 "out-of-range channel %d.", id
);
2325 if (c
->type
!= SSH_CHANNEL_CLOSED
)
2326 packet_disconnect("Received close confirmation for "
2327 "non-closed channel %d (type %d).", id
, c
->type
);
2333 channel_input_open_confirmation(int type
, u_int32_t seq
, void *ctxt
)
2338 id
= packet_get_int();
2339 c
= channel_lookup(id
);
2341 if (c
==NULL
|| c
->type
!= SSH_CHANNEL_OPENING
)
2342 packet_disconnect("Received open confirmation for "
2343 "non-opening channel %d.", id
);
2344 remote_id
= packet_get_int();
2345 /* Record the remote channel number and mark that the channel is now open. */
2346 c
->remote_id
= remote_id
;
2347 c
->type
= SSH_CHANNEL_OPEN
;
2350 c
->remote_window
= packet_get_int();
2351 c
->remote_maxpacket
= packet_get_int();
2352 if (c
->open_confirm
) {
2353 debug2("callback start");
2354 c
->open_confirm(c
->self
, c
->open_confirm_ctx
);
2355 debug2("callback done");
2357 debug2("channel %d: open confirm rwindow %u rmax %u", c
->self
,
2358 c
->remote_window
, c
->remote_maxpacket
);
2364 reason2txt(int reason
)
2367 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED
:
2368 return "administratively prohibited";
2369 case SSH2_OPEN_CONNECT_FAILED
:
2370 return "connect failed";
2371 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE
:
2372 return "unknown channel type";
2373 case SSH2_OPEN_RESOURCE_SHORTAGE
:
2374 return "resource shortage";
2376 return "unknown reason";
2381 channel_input_open_failure(int type
, u_int32_t seq
, void *ctxt
)
2384 char *msg
= NULL
, *lang
= NULL
;
2387 id
= packet_get_int();
2388 c
= channel_lookup(id
);
2390 if (c
==NULL
|| c
->type
!= SSH_CHANNEL_OPENING
)
2391 packet_disconnect("Received open failure for "
2392 "non-opening channel %d.", id
);
2394 reason
= packet_get_int();
2395 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
2396 msg
= packet_get_string(NULL
);
2397 lang
= packet_get_string(NULL
);
2399 logit("channel %d: open failed: %s%s%s", id
,
2400 reason2txt(reason
), msg
? ": ": "", msg
? msg
: "");
2407 /* Schedule the channel for cleanup/deletion. */
2413 channel_input_window_adjust(int type
, u_int32_t seq
, void *ctxt
)
2422 /* Get the channel number and verify it. */
2423 id
= packet_get_int();
2424 c
= channel_lookup(id
);
2427 logit("Received window adjust for non-open channel %d.", id
);
2430 adjust
= packet_get_int();
2432 debug2("channel %d: rcvd adjust %u", id
, adjust
);
2433 c
->remote_window
+= adjust
;
2438 channel_input_port_open(int type
, u_int32_t seq
, void *ctxt
)
2442 char *host
, *originator_string
;
2445 remote_id
= packet_get_int();
2446 host
= packet_get_string(NULL
);
2447 host_port
= packet_get_int();
2449 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN
) {
2450 originator_string
= packet_get_string(NULL
);
2452 originator_string
= xstrdup("unknown (remote did not supply name)");
2455 c
= channel_connect_to(host
, host_port
,
2456 "connected socket", originator_string
);
2457 xfree(originator_string
);
2460 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
2461 packet_put_int(remote_id
);
2464 c
->remote_id
= remote_id
;
2469 channel_input_status_confirm(int type
, u_int32_t seq
, void *ctxt
)
2472 struct channel_confirm
*cc
;
2475 /* Reset keepalive timeout */
2476 packet_set_alive_timeouts(0);
2478 id
= packet_get_int();
2481 debug2("channel_input_status_confirm: type %d id %d", type
, id
);
2483 if ((c
= channel_lookup(id
)) == NULL
) {
2484 logit("channel_input_status_confirm: %d: unknown", id
);
2488 if ((cc
= TAILQ_FIRST(&c
->status_confirms
)) == NULL
)
2490 cc
->cb(type
, c
, cc
->ctx
);
2491 TAILQ_REMOVE(&c
->status_confirms
, cc
, entry
);
2492 bzero(cc
, sizeof(*cc
));
2496 /* -- tcp forwarding */
2499 channel_set_af(int af
)
2506 channel_set_hpn(int external_hpn_disabled
, int external_hpn_buffer_size
)
2508 hpn_disabled
= external_hpn_disabled
;
2509 hpn_buffer_size
= external_hpn_buffer_size
;
2510 debug("HPN Disabled: %d, HPN Buffer Size: %d", hpn_disabled
, hpn_buffer_size
);
2514 channel_setup_fwd_listener(int type
, const char *listen_addr
,
2515 u_short listen_port
, int *allocated_listen_port
,
2516 const char *host_to_connect
, u_short port_to_connect
, int gateway_ports
)
2519 int sock
, r
, success
= 0, wildcard
= 0, is_client
;
2520 struct addrinfo hints
, *ai
, *aitop
;
2521 const char *host
, *addr
;
2522 char ntop
[NI_MAXHOST
], strport
[NI_MAXSERV
];
2525 host
= (type
== SSH_CHANNEL_RPORT_LISTENER
) ?
2526 listen_addr
: host_to_connect
;
2527 is_client
= (type
== SSH_CHANNEL_PORT_LISTENER
);
2530 error("No forward host name.");
2533 if (strlen(host
) >= NI_MAXHOST
) {
2534 error("Forward host name too long.");
2539 * Determine whether or not a port forward listens to loopback,
2540 * specified address or wildcard. On the client, a specified bind
2541 * address will always override gateway_ports. On the server, a
2542 * gateway_ports of 1 (``yes'') will override the client's
2543 * specification and force a wildcard bind, whereas a value of 2
2544 * (``clientspecified'') will bind to whatever address the client
2547 * Special-case listen_addrs are:
2549 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2550 * "" (empty string), "*" -> wildcard v4/v6
2551 * "localhost" -> loopback v4/v6
2554 if (listen_addr
== NULL
) {
2555 /* No address specified: default to gateway_ports setting */
2558 } else if (gateway_ports
|| is_client
) {
2559 if (((datafellows
& SSH_OLD_FORWARD_ADDR
) &&
2560 strcmp(listen_addr
, "0.0.0.0") == 0 && is_client
== 0) ||
2561 *listen_addr
== '\0' || strcmp(listen_addr
, "*") == 0 ||
2562 (!is_client
&& gateway_ports
== 1))
2564 else if (strcmp(listen_addr
, "localhost") != 0)
2568 debug3("channel_setup_fwd_listener: type %d wildcard %d addr %s",
2569 type
, wildcard
, (addr
== NULL
) ? "NULL" : addr
);
2572 * getaddrinfo returns a loopback address if the hostname is
2573 * set to NULL and hints.ai_flags is not AI_PASSIVE
2575 memset(&hints
, 0, sizeof(hints
));
2576 hints
.ai_family
= IPv4or6
;
2577 hints
.ai_flags
= wildcard
? AI_PASSIVE
: 0;
2578 hints
.ai_socktype
= SOCK_STREAM
;
2579 snprintf(strport
, sizeof strport
, "%d", listen_port
);
2580 if ((r
= getaddrinfo(addr
, strport
, &hints
, &aitop
)) != 0) {
2582 /* This really shouldn't happen */
2583 packet_disconnect("getaddrinfo: fatal error: %s",
2584 ssh_gai_strerror(r
));
2586 error("channel_setup_fwd_listener: "
2587 "getaddrinfo(%.64s): %s", addr
,
2588 ssh_gai_strerror(r
));
2592 if (allocated_listen_port
!= NULL
)
2593 *allocated_listen_port
= 0;
2594 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
2595 switch (ai
->ai_family
) {
2597 lport_p
= &((struct sockaddr_in
*)ai
->ai_addr
)->
2601 lport_p
= &((struct sockaddr_in6
*)ai
->ai_addr
)->
2608 * If allocating a port for -R forwards, then use the
2609 * same port for all address families.
2611 if (type
== SSH_CHANNEL_RPORT_LISTENER
&& listen_port
== 0 &&
2612 allocated_listen_port
!= NULL
&& *allocated_listen_port
> 0)
2613 *lport_p
= htons(*allocated_listen_port
);
2615 if (getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, ntop
, sizeof(ntop
),
2616 strport
, sizeof(strport
), NI_NUMERICHOST
|NI_NUMERICSERV
) != 0) {
2617 error("channel_setup_fwd_listener: getnameinfo failed");
2620 /* Create a port to listen for the host. */
2621 sock
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
2623 /* this is no error since kernel may not support ipv6 */
2624 verbose("socket: %.100s", strerror(errno
));
2628 channel_set_reuseaddr(sock
);
2630 debug("Local forwarding listening on %s port %s.",
2633 /* Bind the socket to the address. */
2634 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
2635 /* address can be in use ipv6 address is already bound */
2637 error("bind: %.100s", strerror(errno
));
2639 verbose("bind: %.100s", strerror(errno
));
2644 /* Start listening for connections on the socket. */
2645 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0) {
2646 error("listen: %.100s", strerror(errno
));
2652 * listen_port == 0 requests a dynamically allocated port -
2653 * record what we got.
2655 if (type
== SSH_CHANNEL_RPORT_LISTENER
&& listen_port
== 0 &&
2656 allocated_listen_port
!= NULL
&&
2657 *allocated_listen_port
== 0) {
2658 *allocated_listen_port
= get_sock_port(sock
, 1);
2659 debug("Allocated listen port %d",
2660 *allocated_listen_port
);
2663 /* Allocate a channel number for the socket. */
2664 /* explicitly test for hpn disabled option. if true use smaller window size */
2666 c
= channel_new("port listener", type
, sock
, sock
, -1,
2667 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
2668 0, "port listener", 1);
2670 c
= channel_new("port listener", type
, sock
, sock
, -1,
2671 hpn_buffer_size
, CHAN_TCP_PACKET_DEFAULT
,
2672 0, "port listener", 1);
2673 c
->path
= xstrdup(host
);
2674 c
->host_port
= port_to_connect
;
2675 c
->listening_port
= listen_port
;
2679 error("channel_setup_fwd_listener: cannot listen to port: %d",
2681 freeaddrinfo(aitop
);
2686 channel_cancel_rport_listener(const char *host
, u_short port
)
2691 for (i
= 0; i
< channels_alloc
; i
++) {
2692 Channel
*c
= channels
[i
];
2694 if (c
!= NULL
&& c
->type
== SSH_CHANNEL_RPORT_LISTENER
&&
2695 strcmp(c
->path
, host
) == 0 && c
->listening_port
== port
) {
2696 debug2("%s: close channel %d", __func__
, i
);
2705 /* protocol local port fwd, used by ssh (and sshd in v1) */
2707 channel_setup_local_fwd_listener(const char *listen_host
, u_short listen_port
,
2708 const char *host_to_connect
, u_short port_to_connect
, int gateway_ports
)
2710 return channel_setup_fwd_listener(SSH_CHANNEL_PORT_LISTENER
,
2711 listen_host
, listen_port
, NULL
, host_to_connect
, port_to_connect
,
2715 /* protocol v2 remote port fwd, used by sshd */
2717 channel_setup_remote_fwd_listener(const char *listen_address
,
2718 u_short listen_port
, int *allocated_listen_port
, int gateway_ports
)
2720 return channel_setup_fwd_listener(SSH_CHANNEL_RPORT_LISTENER
,
2721 listen_address
, listen_port
, allocated_listen_port
,
2722 NULL
, 0, gateway_ports
);
2726 * Initiate forwarding of connections to port "port" on remote host through
2727 * the secure channel to host:port from local side.
2731 channel_request_remote_forwarding(const char *listen_host
, u_short listen_port
,
2732 const char *host_to_connect
, u_short port_to_connect
)
2734 int type
, success
= 0;
2736 /* Record locally that connection to this host/port is permitted. */
2737 if (num_permitted_opens
>= SSH_MAX_FORWARDS_PER_DIRECTION
)
2738 fatal("channel_request_remote_forwarding: too many forwards");
2740 /* Send the forward request to the remote side. */
2742 const char *address_to_bind
;
2743 if (listen_host
== NULL
) {
2744 if (datafellows
& SSH_BUG_RFWD_ADDR
)
2745 address_to_bind
= "127.0.0.1";
2747 address_to_bind
= "localhost";
2748 } else if (*listen_host
== '\0' ||
2749 strcmp(listen_host
, "*") == 0) {
2750 if (datafellows
& SSH_BUG_RFWD_ADDR
)
2751 address_to_bind
= "0.0.0.0";
2753 address_to_bind
= "";
2755 address_to_bind
= listen_host
;
2757 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
2758 packet_put_cstring("tcpip-forward");
2759 packet_put_char(1); /* boolean: want reply */
2760 packet_put_cstring(address_to_bind
);
2761 packet_put_int(listen_port
);
2763 packet_write_wait();
2764 /* Assume that server accepts the request */
2767 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST
);
2768 packet_put_int(listen_port
);
2769 packet_put_cstring(host_to_connect
);
2770 packet_put_int(port_to_connect
);
2772 packet_write_wait();
2774 /* Wait for response from the remote side. */
2775 type
= packet_read();
2777 case SSH_SMSG_SUCCESS
:
2780 case SSH_SMSG_FAILURE
:
2783 /* Unknown packet */
2784 packet_disconnect("Protocol error for port forward request:"
2785 "received packet type %d.", type
);
2789 permitted_opens
[num_permitted_opens
].host_to_connect
= xstrdup(host_to_connect
);
2790 permitted_opens
[num_permitted_opens
].port_to_connect
= port_to_connect
;
2791 permitted_opens
[num_permitted_opens
].listen_port
= listen_port
;
2792 num_permitted_opens
++;
2794 return (success
? 0 : -1);
2798 * Request cancellation of remote forwarding of connection host:port from
2802 channel_request_rforward_cancel(const char *host
, u_short port
)
2809 for (i
= 0; i
< num_permitted_opens
; i
++) {
2810 if (permitted_opens
[i
].host_to_connect
!= NULL
&&
2811 permitted_opens
[i
].listen_port
== port
)
2814 if (i
>= num_permitted_opens
) {
2815 debug("%s: requested forward not found", __func__
);
2818 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
2819 packet_put_cstring("cancel-tcpip-forward");
2821 packet_put_cstring(host
== NULL
? "" : host
);
2822 packet_put_int(port
);
2825 permitted_opens
[i
].listen_port
= 0;
2826 permitted_opens
[i
].port_to_connect
= 0;
2827 xfree(permitted_opens
[i
].host_to_connect
);
2828 permitted_opens
[i
].host_to_connect
= NULL
;
2832 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
2833 * listening for the port, and sends back a success reply (or disconnect
2834 * message if there was an error).
2837 channel_input_port_forward_request(int is_root
, int gateway_ports
)
2839 u_short port
, host_port
;
2843 /* Get arguments from the packet. */
2844 port
= packet_get_int();
2845 hostname
= packet_get_string(NULL
);
2846 host_port
= packet_get_int();
2850 * Check that an unprivileged user is not trying to forward a
2853 if (port
< IPPORT_RESERVED
&& !is_root
)
2855 "Requested forwarding of port %d but user is not root.",
2858 packet_disconnect("Dynamic forwarding denied.");
2861 /* Initiate forwarding */
2862 success
= channel_setup_local_fwd_listener(NULL
, port
, hostname
,
2863 host_port
, gateway_ports
);
2865 /* Free the argument string. */
2868 return (success
? 0 : -1);
2872 * Permits opening to any host/port if permitted_opens[] is empty. This is
2873 * usually called by the server, because the user could connect to any port
2874 * anyway, and the server has no way to know but to trust the client anyway.
2877 channel_permit_all_opens(void)
2879 if (num_permitted_opens
== 0)
2880 all_opens_permitted
= 1;
2884 channel_add_permitted_opens(char *host
, int port
)
2886 if (num_permitted_opens
>= SSH_MAX_FORWARDS_PER_DIRECTION
)
2887 fatal("channel_add_permitted_opens: too many forwards");
2888 debug("allow port forwarding to host %s port %d", host
, port
);
2890 permitted_opens
[num_permitted_opens
].host_to_connect
= xstrdup(host
);
2891 permitted_opens
[num_permitted_opens
].port_to_connect
= port
;
2892 num_permitted_opens
++;
2894 all_opens_permitted
= 0;
2898 channel_add_adm_permitted_opens(char *host
, int port
)
2900 if (num_adm_permitted_opens
>= SSH_MAX_FORWARDS_PER_DIRECTION
)
2901 fatal("channel_add_adm_permitted_opens: too many forwards");
2902 debug("config allows port forwarding to host %s port %d", host
, port
);
2904 permitted_adm_opens
[num_adm_permitted_opens
].host_to_connect
2906 permitted_adm_opens
[num_adm_permitted_opens
].port_to_connect
= port
;
2907 return ++num_adm_permitted_opens
;
2911 channel_clear_permitted_opens(void)
2915 for (i
= 0; i
< num_permitted_opens
; i
++)
2916 if (permitted_opens
[i
].host_to_connect
!= NULL
)
2917 xfree(permitted_opens
[i
].host_to_connect
);
2918 num_permitted_opens
= 0;
2922 channel_clear_adm_permitted_opens(void)
2926 for (i
= 0; i
< num_adm_permitted_opens
; i
++)
2927 if (permitted_adm_opens
[i
].host_to_connect
!= NULL
)
2928 xfree(permitted_adm_opens
[i
].host_to_connect
);
2929 num_adm_permitted_opens
= 0;
2933 channel_print_adm_permitted_opens(void)
2937 printf("permitopen");
2938 if (num_adm_permitted_opens
== 0) {
2942 for (i
= 0; i
< num_adm_permitted_opens
; i
++)
2943 if (permitted_adm_opens
[i
].host_to_connect
!= NULL
)
2944 printf(" %s:%d", permitted_adm_opens
[i
].host_to_connect
,
2945 permitted_adm_opens
[i
].port_to_connect
);
2949 /* Try to start non-blocking connect to next host in cctx list */
2951 connect_next(struct channel_connect
*cctx
)
2953 int sock
, saved_errno
;
2954 char ntop
[NI_MAXHOST
], strport
[NI_MAXSERV
];
2956 for (; cctx
->ai
; cctx
->ai
= cctx
->ai
->ai_next
) {
2957 if (cctx
->ai
->ai_family
!= AF_INET
&&
2958 cctx
->ai
->ai_family
!= AF_INET6
)
2960 if (getnameinfo(cctx
->ai
->ai_addr
, cctx
->ai
->ai_addrlen
,
2961 ntop
, sizeof(ntop
), strport
, sizeof(strport
),
2962 NI_NUMERICHOST
|NI_NUMERICSERV
) != 0) {
2963 error("connect_next: getnameinfo failed");
2966 if ((sock
= socket(cctx
->ai
->ai_family
, cctx
->ai
->ai_socktype
,
2967 cctx
->ai
->ai_protocol
)) == -1) {
2968 if (cctx
->ai
->ai_next
== NULL
)
2969 error("socket: %.100s", strerror(errno
));
2971 verbose("socket: %.100s", strerror(errno
));
2974 if (set_nonblock(sock
) == -1)
2975 fatal("%s: set_nonblock(%d)", __func__
, sock
);
2976 if (connect(sock
, cctx
->ai
->ai_addr
,
2977 cctx
->ai
->ai_addrlen
) == -1 && errno
!= EINPROGRESS
) {
2978 debug("connect_next: host %.100s ([%.100s]:%s): "
2979 "%.100s", cctx
->host
, ntop
, strport
,
2981 saved_errno
= errno
;
2983 errno
= saved_errno
;
2984 continue; /* fail -- try next */
2986 debug("connect_next: host %.100s ([%.100s]:%s) "
2987 "in progress, fd=%d", cctx
->host
, ntop
, strport
, sock
);
2988 cctx
->ai
= cctx
->ai
->ai_next
;
2996 channel_connect_ctx_free(struct channel_connect
*cctx
)
3000 freeaddrinfo(cctx
->aitop
);
3001 bzero(cctx
, sizeof(*cctx
));
3003 cctx
->ai
= cctx
->aitop
= NULL
;
3006 /* Return CONNECTING channel to remote host, port */
3008 connect_to(const char *host
, u_short port
, char *ctype
, char *rname
)
3010 struct addrinfo hints
;
3013 char strport
[NI_MAXSERV
];
3014 struct channel_connect cctx
;
3017 memset(&cctx
, 0, sizeof(cctx
));
3018 memset(&hints
, 0, sizeof(hints
));
3019 hints
.ai_family
= IPv4or6
;
3020 hints
.ai_socktype
= SOCK_STREAM
;
3021 snprintf(strport
, sizeof strport
, "%d", port
);
3022 if ((gaierr
= getaddrinfo(host
, strport
, &hints
, &cctx
.aitop
)) != 0) {
3023 error("connect_to %.100s: unknown host (%s)", host
,
3024 ssh_gai_strerror(gaierr
));
3028 cctx
.host
= xstrdup(host
);
3030 cctx
.ai
= cctx
.aitop
;
3032 if ((sock
= connect_next(&cctx
)) == -1) {
3033 error("connect to %.100s port %d failed: %s",
3034 host
, port
, strerror(errno
));
3035 channel_connect_ctx_free(&cctx
);
3038 c
= channel_new(ctype
, SSH_CHANNEL_CONNECTING
, sock
, sock
, -1,
3039 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
, 0, rname
, 1);
3040 c
->connect_ctx
= cctx
;
3045 channel_connect_by_listen_address(u_short listen_port
, char *ctype
, char *rname
)
3049 for (i
= 0; i
< num_permitted_opens
; i
++) {
3050 if (permitted_opens
[i
].host_to_connect
!= NULL
&&
3051 permitted_opens
[i
].listen_port
== listen_port
) {
3053 permitted_opens
[i
].host_to_connect
,
3054 permitted_opens
[i
].port_to_connect
, ctype
, rname
);
3057 error("WARNING: Server requests forwarding for unknown listen_port %d",
3062 /* Check if connecting to that port is permitted and connect. */
3064 channel_connect_to(const char *host
, u_short port
, char *ctype
, char *rname
)
3066 int i
, permit
, permit_adm
= 1;
3068 permit
= all_opens_permitted
;
3070 for (i
= 0; i
< num_permitted_opens
; i
++)
3071 if (permitted_opens
[i
].host_to_connect
!= NULL
&&
3072 permitted_opens
[i
].port_to_connect
== port
&&
3073 strcmp(permitted_opens
[i
].host_to_connect
, host
) == 0)
3077 if (num_adm_permitted_opens
> 0) {
3079 for (i
= 0; i
< num_adm_permitted_opens
; i
++)
3080 if (permitted_adm_opens
[i
].host_to_connect
!= NULL
&&
3081 permitted_adm_opens
[i
].port_to_connect
== port
&&
3082 strcmp(permitted_adm_opens
[i
].host_to_connect
, host
)
3087 if (!permit
|| !permit_adm
) {
3088 logit("Received request to connect to host %.100s port %d, "
3089 "but the request was denied.", host
, port
);
3092 return connect_to(host
, port
, ctype
, rname
);
3096 channel_send_window_changes(void)
3101 for (i
= 0; i
< channels_alloc
; i
++) {
3102 if (channels
[i
] == NULL
|| !channels
[i
]->client_tty
||
3103 channels
[i
]->type
!= SSH_CHANNEL_OPEN
)
3105 if (ioctl(channels
[i
]->rfd
, TIOCGWINSZ
, &ws
) < 0)
3107 channel_request_start(i
, "window-change", 0);
3108 packet_put_int((u_int
)ws
.ws_col
);
3109 packet_put_int((u_int
)ws
.ws_row
);
3110 packet_put_int((u_int
)ws
.ws_xpixel
);
3111 packet_put_int((u_int
)ws
.ws_ypixel
);
3116 /* -- X11 forwarding */
3119 * Creates an internet domain socket for listening for X11 connections.
3120 * Returns 0 and a suitable display number for the DISPLAY variable
3121 * stored in display_numberp , or -1 if an error occurs.
3124 x11_create_display_inet(int x11_display_offset
, int x11_use_localhost
,
3125 int single_connection
, u_int
*display_numberp
, int **chanids
)
3128 int display_number
, sock
;
3130 struct addrinfo hints
, *ai
, *aitop
;
3131 char strport
[NI_MAXSERV
];
3132 int gaierr
, n
, num_socks
= 0, socks
[NUM_SOCKS
];
3134 if (chanids
== NULL
)
3137 for (display_number
= x11_display_offset
;
3138 display_number
< MAX_DISPLAYS
;
3140 port
= 6000 + display_number
;
3141 memset(&hints
, 0, sizeof(hints
));
3142 hints
.ai_family
= IPv4or6
;
3143 hints
.ai_flags
= x11_use_localhost
? 0: AI_PASSIVE
;
3144 hints
.ai_socktype
= SOCK_STREAM
;
3145 snprintf(strport
, sizeof strport
, "%d", port
);
3146 if ((gaierr
= getaddrinfo(NULL
, strport
, &hints
, &aitop
)) != 0) {
3147 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr
));
3150 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
3151 if (ai
->ai_family
!= AF_INET
&& ai
->ai_family
!= AF_INET6
)
3153 sock
= socket(ai
->ai_family
, ai
->ai_socktype
,
3156 if ((errno
!= EINVAL
) && (errno
!= EAFNOSUPPORT
)) {
3157 error("socket: %.100s", strerror(errno
));
3158 freeaddrinfo(aitop
);
3161 debug("x11_create_display_inet: Socket family %d not supported",
3167 if (ai
->ai_family
== AF_INET6
) {
3169 if (setsockopt(sock
, IPPROTO_IPV6
, IPV6_V6ONLY
, &on
, sizeof(on
)) < 0)
3170 error("setsockopt IPV6_V6ONLY: %.100s", strerror(errno
));
3173 if (x11_use_localhost
)
3174 channel_set_reuseaddr(sock
);
3175 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
3176 debug2("bind port %d: %.100s", port
, strerror(errno
));
3179 for (n
= 0; n
< num_socks
; n
++) {
3185 socks
[num_socks
++] = sock
;
3186 if (num_socks
== NUM_SOCKS
)
3189 freeaddrinfo(aitop
);
3193 if (display_number
>= MAX_DISPLAYS
) {
3194 error("Failed to allocate internet-domain X11 display socket.");
3197 /* Start listening for connections on the socket. */
3198 for (n
= 0; n
< num_socks
; n
++) {
3200 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0) {
3201 error("listen: %.100s", strerror(errno
));
3207 /* Allocate a channel for each socket. */
3208 *chanids
= xcalloc(num_socks
+ 1, sizeof(**chanids
));
3209 for (n
= 0; n
< num_socks
; n
++) {
3211 /* Is this really necassary? */
3213 nc
= channel_new("x11 listener",
3214 SSH_CHANNEL_X11_LISTENER
, sock
, sock
, -1,
3215 CHAN_X11_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
,
3216 0, "X11 inet listener", 1);
3218 nc
= channel_new("x11 listener",
3219 SSH_CHANNEL_X11_LISTENER
, sock
, sock
, -1,
3220 hpn_buffer_size
, CHAN_X11_PACKET_DEFAULT
,
3221 0, "X11 inet listener", 1);
3222 nc
->single_connection
= single_connection
;
3223 (*chanids
)[n
] = nc
->self
;
3227 /* Return the display number for the DISPLAY environment variable. */
3228 *display_numberp
= display_number
;
3233 connect_local_xsocket_path(const char *pathname
)
3236 struct sockaddr_un addr
;
3238 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
3240 error("socket: %.100s", strerror(errno
));
3241 memset(&addr
, 0, sizeof(addr
));
3242 addr
.sun_family
= AF_UNIX
;
3243 strlcpy(addr
.sun_path
, pathname
, sizeof addr
.sun_path
);
3244 if (connect(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)) == 0)
3247 error("connect %.100s: %.100s", addr
.sun_path
, strerror(errno
));
3252 connect_local_xsocket(u_int dnr
)
3255 snprintf(buf
, sizeof buf
, _PATH_UNIX_X
, dnr
);
3256 return connect_local_xsocket_path(buf
);
3260 x11_connect_display(void)
3262 u_int display_number
;
3263 const char *display
;
3264 char buf
[1024], *cp
;
3265 struct addrinfo hints
, *ai
, *aitop
;
3266 char strport
[NI_MAXSERV
];
3267 int gaierr
, sock
= 0;
3269 /* Try to open a socket for the local X server. */
3270 display
= getenv("DISPLAY");
3272 error("DISPLAY not set.");
3276 * Now we decode the value of the DISPLAY variable and make a
3277 * connection to the real X server.
3280 /* Check if the display is from launchd. */
3282 if (strncmp(display
, "/tmp/launch", 11) == 0) {
3283 sock
= connect_local_xsocket_path(display
);
3287 /* OK, we now have a connection to the display. */
3292 * Check if it is a unix domain socket. Unix domain displays are in
3293 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
3295 if (strncmp(display
, "unix:", 5) == 0 ||
3296 display
[0] == ':') {
3297 /* Connect to the unix domain socket. */
3298 if (sscanf(strrchr(display
, ':') + 1, "%u", &display_number
) != 1) {
3299 error("Could not parse display number from DISPLAY: %.100s",
3303 /* Create a socket. */
3304 sock
= connect_local_xsocket(display_number
);
3308 /* OK, we now have a connection to the display. */
3312 * Connect to an inet socket. The DISPLAY value is supposedly
3313 * hostname:d[.s], where hostname may also be numeric IP address.
3315 strlcpy(buf
, display
, sizeof(buf
));
3316 cp
= strchr(buf
, ':');
3318 error("Could not find ':' in DISPLAY: %.100s", display
);
3322 /* buf now contains the host name. But first we parse the display number. */
3323 if (sscanf(cp
+ 1, "%u", &display_number
) != 1) {
3324 error("Could not parse display number from DISPLAY: %.100s",
3329 /* Look up the host address */
3330 memset(&hints
, 0, sizeof(hints
));
3331 hints
.ai_family
= IPv4or6
;
3332 hints
.ai_socktype
= SOCK_STREAM
;
3333 snprintf(strport
, sizeof strport
, "%u", 6000 + display_number
);
3334 if ((gaierr
= getaddrinfo(buf
, strport
, &hints
, &aitop
)) != 0) {
3335 error("%.100s: unknown host. (%s)", buf
,
3336 ssh_gai_strerror(gaierr
));
3339 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
3340 /* Create a socket. */
3341 sock
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
3343 debug2("socket: %.100s", strerror(errno
));
3346 /* Connect it to the display. */
3347 if (connect(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
3348 debug2("connect %.100s port %u: %.100s", buf
,
3349 6000 + display_number
, strerror(errno
));
3356 freeaddrinfo(aitop
);
3358 error("connect %.100s port %u: %.100s", buf
, 6000 + display_number
,
3367 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
3368 * the remote channel number. We should do whatever we want, and respond
3369 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
3374 x11_input_open(int type
, u_int32_t seq
, void *ctxt
)
3377 int remote_id
, sock
= 0;
3380 debug("Received X11 open request.");
3382 remote_id
= packet_get_int();
3384 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN
) {
3385 remote_host
= packet_get_string(NULL
);
3387 remote_host
= xstrdup("unknown (remote did not supply name)");
3391 /* Obtain a connection to the real X display. */
3392 sock
= x11_connect_display();
3394 /* Allocate a channel for this connection. */
3395 c
= channel_new("connected x11 socket",
3396 SSH_CHANNEL_X11_OPEN
, sock
, sock
, -1, 0, 0, 0,
3398 c
->remote_id
= remote_id
;
3403 /* Send refusal to the remote host. */
3404 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
3405 packet_put_int(remote_id
);
3407 /* Send a confirmation to the remote host. */
3408 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
3409 packet_put_int(remote_id
);
3410 packet_put_int(c
->self
);
3415 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
3418 deny_input_open(int type
, u_int32_t seq
, void *ctxt
)
3420 int rchan
= packet_get_int();
3423 case SSH_SMSG_AGENT_OPEN
:
3424 error("Warning: ssh server tried agent forwarding.");
3426 case SSH_SMSG_X11_OPEN
:
3427 error("Warning: ssh server tried X11 forwarding.");
3430 error("deny_input_open: type %d", type
);
3433 error("Warning: this is probably a break-in attempt by a malicious server.");
3434 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
3435 packet_put_int(rchan
);
3440 * Requests forwarding of X11 connections, generates fake authentication
3441 * data, and enables authentication spoofing.
3442 * This should be called in the client only.
3445 x11_request_forwarding_with_spoofing(int client_session_id
, const char *disp
,
3446 const char *proto
, const char *data
)
3448 u_int data_len
= (u_int
) strlen(data
) / 2;
3455 if (x11_saved_display
== NULL
)
3456 x11_saved_display
= xstrdup(disp
);
3457 else if (strcmp(disp
, x11_saved_display
) != 0) {
3458 error("x11_request_forwarding_with_spoofing: different "
3459 "$DISPLAY already forwarded");
3463 cp
= strchr(disp
, ':');
3465 cp
= strchr(cp
, '.');
3467 screen_number
= (u_int
)strtonum(cp
+ 1, 0, 400, NULL
);
3471 if (x11_saved_proto
== NULL
) {
3472 /* Save protocol name. */
3473 x11_saved_proto
= xstrdup(proto
);
3475 * Extract real authentication data and generate fake data
3476 * of the same length.
3478 x11_saved_data
= xmalloc(data_len
);
3479 x11_fake_data
= xmalloc(data_len
);
3480 for (i
= 0; i
< data_len
; i
++) {
3481 if (sscanf(data
+ 2 * i
, "%2x", &value
) != 1)
3482 fatal("x11_request_forwarding: bad "
3483 "authentication data: %.100s", data
);
3486 x11_saved_data
[i
] = value
;
3487 x11_fake_data
[i
] = rnd
& 0xff;
3490 x11_saved_data_len
= data_len
;
3491 x11_fake_data_len
= data_len
;
3494 /* Convert the fake data into hex. */
3495 new_data
= tohex(x11_fake_data
, data_len
);
3497 /* Send the request packet. */
3499 channel_request_start(client_session_id
, "x11-req", 0);
3500 packet_put_char(0); /* XXX bool single connection */
3502 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING
);
3504 packet_put_cstring(proto
);
3505 packet_put_cstring(new_data
);
3506 packet_put_int(screen_number
);
3508 packet_write_wait();
3513 /* -- agent forwarding */
3515 /* Sends a message to the server to request authentication fd forwarding. */
3518 auth_request_forwarding(void)
3520 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING
);
3522 packet_write_wait();