1 /* $OpenBSD: channels.c,v 1.336 2014/07/15 15:54:14 millert 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>
46 #include <sys/ioctl.h>
48 #include <sys/socket.h>
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
66 #include "openbsd-compat/sys-queue.h"
80 #include "pathnames.h"
85 * Pointer to an array containing all allocated channels. The array is
86 * dynamically extended as needed.
88 static Channel
**channels
= NULL
;
91 * Size of the channel array. All slots of the array must always be
92 * initialized (at least the type field); unused slots set to NULL
94 static u_int channels_alloc
= 0;
97 * Maximum file descriptor value used in any of the channels. This is
98 * updated in channel_new.
100 static int channel_max_fd
= 0;
103 /* -- tcp forwarding */
106 * Data structure for storing which hosts are permitted for forward requests.
107 * The local sides of any remote forwards are stored in this array to prevent
108 * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
109 * network (which might be behind a firewall).
111 /* XXX: streamlocal wants a path instead of host:port */
112 /* Overload host_to_connect; we could just make this match Forward */
113 /* XXX - can we use listen_host instead of listen_path? */
115 char *host_to_connect
; /* Connect to 'host'. */
116 int port_to_connect
; /* Connect to 'port'. */
117 char *listen_host
; /* Remote side should listen address. */
118 char *listen_path
; /* Remote side should listen path. */
119 int listen_port
; /* Remote side should listen port. */
122 /* List of all permitted host/port pairs to connect by the user. */
123 static ForwardPermission
*permitted_opens
= NULL
;
125 /* List of all permitted host/port pairs to connect by the admin. */
126 static ForwardPermission
*permitted_adm_opens
= NULL
;
128 /* Number of permitted host/port pairs in the array permitted by the user. */
129 static int num_permitted_opens
= 0;
131 /* Number of permitted host/port pair in the array permitted by the admin. */
132 static int num_adm_permitted_opens
= 0;
134 /* special-case port number meaning allow any port */
135 #define FWD_PERMIT_ANY_PORT 0
138 * If this is true, all opens are permitted. This is the case on the server
139 * on which we have to trust the client anyway, and the user could do
140 * anything after logging in anyway.
142 static int all_opens_permitted
= 0;
145 /* -- X11 forwarding */
147 /* Maximum number of fake X11 displays to try. */
148 #define MAX_DISPLAYS 1000
150 /* Saved X11 local (client) display. */
151 static char *x11_saved_display
= NULL
;
153 /* Saved X11 authentication protocol name. */
154 static char *x11_saved_proto
= NULL
;
156 /* Saved X11 authentication data. This is the real data. */
157 static char *x11_saved_data
= NULL
;
158 static u_int x11_saved_data_len
= 0;
161 * Fake X11 authentication data. This is what the server will be sending us;
162 * we should replace any occurrences of this by the real data.
164 static u_char
*x11_fake_data
= NULL
;
165 static u_int x11_fake_data_len
;
168 /* -- agent forwarding */
172 /* AF_UNSPEC or AF_INET or AF_INET6 */
173 static int IPv4or6
= AF_UNSPEC
;
176 static void port_open_helper(Channel
*c
, char *rtype
);
178 /* non-blocking connect helpers */
179 static int connect_next(struct channel_connect
*);
180 static void channel_connect_ctx_free(struct channel_connect
*);
183 static int hpn_disabled
= 0;
184 static int hpn_buffer_size
= 2 * 1024 * 1024;
186 /* -- channel core */
191 channel_by_id(int id
)
195 if (id
< 0 || (u_int
)id
>= channels_alloc
) {
196 logit("channel_by_id: %d: bad id", id
);
201 logit("channel_by_id: %d: bad id: channel free", id
);
208 * Returns the channel if it is allowed to receive protocol messages.
209 * Private channels, like listening sockets, may not receive messages.
212 channel_lookup(int id
)
216 if ((c
= channel_by_id(id
)) == NULL
)
220 case SSH_CHANNEL_X11_OPEN
:
221 case SSH_CHANNEL_LARVAL
:
222 case SSH_CHANNEL_CONNECTING
:
223 case SSH_CHANNEL_DYNAMIC
:
224 case SSH_CHANNEL_OPENING
:
225 case SSH_CHANNEL_OPEN
:
226 case SSH_CHANNEL_INPUT_DRAINING
:
227 case SSH_CHANNEL_OUTPUT_DRAINING
:
228 case SSH_CHANNEL_ABANDONED
:
231 logit("Non-public channel %d, type %d.", id
, c
->type
);
236 * Register filedescriptors for a channel, used when allocating a channel or
237 * when the channel consumer/producer is ready, e.g. shell exec'd
240 channel_register_fds(Channel
*c
, int rfd
, int wfd
, int efd
,
241 int extusage
, int nonblock
, int is_tty
)
243 /* Update the maximum file descriptor value. */
244 channel_max_fd
= MAX(channel_max_fd
, rfd
);
245 channel_max_fd
= MAX(channel_max_fd
, wfd
);
246 channel_max_fd
= MAX(channel_max_fd
, efd
);
249 fcntl(rfd
, F_SETFD
, FD_CLOEXEC
);
250 if (wfd
!= -1 && wfd
!= rfd
)
251 fcntl(wfd
, F_SETFD
, FD_CLOEXEC
);
252 if (efd
!= -1 && efd
!= rfd
&& efd
!= wfd
)
253 fcntl(efd
, F_SETFD
, FD_CLOEXEC
);
257 c
->sock
= (rfd
== wfd
) ? rfd
: -1;
259 c
->extended_usage
= extusage
;
261 if ((c
->isatty
= is_tty
) != 0)
262 debug2("channel %d: rfd %d isatty", c
->self
, c
->rfd
);
264 /* XXX: Later AIX versions can't push as much data to tty */
265 c
->wfd_isatty
= is_tty
|| isatty(c
->wfd
);
268 /* enable nonblocking mode */
280 * Allocate a new channel object and set its type and socket. This will cause
281 * remote_name to be freed.
284 channel_new(char *ctype
, int type
, int rfd
, int wfd
, int efd
,
285 u_int window
, u_int maxpack
, int extusage
, char *remote_name
, int nonblock
)
291 /* Do initial allocation if this is the first call. */
292 if (channels_alloc
== 0) {
294 channels
= xcalloc(channels_alloc
, sizeof(Channel
*));
295 for (i
= 0; i
< channels_alloc
; i
++)
298 /* Try to find a free slot where to put the new channel. */
299 for (found
= -1, i
= 0; i
< channels_alloc
; i
++)
300 if (channels
[i
] == NULL
) {
301 /* Found a free slot. */
306 /* There are no free slots. Take last+1 slot and expand the array. */
307 found
= channels_alloc
;
308 if (channels_alloc
> 10000)
309 fatal("channel_new: internal error: channels_alloc %d "
310 "too big.", channels_alloc
);
311 channels
= xrealloc(channels
, channels_alloc
+ 10,
313 channels_alloc
+= 10;
314 debug2("channel: expanding %d", channels_alloc
);
315 for (i
= found
; i
< channels_alloc
; i
++)
318 /* Initialize and return new channel. */
319 c
= channels
[found
] = xcalloc(1, sizeof(Channel
));
320 buffer_init(&c
->input
);
321 buffer_init(&c
->output
);
322 buffer_init(&c
->extended
);
324 c
->listening_addr
= NULL
;
325 c
->listening_port
= 0;
326 c
->ostate
= CHAN_OUTPUT_OPEN
;
327 c
->istate
= CHAN_INPUT_OPEN
;
329 channel_register_fds(c
, rfd
, wfd
, efd
, extusage
, nonblock
, 0);
334 c
->local_window
= window
;
335 c
->local_window_max
= window
;
336 c
->local_consumed
= 0;
337 c
->local_maxpacket
= maxpack
;
338 c
->dynamic_window
= 0;
340 c
->remote_name
= xstrdup(remote_name
);
341 c
->remote_window
= 0;
342 c
->remote_maxpacket
= 0;
344 c
->single_connection
= 0;
345 c
->detach_user
= NULL
;
347 c
->open_confirm
= NULL
;
348 c
->open_confirm_ctx
= NULL
;
349 c
->input_filter
= NULL
;
350 c
->output_filter
= NULL
;
351 c
->filter_ctx
= NULL
;
352 c
->filter_cleanup
= NULL
;
357 c
->delayed
= 1; /* prevent call to channel_post handler */
358 TAILQ_INIT(&c
->status_confirms
);
359 debug("channel %d: new [%s]", found
, remote_name
);
364 channel_find_maxfd(void)
370 for (i
= 0; i
< channels_alloc
; i
++) {
373 max
= MAX(max
, c
->rfd
);
374 max
= MAX(max
, c
->wfd
);
375 max
= MAX(max
, c
->efd
);
382 channel_close_fd(int *fdp
)
384 int ret
= 0, fd
= *fdp
;
389 if (fd
== channel_max_fd
)
390 channel_max_fd
= channel_find_maxfd();
395 /* Close all channel fd/socket. */
397 channel_close_fds(Channel
*c
)
399 channel_close_fd(&c
->sock
);
400 channel_close_fd(&c
->rfd
);
401 channel_close_fd(&c
->wfd
);
402 channel_close_fd(&c
->efd
);
405 /* Free the channel and close its fd/socket. */
407 channel_free(Channel
*c
)
411 struct channel_confirm
*cc
;
413 for (n
= 0, i
= 0; i
< channels_alloc
; i
++)
416 debug("channel %d: free: %s, nchannels %u", c
->self
,
417 c
->remote_name
? c
->remote_name
: "???", n
);
419 s
= channel_open_message();
420 debug3("channel %d: status: %s", c
->self
, s
);
424 shutdown(c
->sock
, SHUT_RDWR
);
425 channel_close_fds(c
);
426 buffer_free(&c
->input
);
427 buffer_free(&c
->output
);
428 buffer_free(&c
->extended
);
429 free(c
->remote_name
);
430 c
->remote_name
= NULL
;
433 free(c
->listening_addr
);
434 c
->listening_addr
= NULL
;
435 while ((cc
= TAILQ_FIRST(&c
->status_confirms
)) != NULL
) {
436 if (cc
->abandon_cb
!= NULL
)
437 cc
->abandon_cb(c
, cc
->ctx
);
438 TAILQ_REMOVE(&c
->status_confirms
, cc
, entry
);
439 explicit_bzero(cc
, sizeof(*cc
));
442 if (c
->filter_cleanup
!= NULL
&& c
->filter_ctx
!= NULL
)
443 c
->filter_cleanup(c
->self
, c
->filter_ctx
);
444 channels
[c
->self
] = NULL
;
449 channel_free_all(void)
453 for (i
= 0; i
< channels_alloc
; i
++)
454 if (channels
[i
] != NULL
)
455 channel_free(channels
[i
]);
459 * Closes the sockets/fds of all channels. This is used to close extra file
460 * descriptors after a fork.
463 channel_close_all(void)
467 for (i
= 0; i
< channels_alloc
; i
++)
468 if (channels
[i
] != NULL
)
469 channel_close_fds(channels
[i
]);
473 * Stop listening to channels.
476 channel_stop_listening(void)
481 for (i
= 0; i
< channels_alloc
; i
++) {
485 case SSH_CHANNEL_AUTH_SOCKET
:
486 case SSH_CHANNEL_PORT_LISTENER
:
487 case SSH_CHANNEL_RPORT_LISTENER
:
488 case SSH_CHANNEL_X11_LISTENER
:
489 case SSH_CHANNEL_UNIX_LISTENER
:
490 case SSH_CHANNEL_RUNIX_LISTENER
:
491 channel_close_fd(&c
->sock
);
500 * Returns true if no channel has too much buffered data, and false if one or
501 * more channel is overfull.
504 channel_not_very_much_buffered_data(void)
509 for (i
= 0; i
< channels_alloc
; i
++) {
511 if (c
!= NULL
&& c
->type
== SSH_CHANNEL_OPEN
) {
514 buffer_len(&c
->input
) > packet_get_maxsize()) {
515 debug2("channel %d: big input buffer %d",
516 c
->self
, buffer_len(&c
->input
));
520 if (buffer_len(&c
->output
) > packet_get_maxsize()) {
521 debug2("channel %d: big output buffer %u > %u",
522 c
->self
, buffer_len(&c
->output
),
523 packet_get_maxsize());
531 /* Returns true if any channel is still open. */
533 channel_still_open(void)
538 for (i
= 0; i
< channels_alloc
; i
++) {
543 case SSH_CHANNEL_X11_LISTENER
:
544 case SSH_CHANNEL_PORT_LISTENER
:
545 case SSH_CHANNEL_RPORT_LISTENER
:
546 case SSH_CHANNEL_MUX_LISTENER
:
547 case SSH_CHANNEL_CLOSED
:
548 case SSH_CHANNEL_AUTH_SOCKET
:
549 case SSH_CHANNEL_DYNAMIC
:
550 case SSH_CHANNEL_CONNECTING
:
551 case SSH_CHANNEL_ZOMBIE
:
552 case SSH_CHANNEL_ABANDONED
:
553 case SSH_CHANNEL_UNIX_LISTENER
:
554 case SSH_CHANNEL_RUNIX_LISTENER
:
556 case SSH_CHANNEL_LARVAL
:
558 fatal("cannot happen: SSH_CHANNEL_LARVAL");
560 case SSH_CHANNEL_OPENING
:
561 case SSH_CHANNEL_OPEN
:
562 case SSH_CHANNEL_X11_OPEN
:
563 case SSH_CHANNEL_MUX_CLIENT
:
565 case SSH_CHANNEL_INPUT_DRAINING
:
566 case SSH_CHANNEL_OUTPUT_DRAINING
:
568 fatal("cannot happen: OUT_DRAIN");
571 fatal("channel_still_open: bad channel type %d", c
->type
);
578 /* Returns the id of an open channel suitable for keepaliving */
580 channel_find_open(void)
585 for (i
= 0; i
< channels_alloc
; i
++) {
587 if (c
== NULL
|| c
->remote_id
< 0)
590 case SSH_CHANNEL_CLOSED
:
591 case SSH_CHANNEL_DYNAMIC
:
592 case SSH_CHANNEL_X11_LISTENER
:
593 case SSH_CHANNEL_PORT_LISTENER
:
594 case SSH_CHANNEL_RPORT_LISTENER
:
595 case SSH_CHANNEL_MUX_LISTENER
:
596 case SSH_CHANNEL_MUX_CLIENT
:
597 case SSH_CHANNEL_OPENING
:
598 case SSH_CHANNEL_CONNECTING
:
599 case SSH_CHANNEL_ZOMBIE
:
600 case SSH_CHANNEL_ABANDONED
:
601 case SSH_CHANNEL_UNIX_LISTENER
:
602 case SSH_CHANNEL_RUNIX_LISTENER
:
604 case SSH_CHANNEL_LARVAL
:
605 case SSH_CHANNEL_AUTH_SOCKET
:
606 case SSH_CHANNEL_OPEN
:
607 case SSH_CHANNEL_X11_OPEN
:
609 case SSH_CHANNEL_INPUT_DRAINING
:
610 case SSH_CHANNEL_OUTPUT_DRAINING
:
612 fatal("cannot happen: OUT_DRAIN");
615 fatal("channel_find_open: bad channel type %d", c
->type
);
624 * Returns a message describing the currently open forwarded connections,
625 * suitable for sending to the client. The message contains crlf pairs for
629 channel_open_message(void)
636 buffer_init(&buffer
);
637 snprintf(buf
, sizeof buf
, "The following connections are open:\r\n");
638 buffer_append(&buffer
, buf
, strlen(buf
));
639 for (i
= 0; i
< channels_alloc
; i
++) {
644 case SSH_CHANNEL_X11_LISTENER
:
645 case SSH_CHANNEL_PORT_LISTENER
:
646 case SSH_CHANNEL_RPORT_LISTENER
:
647 case SSH_CHANNEL_CLOSED
:
648 case SSH_CHANNEL_AUTH_SOCKET
:
649 case SSH_CHANNEL_ZOMBIE
:
650 case SSH_CHANNEL_ABANDONED
:
651 case SSH_CHANNEL_MUX_CLIENT
:
652 case SSH_CHANNEL_MUX_LISTENER
:
653 case SSH_CHANNEL_UNIX_LISTENER
:
654 case SSH_CHANNEL_RUNIX_LISTENER
:
656 case SSH_CHANNEL_LARVAL
:
657 case SSH_CHANNEL_OPENING
:
658 case SSH_CHANNEL_CONNECTING
:
659 case SSH_CHANNEL_DYNAMIC
:
660 case SSH_CHANNEL_OPEN
:
661 case SSH_CHANNEL_X11_OPEN
:
662 case SSH_CHANNEL_INPUT_DRAINING
:
663 case SSH_CHANNEL_OUTPUT_DRAINING
:
664 snprintf(buf
, sizeof buf
,
665 " #%d %.300s (t%d r%d i%d/%d o%d/%d fd %d/%d cc %d)\r\n",
666 c
->self
, c
->remote_name
,
667 c
->type
, c
->remote_id
,
668 c
->istate
, buffer_len(&c
->input
),
669 c
->ostate
, buffer_len(&c
->output
),
670 c
->rfd
, c
->wfd
, c
->ctl_chan
);
671 buffer_append(&buffer
, buf
, strlen(buf
));
674 fatal("channel_open_message: bad channel type %d", c
->type
);
678 buffer_append(&buffer
, "\0", 1);
679 cp
= xstrdup(buffer_ptr(&buffer
));
680 buffer_free(&buffer
);
685 channel_send_open(int id
)
687 Channel
*c
= channel_lookup(id
);
690 logit("channel_send_open: %d: bad id", id
);
693 debug2("channel %d: send open", id
);
694 packet_start(SSH2_MSG_CHANNEL_OPEN
);
695 packet_put_cstring(c
->ctype
);
696 packet_put_int(c
->self
);
697 packet_put_int(c
->local_window
);
698 packet_put_int(c
->local_maxpacket
);
703 channel_request_start(int id
, char *service
, int wantconfirm
)
705 Channel
*c
= channel_lookup(id
);
708 logit("channel_request_start: %d: unknown channel id", id
);
711 debug2("channel %d: request %s confirm %d", id
, service
, wantconfirm
);
712 packet_start(SSH2_MSG_CHANNEL_REQUEST
);
713 packet_put_int(c
->remote_id
);
714 packet_put_cstring(service
);
715 packet_put_char(wantconfirm
);
719 channel_register_status_confirm(int id
, channel_confirm_cb
*cb
,
720 channel_confirm_abandon_cb
*abandon_cb
, void *ctx
)
722 struct channel_confirm
*cc
;
725 if ((c
= channel_lookup(id
)) == NULL
)
726 fatal("channel_register_expect: %d: bad id", id
);
728 cc
= xcalloc(1, sizeof(*cc
));
730 cc
->abandon_cb
= abandon_cb
;
732 TAILQ_INSERT_TAIL(&c
->status_confirms
, cc
, entry
);
736 channel_register_open_confirm(int id
, channel_open_fn
*fn
, void *ctx
)
738 Channel
*c
= channel_lookup(id
);
741 logit("channel_register_open_confirm: %d: bad id", id
);
744 c
->open_confirm
= fn
;
745 c
->open_confirm_ctx
= ctx
;
749 channel_register_cleanup(int id
, channel_callback_fn
*fn
, int do_close
)
751 Channel
*c
= channel_by_id(id
);
754 logit("channel_register_cleanup: %d: bad id", id
);
758 c
->detach_close
= do_close
;
762 channel_cancel_cleanup(int id
)
764 Channel
*c
= channel_by_id(id
);
767 logit("channel_cancel_cleanup: %d: bad id", id
);
770 c
->detach_user
= NULL
;
775 channel_register_filter(int id
, channel_infilter_fn
*ifn
,
776 channel_outfilter_fn
*ofn
, channel_filter_cleanup_fn
*cfn
, void *ctx
)
778 Channel
*c
= channel_lookup(id
);
781 logit("channel_register_filter: %d: bad id", id
);
784 c
->input_filter
= ifn
;
785 c
->output_filter
= ofn
;
787 c
->filter_cleanup
= cfn
;
791 channel_set_fds(int id
, int rfd
, int wfd
, int efd
,
792 int extusage
, int nonblock
, int is_tty
, u_int window_max
)
794 Channel
*c
= channel_lookup(id
);
796 if (c
== NULL
|| c
->type
!= SSH_CHANNEL_LARVAL
)
797 fatal("channel_activate for non-larval channel %d.", id
);
798 channel_register_fds(c
, rfd
, wfd
, efd
, extusage
, nonblock
, is_tty
);
799 c
->type
= SSH_CHANNEL_OPEN
;
800 c
->local_window
= c
->local_window_max
= window_max
;
801 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
802 packet_put_int(c
->remote_id
);
803 packet_put_int(c
->local_window
);
808 * 'channel_pre*' are called just before select() to add any bits relevant to
809 * channels in the select bitmasks.
812 * 'channel_post*': perform any appropriate operations for channels which
813 * have events pending.
815 typedef void chan_fn(Channel
*c
, fd_set
*readset
, fd_set
*writeset
);
816 chan_fn
*channel_pre
[SSH_CHANNEL_MAX_TYPE
];
817 chan_fn
*channel_post
[SSH_CHANNEL_MAX_TYPE
];
821 channel_pre_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
823 FD_SET(c
->sock
, readset
);
828 channel_pre_connecting(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
830 debug3("channel %d: waiting for connection", c
->self
);
831 FD_SET(c
->sock
, writeset
);
835 channel_pre_open_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
837 if (buffer_len(&c
->input
) < packet_get_maxsize())
838 FD_SET(c
->sock
, readset
);
839 if (buffer_len(&c
->output
) > 0)
840 FD_SET(c
->sock
, writeset
);
843 int channel_tcpwinsz () {
844 u_int32_t tcpwinsz
= 0;
845 socklen_t optsz
= sizeof(tcpwinsz
);
848 /* if we aren't on a socket return 128KB*/
849 if(!packet_connection_is_on_socket())
851 ret
= getsockopt(packet_get_connection_in(),
852 SOL_SOCKET
, SO_RCVBUF
, &tcpwinsz
, &optsz
);
853 /* return no more than 64MB */
854 if ((ret
== 0) && tcpwinsz
> SSHBUF_SIZE_MAX
)
855 tcpwinsz
= SSHBUF_SIZE_MAX
;
856 debug2("tcpwinsz: %d for connection: %d", tcpwinsz
,
857 packet_get_connection_in());
862 channel_pre_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
864 u_int limit
= compat20
? c
->remote_window
: packet_get_maxsize();
866 /* check buffer limits */
867 if ((!c
->tcpwinsz
) || (c
->dynamic_window
> 0))
868 c
->tcpwinsz
= channel_tcpwinsz();
870 limit
= MIN(limit
, 2 * c
->tcpwinsz
);
872 if (c
->istate
== CHAN_INPUT_OPEN
&&
874 buffer_len(&c
->input
) < limit
&&
875 buffer_check_alloc(&c
->input
, CHAN_RBUF
))
876 FD_SET(c
->rfd
, readset
);
877 if (c
->ostate
== CHAN_OUTPUT_OPEN
||
878 c
->ostate
== CHAN_OUTPUT_WAIT_DRAIN
) {
879 if (buffer_len(&c
->output
) > 0) {
880 FD_SET(c
->wfd
, writeset
);
881 } else if (c
->ostate
== CHAN_OUTPUT_WAIT_DRAIN
) {
882 if (CHANNEL_EFD_OUTPUT_ACTIVE(c
))
883 debug2("channel %d: obuf_empty delayed efd %d/(%d)",
884 c
->self
, c
->efd
, buffer_len(&c
->extended
));
889 /** XXX check close conditions, too */
890 if (compat20
&& c
->efd
!= -1 &&
891 !(c
->istate
== CHAN_INPUT_CLOSED
&& c
->ostate
== CHAN_OUTPUT_CLOSED
)) {
892 if (c
->extended_usage
== CHAN_EXTENDED_WRITE
&&
893 buffer_len(&c
->extended
) > 0)
894 FD_SET(c
->efd
, writeset
);
895 else if (c
->efd
!= -1 && !(c
->flags
& CHAN_EOF_SENT
) &&
896 (c
->extended_usage
== CHAN_EXTENDED_READ
||
897 c
->extended_usage
== CHAN_EXTENDED_IGNORE
) &&
898 buffer_len(&c
->extended
) < c
->remote_window
)
899 FD_SET(c
->efd
, readset
);
901 /* XXX: What about efd? races? */
906 channel_pre_input_draining(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
908 if (buffer_len(&c
->input
) == 0) {
909 packet_start(SSH_MSG_CHANNEL_CLOSE
);
910 packet_put_int(c
->remote_id
);
912 c
->type
= SSH_CHANNEL_CLOSED
;
913 debug2("channel %d: closing after input drain.", c
->self
);
919 channel_pre_output_draining(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
921 if (buffer_len(&c
->output
) == 0)
924 FD_SET(c
->sock
, writeset
);
928 * This is a special state for X11 authentication spoofing. An opened X11
929 * connection (when authentication spoofing is being done) remains in this
930 * state until the first packet has been completely read. The authentication
931 * data in that packet is then substituted by the real data if it matches the
932 * fake data, and the channel is put into normal mode.
933 * XXX All this happens at the client side.
934 * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
937 x11_open_helper(Buffer
*b
)
940 u_int proto_len
, data_len
;
942 /* Check if the fixed size part of the packet is in buffer. */
943 if (buffer_len(b
) < 12)
946 /* Parse the lengths of variable-length fields. */
948 if (ucp
[0] == 0x42) { /* Byte order MSB first. */
949 proto_len
= 256 * ucp
[6] + ucp
[7];
950 data_len
= 256 * ucp
[8] + ucp
[9];
951 } else if (ucp
[0] == 0x6c) { /* Byte order LSB first. */
952 proto_len
= ucp
[6] + 256 * ucp
[7];
953 data_len
= ucp
[8] + 256 * ucp
[9];
955 debug2("Initial X11 packet contains bad byte order byte: 0x%x",
960 /* Check if the whole packet is in buffer. */
962 12 + ((proto_len
+ 3) & ~3) + ((data_len
+ 3) & ~3))
965 /* Check if authentication protocol matches. */
966 if (proto_len
!= strlen(x11_saved_proto
) ||
967 memcmp(ucp
+ 12, x11_saved_proto
, proto_len
) != 0) {
968 debug2("X11 connection uses different authentication protocol.");
971 /* Check if authentication data matches our fake data. */
972 if (data_len
!= x11_fake_data_len
||
973 timingsafe_bcmp(ucp
+ 12 + ((proto_len
+ 3) & ~3),
974 x11_fake_data
, x11_fake_data_len
) != 0) {
975 debug2("X11 auth data does not match fake data.");
978 /* Check fake data length */
979 if (x11_fake_data_len
!= x11_saved_data_len
) {
980 error("X11 fake_data_len %d != saved_data_len %d",
981 x11_fake_data_len
, x11_saved_data_len
);
985 * Received authentication protocol and data match
986 * our fake data. Substitute the fake data with real
989 memcpy(ucp
+ 12 + ((proto_len
+ 3) & ~3),
990 x11_saved_data
, x11_saved_data_len
);
995 channel_pre_x11_open_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
997 int ret
= x11_open_helper(&c
->output
);
1000 /* Start normal processing for the channel. */
1001 c
->type
= SSH_CHANNEL_OPEN
;
1002 channel_pre_open_13(c
, readset
, writeset
);
1003 } else if (ret
== -1) {
1005 * We have received an X11 connection that has bad
1006 * authentication information.
1008 logit("X11 connection rejected because of wrong authentication.");
1009 buffer_clear(&c
->input
);
1010 buffer_clear(&c
->output
);
1011 channel_close_fd(&c
->sock
);
1013 c
->type
= SSH_CHANNEL_CLOSED
;
1014 packet_start(SSH_MSG_CHANNEL_CLOSE
);
1015 packet_put_int(c
->remote_id
);
1021 channel_pre_x11_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1023 int ret
= x11_open_helper(&c
->output
);
1025 /* c->force_drain = 1; */
1028 c
->type
= SSH_CHANNEL_OPEN
;
1029 channel_pre_open(c
, readset
, writeset
);
1030 } else if (ret
== -1) {
1031 logit("X11 connection rejected because of wrong authentication.");
1032 debug2("X11 rejected %d i%d/o%d", c
->self
, c
->istate
, c
->ostate
);
1033 chan_read_failed(c
);
1034 buffer_clear(&c
->input
);
1036 buffer_clear(&c
->output
);
1037 /* for proto v1, the peer will send an IEOF */
1039 chan_write_failed(c
);
1041 c
->type
= SSH_CHANNEL_OPEN
;
1042 debug2("X11 closed %d i%d/o%d", c
->self
, c
->istate
, c
->ostate
);
1047 channel_pre_mux_client(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1049 if (c
->istate
== CHAN_INPUT_OPEN
&& !c
->mux_pause
&&
1050 buffer_check_alloc(&c
->input
, CHAN_RBUF
))
1051 FD_SET(c
->rfd
, readset
);
1052 if (c
->istate
== CHAN_INPUT_WAIT_DRAIN
) {
1053 /* clear buffer immediately (discard any partial packet) */
1054 buffer_clear(&c
->input
);
1056 /* Start output drain. XXX just kill chan? */
1057 chan_rcvd_oclose(c
);
1059 if (c
->ostate
== CHAN_OUTPUT_OPEN
||
1060 c
->ostate
== CHAN_OUTPUT_WAIT_DRAIN
) {
1061 if (buffer_len(&c
->output
) > 0)
1062 FD_SET(c
->wfd
, writeset
);
1063 else if (c
->ostate
== CHAN_OUTPUT_WAIT_DRAIN
)
1068 /* try to decode a socks4 header */
1071 channel_decode_socks4(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1074 u_int len
, have
, i
, found
, need
;
1079 u_int16_t dest_port
;
1080 struct in_addr dest_addr
;
1083 debug2("channel %d: decode socks4", c
->self
);
1085 have
= buffer_len(&c
->input
);
1086 len
= sizeof(s4_req
);
1089 p
= buffer_ptr(&c
->input
);
1092 /* SOCKS4A uses an invalid IP address 0.0.0.x */
1093 if (p
[4] == 0 && p
[5] == 0 && p
[6] == 0 && p
[7] != 0) {
1094 debug2("channel %d: socks4a request", c
->self
);
1095 /* ... and needs an extra string (the hostname) */
1098 /* Check for terminating NUL on the string(s) */
1099 for (found
= 0, i
= len
; i
< have
; i
++) {
1106 /* the peer is probably sending garbage */
1107 debug("channel %d: decode socks4: too long",
1114 buffer_get(&c
->input
, (char *)&s4_req
.version
, 1);
1115 buffer_get(&c
->input
, (char *)&s4_req
.command
, 1);
1116 buffer_get(&c
->input
, (char *)&s4_req
.dest_port
, 2);
1117 buffer_get(&c
->input
, (char *)&s4_req
.dest_addr
, 4);
1118 have
= buffer_len(&c
->input
);
1119 p
= buffer_ptr(&c
->input
);
1120 if (memchr(p
, '\0', have
) == NULL
)
1121 fatal("channel %d: decode socks4: user not nul terminated",
1124 debug2("channel %d: decode socks4: user %s/%d", c
->self
, p
, len
);
1125 len
++; /* trailing '\0' */
1127 fatal("channel %d: decode socks4: len %d > have %d",
1128 c
->self
, len
, have
);
1129 strlcpy(username
, p
, sizeof(username
));
1130 buffer_consume(&c
->input
, len
);
1134 if (need
== 1) { /* SOCKS4: one string */
1135 host
= inet_ntoa(s4_req
.dest_addr
);
1136 c
->path
= xstrdup(host
);
1137 } else { /* SOCKS4A: two strings */
1138 have
= buffer_len(&c
->input
);
1139 p
= buffer_ptr(&c
->input
);
1141 debug2("channel %d: decode socks4a: host %s/%d",
1143 len
++; /* trailing '\0' */
1145 fatal("channel %d: decode socks4a: len %d > have %d",
1146 c
->self
, len
, have
);
1147 if (len
> NI_MAXHOST
) {
1148 error("channel %d: hostname \"%.100s\" too long",
1152 c
->path
= xstrdup(p
);
1153 buffer_consume(&c
->input
, len
);
1155 c
->host_port
= ntohs(s4_req
.dest_port
);
1157 debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
1158 c
->self
, c
->path
, c
->host_port
, s4_req
.command
);
1160 if (s4_req
.command
!= 1) {
1161 debug("channel %d: cannot handle: %s cn %d",
1162 c
->self
, need
== 1 ? "SOCKS4" : "SOCKS4A", s4_req
.command
);
1165 s4_rsp
.version
= 0; /* vn: 0 for reply */
1166 s4_rsp
.command
= 90; /* cd: req granted */
1167 s4_rsp
.dest_port
= 0; /* ignored */
1168 s4_rsp
.dest_addr
.s_addr
= INADDR_ANY
; /* ignored */
1169 buffer_append(&c
->output
, &s4_rsp
, sizeof(s4_rsp
));
1173 /* try to decode a socks5 header */
1174 #define SSH_SOCKS5_AUTHDONE 0x1000
1175 #define SSH_SOCKS5_NOAUTH 0x00
1176 #define SSH_SOCKS5_IPV4 0x01
1177 #define SSH_SOCKS5_DOMAIN 0x03
1178 #define SSH_SOCKS5_IPV6 0x04
1179 #define SSH_SOCKS5_CONNECT 0x01
1180 #define SSH_SOCKS5_SUCCESS 0x00
1184 channel_decode_socks5(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1192 u_int16_t dest_port
;
1193 char dest_addr
[255+1], ntop
[INET6_ADDRSTRLEN
];
1195 u_int have
, need
, i
, found
, nmethods
, addrlen
, af
;
1197 debug2("channel %d: decode socks5", c
->self
);
1198 p
= buffer_ptr(&c
->input
);
1201 have
= buffer_len(&c
->input
);
1202 if (!(c
->flags
& SSH_SOCKS5_AUTHDONE
)) {
1203 /* format: ver | nmethods | methods */
1207 if (have
< nmethods
+ 2)
1209 /* look for method: "NO AUTHENTICATION REQUIRED" */
1210 for (found
= 0, i
= 2; i
< nmethods
+ 2; i
++) {
1211 if (p
[i
] == SSH_SOCKS5_NOAUTH
) {
1217 debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
1221 buffer_consume(&c
->input
, nmethods
+ 2);
1222 buffer_put_char(&c
->output
, 0x05); /* version */
1223 buffer_put_char(&c
->output
, SSH_SOCKS5_NOAUTH
); /* method */
1224 FD_SET(c
->sock
, writeset
);
1225 c
->flags
|= SSH_SOCKS5_AUTHDONE
;
1226 debug2("channel %d: socks5 auth done", c
->self
);
1227 return 0; /* need more */
1229 debug2("channel %d: socks5 post auth", c
->self
);
1230 if (have
< sizeof(s5_req
)+1)
1231 return 0; /* need more */
1232 memcpy(&s5_req
, p
, sizeof(s5_req
));
1233 if (s5_req
.version
!= 0x05 ||
1234 s5_req
.command
!= SSH_SOCKS5_CONNECT
||
1235 s5_req
.reserved
!= 0x00) {
1236 debug2("channel %d: only socks5 connect supported", c
->self
);
1239 switch (s5_req
.atyp
){
1240 case SSH_SOCKS5_IPV4
:
1244 case SSH_SOCKS5_DOMAIN
:
1245 addrlen
= p
[sizeof(s5_req
)];
1248 case SSH_SOCKS5_IPV6
:
1253 debug2("channel %d: bad socks5 atyp %d", c
->self
, s5_req
.atyp
);
1256 need
= sizeof(s5_req
) + addrlen
+ 2;
1257 if (s5_req
.atyp
== SSH_SOCKS5_DOMAIN
)
1261 buffer_consume(&c
->input
, sizeof(s5_req
));
1262 if (s5_req
.atyp
== SSH_SOCKS5_DOMAIN
)
1263 buffer_consume(&c
->input
, 1); /* host string length */
1264 buffer_get(&c
->input
, &dest_addr
, addrlen
);
1265 buffer_get(&c
->input
, (char *)&dest_port
, 2);
1266 dest_addr
[addrlen
] = '\0';
1269 if (s5_req
.atyp
== SSH_SOCKS5_DOMAIN
) {
1270 if (addrlen
>= NI_MAXHOST
) {
1271 error("channel %d: dynamic request: socks5 hostname "
1272 "\"%.100s\" too long", c
->self
, dest_addr
);
1275 c
->path
= xstrdup(dest_addr
);
1277 if (inet_ntop(af
, dest_addr
, ntop
, sizeof(ntop
)) == NULL
)
1279 c
->path
= xstrdup(ntop
);
1281 c
->host_port
= ntohs(dest_port
);
1283 debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
1284 c
->self
, c
->path
, c
->host_port
, s5_req
.command
);
1286 s5_rsp
.version
= 0x05;
1287 s5_rsp
.command
= SSH_SOCKS5_SUCCESS
;
1288 s5_rsp
.reserved
= 0; /* ignored */
1289 s5_rsp
.atyp
= SSH_SOCKS5_IPV4
;
1290 dest_port
= 0; /* ignored */
1292 buffer_append(&c
->output
, &s5_rsp
, sizeof(s5_rsp
));
1293 buffer_put_int(&c
->output
, ntohl(INADDR_ANY
)); /* bind address */
1294 buffer_append(&c
->output
, &dest_port
, sizeof(dest_port
));
1299 channel_connect_stdio_fwd(const char *host_to_connect
, u_short port_to_connect
,
1304 debug("channel_connect_stdio_fwd %s:%d", host_to_connect
,
1307 c
= channel_new("stdio-forward", SSH_CHANNEL_OPENING
, in
, out
,
1308 -1, CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
1309 0, "stdio-forward", /*nonblock*/0);
1311 c
->path
= xstrdup(host_to_connect
);
1312 c
->host_port
= port_to_connect
;
1313 c
->listening_port
= 0;
1316 channel_register_fds(c
, in
, out
, -1, 0, 1, 0);
1317 port_open_helper(c
, "direct-tcpip");
1322 /* dynamic port forwarding */
1324 channel_pre_dynamic(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1330 have
= buffer_len(&c
->input
);
1331 debug2("channel %d: pre_dynamic: have %d", c
->self
, have
);
1332 /* buffer_dump(&c->input); */
1333 /* check if the fixed size part of the packet is in buffer. */
1336 FD_SET(c
->sock
, readset
);
1339 /* try to guess the protocol */
1340 p
= buffer_ptr(&c
->input
);
1343 ret
= channel_decode_socks4(c
, readset
, writeset
);
1346 ret
= channel_decode_socks5(c
, readset
, writeset
);
1354 } else if (ret
== 0) {
1355 debug2("channel %d: pre_dynamic: need more", c
->self
);
1357 FD_SET(c
->sock
, readset
);
1359 /* switch to the next state */
1360 c
->type
= SSH_CHANNEL_OPENING
;
1361 port_open_helper(c
, "direct-tcpip");
1365 /* This is our fake X11 server socket. */
1368 channel_post_x11_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1371 struct sockaddr_storage addr
;
1372 int newsock
, oerrno
;
1374 char buf
[16384], *remote_ipaddr
;
1377 if (FD_ISSET(c
->sock
, readset
)) {
1378 debug("X11 connection requested.");
1379 addrlen
= sizeof(addr
);
1380 newsock
= accept(c
->sock
, (struct sockaddr
*)&addr
, &addrlen
);
1381 if (c
->single_connection
) {
1383 debug2("single_connection: closing X11 listener.");
1384 channel_close_fd(&c
->sock
);
1389 if (errno
!= EINTR
&& errno
!= EWOULDBLOCK
&&
1390 errno
!= ECONNABORTED
)
1391 error("accept: %.100s", strerror(errno
));
1392 if (errno
== EMFILE
|| errno
== ENFILE
)
1393 c
->notbefore
= monotime() + 1;
1396 set_nodelay(newsock
);
1397 remote_ipaddr
= get_peer_ipaddr(newsock
);
1398 remote_port
= get_peer_port(newsock
);
1399 snprintf(buf
, sizeof buf
, "X11 connection from %.200s port %d",
1400 remote_ipaddr
, remote_port
);
1402 nc
= channel_new("accepted x11 socket",
1403 SSH_CHANNEL_OPENING
, newsock
, newsock
, -1,
1404 c
->local_window_max
, c
->local_maxpacket
, 0, buf
, 1);
1406 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1407 packet_put_cstring("x11");
1408 packet_put_int(nc
->self
);
1409 packet_put_int(nc
->local_window_max
);
1410 packet_put_int(nc
->local_maxpacket
);
1411 /* originator ipaddr and port */
1412 packet_put_cstring(remote_ipaddr
);
1413 if (datafellows
& SSH_BUG_X11FWD
) {
1414 debug2("ssh2 x11 bug compat mode");
1416 packet_put_int(remote_port
);
1420 packet_start(SSH_SMSG_X11_OPEN
);
1421 packet_put_int(nc
->self
);
1422 if (packet_get_protocol_flags() &
1423 SSH_PROTOFLAG_HOST_IN_FWD_OPEN
)
1424 packet_put_cstring(buf
);
1427 free(remote_ipaddr
);
1432 port_open_helper(Channel
*c
, char *rtype
)
1435 char *local_ipaddr
= get_local_ipaddr(c
->sock
);
1436 int local_port
= c
->sock
== -1 ? 65536 : get_sock_port(c
->sock
, 1);
1437 char *remote_ipaddr
= get_peer_ipaddr(c
->sock
);
1438 int remote_port
= get_peer_port(c
->sock
);
1440 if (remote_port
== -1) {
1441 /* Fake addr/port to appease peers that validate it (Tectia) */
1442 free(remote_ipaddr
);
1443 remote_ipaddr
= xstrdup("127.0.0.1");
1444 remote_port
= 65535;
1447 snprintf(buf
, sizeof buf
,
1448 "%s: listening port %d for %.100s port %d, "
1449 "connect from %.200s port %d to %.100s port %d",
1450 rtype
, c
->listening_port
, c
->path
, c
->host_port
,
1451 remote_ipaddr
, remote_port
, local_ipaddr
, local_port
);
1453 free(c
->remote_name
);
1454 c
->remote_name
= xstrdup(buf
);
1457 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1458 packet_put_cstring(rtype
);
1459 packet_put_int(c
->self
);
1460 packet_put_int(c
->local_window_max
);
1461 packet_put_int(c
->local_maxpacket
);
1462 if (strcmp(rtype
, "direct-tcpip") == 0) {
1463 /* target host, port */
1464 packet_put_cstring(c
->path
);
1465 packet_put_int(c
->host_port
);
1466 } else if (strcmp(rtype
, "direct-streamlocal@openssh.com") == 0) {
1468 packet_put_cstring(c
->path
);
1469 } else if (strcmp(rtype
, "forwarded-streamlocal@openssh.com") == 0) {
1471 packet_put_cstring(c
->path
);
1473 /* listen address, port */
1474 packet_put_cstring(c
->path
);
1475 packet_put_int(local_port
);
1477 if (strcmp(rtype
, "forwarded-streamlocal@openssh.com") == 0) {
1478 /* reserved for future owner/mode info */
1479 packet_put_cstring("");
1481 /* originator host and port */
1482 packet_put_cstring(remote_ipaddr
);
1483 packet_put_int((u_int
)remote_port
);
1487 packet_start(SSH_MSG_PORT_OPEN
);
1488 packet_put_int(c
->self
);
1489 packet_put_cstring(c
->path
);
1490 packet_put_int(c
->host_port
);
1491 if (packet_get_protocol_flags() &
1492 SSH_PROTOFLAG_HOST_IN_FWD_OPEN
)
1493 packet_put_cstring(c
->remote_name
);
1496 free(remote_ipaddr
);
1501 channel_set_reuseaddr(int fd
)
1506 * Set socket options.
1507 * Allow local port reuse in TIME_WAIT.
1509 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
)) == -1)
1510 error("setsockopt SO_REUSEADDR fd %d: %s", fd
, strerror(errno
));
1514 * This socket is listening for connections to a forwarded TCP/IP port.
1518 channel_post_port_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1521 struct sockaddr_storage addr
;
1522 int newsock
, nextstate
;
1526 if (FD_ISSET(c
->sock
, readset
)) {
1527 debug("Connection to port %d forwarding "
1528 "to %.100s port %d requested.",
1529 c
->listening_port
, c
->path
, c
->host_port
);
1531 if (c
->type
== SSH_CHANNEL_RPORT_LISTENER
) {
1532 nextstate
= SSH_CHANNEL_OPENING
;
1533 rtype
= "forwarded-tcpip";
1534 } else if (c
->type
== SSH_CHANNEL_RUNIX_LISTENER
) {
1535 nextstate
= SSH_CHANNEL_OPENING
;
1536 rtype
= "forwarded-streamlocal@openssh.com";
1537 } else if (c
->host_port
== PORT_STREAMLOCAL
) {
1538 nextstate
= SSH_CHANNEL_OPENING
;
1539 rtype
= "direct-streamlocal@openssh.com";
1540 } else if (c
->host_port
== 0) {
1541 nextstate
= SSH_CHANNEL_DYNAMIC
;
1542 rtype
= "dynamic-tcpip";
1544 nextstate
= SSH_CHANNEL_OPENING
;
1545 rtype
= "direct-tcpip";
1548 addrlen
= sizeof(addr
);
1549 newsock
= accept(c
->sock
, (struct sockaddr
*)&addr
, &addrlen
);
1551 if (errno
!= EINTR
&& errno
!= EWOULDBLOCK
&&
1552 errno
!= ECONNABORTED
)
1553 error("accept: %.100s", strerror(errno
));
1554 if (errno
== EMFILE
|| errno
== ENFILE
)
1555 c
->notbefore
= monotime() + 1;
1558 if (c
->host_port
!= PORT_STREAMLOCAL
)
1559 set_nodelay(newsock
);
1560 nc
= channel_new(rtype
, nextstate
, newsock
, newsock
, -1,
1561 c
->local_window_max
, c
->local_maxpacket
, 0, rtype
, 1);
1562 nc
->listening_port
= c
->listening_port
;
1563 nc
->host_port
= c
->host_port
;
1564 if (c
->path
!= NULL
)
1565 nc
->path
= xstrdup(c
->path
);
1567 if (nextstate
!= SSH_CHANNEL_DYNAMIC
)
1568 port_open_helper(nc
, rtype
);
1573 * This is the authentication agent socket listening for connections from
1578 channel_post_auth_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1582 struct sockaddr_storage addr
;
1585 if (FD_ISSET(c
->sock
, readset
)) {
1586 addrlen
= sizeof(addr
);
1587 newsock
= accept(c
->sock
, (struct sockaddr
*)&addr
, &addrlen
);
1589 error("accept from auth socket: %.100s",
1591 if (errno
== EMFILE
|| errno
== ENFILE
)
1592 c
->notbefore
= monotime() + 1;
1595 nc
= channel_new("accepted auth socket",
1596 SSH_CHANNEL_OPENING
, newsock
, newsock
, -1,
1597 c
->local_window_max
, c
->local_maxpacket
,
1598 0, "accepted auth socket", 1);
1600 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1601 packet_put_cstring("auth-agent@openssh.com");
1602 packet_put_int(nc
->self
);
1603 packet_put_int(c
->local_window_max
);
1604 packet_put_int(c
->local_maxpacket
);
1606 packet_start(SSH_SMSG_AGENT_OPEN
);
1607 packet_put_int(nc
->self
);
1615 channel_post_connecting(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1618 socklen_t sz
= sizeof(err
);
1620 if (FD_ISSET(c
->sock
, writeset
)) {
1621 if (getsockopt(c
->sock
, SOL_SOCKET
, SO_ERROR
, &err
, &sz
) < 0) {
1623 error("getsockopt SO_ERROR failed");
1626 debug("channel %d: connected to %s port %d",
1627 c
->self
, c
->connect_ctx
.host
, c
->connect_ctx
.port
);
1628 channel_connect_ctx_free(&c
->connect_ctx
);
1629 c
->type
= SSH_CHANNEL_OPEN
;
1631 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
1632 packet_put_int(c
->remote_id
);
1633 packet_put_int(c
->self
);
1634 packet_put_int(c
->local_window
);
1635 packet_put_int(c
->local_maxpacket
);
1637 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
1638 packet_put_int(c
->remote_id
);
1639 packet_put_int(c
->self
);
1642 debug("channel %d: connection failed: %s",
1643 c
->self
, strerror(err
));
1644 /* Try next address, if any */
1645 if ((sock
= connect_next(&c
->connect_ctx
)) > 0) {
1647 c
->sock
= c
->rfd
= c
->wfd
= sock
;
1648 channel_max_fd
= channel_find_maxfd();
1651 /* Exhausted all addresses */
1652 error("connect_to %.100s port %d: failed.",
1653 c
->connect_ctx
.host
, c
->connect_ctx
.port
);
1654 channel_connect_ctx_free(&c
->connect_ctx
);
1656 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
1657 packet_put_int(c
->remote_id
);
1658 packet_put_int(SSH2_OPEN_CONNECT_FAILED
);
1659 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
1660 packet_put_cstring(strerror(err
));
1661 packet_put_cstring("");
1664 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
1665 packet_put_int(c
->remote_id
);
1675 channel_handle_rfd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1677 char buf
[CHAN_RBUF
];
1680 force
= c
->isatty
&& c
->detach_close
&& c
->istate
!= CHAN_INPUT_CLOSED
;
1681 if (c
->rfd
!= -1 && (force
|| FD_ISSET(c
->rfd
, readset
))) {
1683 len
= read(c
->rfd
, buf
, sizeof(buf
));
1684 if (len
< 0 && (errno
== EINTR
||
1685 ((errno
== EAGAIN
|| errno
== EWOULDBLOCK
) && !force
)))
1687 #ifndef PTY_ZEROREAD
1690 if ((!c
->isatty
&& len
<= 0) ||
1691 (c
->isatty
&& (len
< 0 || (len
== 0 && errno
!= 0)))) {
1693 debug2("channel %d: read<=0 rfd %d len %d",
1694 c
->self
, c
->rfd
, len
);
1695 if (c
->type
!= SSH_CHANNEL_OPEN
) {
1696 debug2("channel %d: not open", c
->self
);
1699 } else if (compat13
) {
1700 buffer_clear(&c
->output
);
1701 c
->type
= SSH_CHANNEL_INPUT_DRAINING
;
1702 debug2("channel %d: input draining.", c
->self
);
1704 chan_read_failed(c
);
1708 if (c
->input_filter
!= NULL
) {
1709 if (c
->input_filter(c
, buf
, len
) == -1) {
1710 debug2("channel %d: filter stops", c
->self
);
1711 chan_read_failed(c
);
1713 } else if (c
->datagram
) {
1714 buffer_put_string(&c
->input
, buf
, len
);
1716 buffer_append(&c
->input
, buf
, len
);
1724 channel_handle_wfd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1727 u_char
*data
= NULL
, *buf
;
1728 u_int dlen
, olen
= 0;
1731 /* Send buffered output data to the socket. */
1733 FD_ISSET(c
->wfd
, writeset
) &&
1734 buffer_len(&c
->output
) > 0) {
1735 olen
= buffer_len(&c
->output
);
1736 if (c
->output_filter
!= NULL
) {
1737 if ((buf
= c
->output_filter(c
, &data
, &dlen
)) == NULL
) {
1738 debug2("channel %d: filter stops", c
->self
);
1739 if (c
->type
!= SSH_CHANNEL_OPEN
)
1742 chan_write_failed(c
);
1745 } else if (c
->datagram
) {
1746 buf
= data
= buffer_get_string(&c
->output
, &dlen
);
1748 buf
= data
= buffer_ptr(&c
->output
);
1749 dlen
= buffer_len(&c
->output
);
1753 /* ignore truncated writes, datagrams might get lost */
1754 len
= write(c
->wfd
, buf
, dlen
);
1756 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
||
1757 errno
== EWOULDBLOCK
))
1760 if (c
->type
!= SSH_CHANNEL_OPEN
)
1763 chan_write_failed(c
);
1769 /* XXX: Later AIX versions can't push as much data to tty */
1770 if (compat20
&& c
->wfd_isatty
)
1771 dlen
= MIN(dlen
, 8*1024);
1774 len
= write(c
->wfd
, buf
, dlen
);
1776 (errno
== EINTR
|| errno
== EAGAIN
|| errno
== EWOULDBLOCK
))
1779 if (c
->type
!= SSH_CHANNEL_OPEN
) {
1780 debug2("channel %d: not open", c
->self
);
1783 } else if (compat13
) {
1784 buffer_clear(&c
->output
);
1785 debug2("channel %d: input draining.", c
->self
);
1786 c
->type
= SSH_CHANNEL_INPUT_DRAINING
;
1788 chan_write_failed(c
);
1792 #ifndef BROKEN_TCGETATTR_ICANON
1793 if (compat20
&& c
->isatty
&& dlen
>= 1 && buf
[0] != '\r') {
1794 if (tcgetattr(c
->wfd
, &tio
) == 0 &&
1795 !(tio
.c_lflag
& ECHO
) && (tio
.c_lflag
& ICANON
)) {
1797 * Simulate echo to reduce the impact of
1798 * traffic analysis. We need to match the
1799 * size of a SSH2_MSG_CHANNEL_DATA message
1800 * (4 byte channel id + buf)
1802 packet_send_ignore(4 + len
);
1807 buffer_consume(&c
->output
, len
);
1810 if (compat20
&& olen
> 0)
1811 c
->local_consumed
+= olen
- buffer_len(&c
->output
);
1816 channel_handle_efd(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1818 char buf
[CHAN_RBUF
];
1821 /** XXX handle drain efd, too */
1823 if (c
->extended_usage
== CHAN_EXTENDED_WRITE
&&
1824 FD_ISSET(c
->efd
, writeset
) &&
1825 buffer_len(&c
->extended
) > 0) {
1826 len
= write(c
->efd
, buffer_ptr(&c
->extended
),
1827 buffer_len(&c
->extended
));
1828 debug2("channel %d: written %d to efd %d",
1829 c
->self
, len
, c
->efd
);
1830 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
||
1831 errno
== EWOULDBLOCK
))
1834 debug2("channel %d: closing write-efd %d",
1836 channel_close_fd(&c
->efd
);
1838 buffer_consume(&c
->extended
, len
);
1839 c
->local_consumed
+= len
;
1841 } else if (c
->efd
!= -1 &&
1842 (c
->extended_usage
== CHAN_EXTENDED_READ
||
1843 c
->extended_usage
== CHAN_EXTENDED_IGNORE
) &&
1844 (c
->detach_close
|| FD_ISSET(c
->efd
, readset
))) {
1845 len
= read(c
->efd
, buf
, sizeof(buf
));
1846 debug2("channel %d: read %d from efd %d",
1847 c
->self
, len
, c
->efd
);
1848 if (len
< 0 && (errno
== EINTR
|| ((errno
== EAGAIN
||
1849 errno
== EWOULDBLOCK
) && !c
->detach_close
)))
1852 debug2("channel %d: closing read-efd %d",
1854 channel_close_fd(&c
->efd
);
1856 if (c
->extended_usage
== CHAN_EXTENDED_IGNORE
) {
1857 debug3("channel %d: discard efd",
1860 buffer_append(&c
->extended
, buf
, len
);
1868 channel_check_window(Channel
*c
)
1870 if (c
->type
== SSH_CHANNEL_OPEN
&&
1871 !(c
->flags
& (CHAN_CLOSE_SENT
|CHAN_CLOSE_RCVD
)) &&
1872 ((c
->local_window_max
- c
->local_window
>
1873 c
->local_maxpacket
*3) ||
1874 c
->local_window
< c
->local_window_max
/2) &&
1875 c
->local_consumed
> 0) {
1877 /* adjust max window size if we are in a dynamic environment */
1878 if (c
->dynamic_window
&& (c
->tcpwinsz
> c
->local_window_max
)) {
1879 /* grow the window somewhat aggressively to maintain pressure */
1880 addition
= 1.5*(c
->tcpwinsz
- c
->local_window_max
);
1881 c
->local_window_max
+= addition
;
1883 packet_start(SSH2_MSG_CHANNEL_WINDOW_ADJUST
);
1884 packet_put_int(c
->remote_id
);
1885 packet_put_int(c
->local_consumed
+ addition
);
1887 debug2("channel %d: window %d sent adjust %d",
1888 c
->self
, c
->local_window
,
1890 c
->local_window
+= c
->local_consumed
+ addition
;
1891 c
->local_consumed
= 0;
1897 channel_post_open(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1899 channel_handle_rfd(c
, readset
, writeset
);
1900 channel_handle_wfd(c
, readset
, writeset
);
1903 channel_handle_efd(c
, readset
, writeset
);
1904 channel_check_window(c
);
1908 read_mux(Channel
*c
, u_int need
)
1910 char buf
[CHAN_RBUF
];
1914 if (buffer_len(&c
->input
) < need
) {
1915 rlen
= need
- buffer_len(&c
->input
);
1916 len
= read(c
->rfd
, buf
, MIN(rlen
, CHAN_RBUF
));
1918 if (errno
!= EINTR
&& errno
!= EAGAIN
) {
1919 debug2("channel %d: ctl read<=0 rfd %d len %d",
1920 c
->self
, c
->rfd
, len
);
1921 chan_read_failed(c
);
1925 buffer_append(&c
->input
, buf
, len
);
1927 return buffer_len(&c
->input
);
1931 channel_post_mux_client(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1937 fatal("%s: entered with !compat20", __func__
);
1939 if (c
->rfd
!= -1 && !c
->mux_pause
&& FD_ISSET(c
->rfd
, readset
) &&
1940 (c
->istate
== CHAN_INPUT_OPEN
||
1941 c
->istate
== CHAN_INPUT_WAIT_DRAIN
)) {
1943 * Don't not read past the precise end of packets to
1944 * avoid disrupting fd passing.
1946 if (read_mux(c
, 4) < 4) /* read header */
1948 need
= get_u32(buffer_ptr(&c
->input
));
1949 #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
1950 if (need
> CHANNEL_MUX_MAX_PACKET
) {
1951 debug2("channel %d: packet too big %u > %u",
1952 c
->self
, CHANNEL_MUX_MAX_PACKET
, need
);
1953 chan_rcvd_oclose(c
);
1956 if (read_mux(c
, need
+ 4) < need
+ 4) /* read body */
1958 if (c
->mux_rcb(c
) != 0) {
1959 debug("channel %d: mux_rcb failed", c
->self
);
1965 if (c
->wfd
!= -1 && FD_ISSET(c
->wfd
, writeset
) &&
1966 buffer_len(&c
->output
) > 0) {
1967 len
= write(c
->wfd
, buffer_ptr(&c
->output
),
1968 buffer_len(&c
->output
));
1969 if (len
< 0 && (errno
== EINTR
|| errno
== EAGAIN
))
1975 buffer_consume(&c
->output
, len
);
1980 channel_post_mux_listener(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
1983 struct sockaddr_storage addr
;
1989 if (!FD_ISSET(c
->sock
, readset
))
1992 debug("multiplexing control connection");
1995 * Accept connection on control socket
1997 memset(&addr
, 0, sizeof(addr
));
1998 addrlen
= sizeof(addr
);
1999 if ((newsock
= accept(c
->sock
, (struct sockaddr
*)&addr
,
2001 error("%s accept: %s", __func__
, strerror(errno
));
2002 if (errno
== EMFILE
|| errno
== ENFILE
)
2003 c
->notbefore
= monotime() + 1;
2007 if (getpeereid(newsock
, &euid
, &egid
) < 0) {
2008 error("%s getpeereid failed: %s", __func__
,
2013 if ((euid
!= 0) && (getuid() != euid
)) {
2014 error("multiplex uid mismatch: peer euid %u != uid %u",
2015 (u_int
)euid
, (u_int
)getuid());
2019 nc
= channel_new("multiplex client", SSH_CHANNEL_MUX_CLIENT
,
2020 newsock
, newsock
, -1, c
->local_window_max
,
2021 c
->local_maxpacket
, 0, "mux-control", 1);
2022 nc
->mux_rcb
= c
->mux_rcb
;
2023 debug3("%s: new mux channel %d fd %d", __func__
,
2024 nc
->self
, nc
->sock
);
2025 /* establish state */
2027 /* mux state transitions must not elicit protocol messages */
2028 nc
->flags
|= CHAN_LOCAL
;
2033 channel_post_output_drain_13(Channel
*c
, fd_set
*readset
, fd_set
*writeset
)
2037 /* Send buffered output data to the socket. */
2038 if (FD_ISSET(c
->sock
, writeset
) && buffer_len(&c
->output
) > 0) {
2039 len
= write(c
->sock
, buffer_ptr(&c
->output
),
2040 buffer_len(&c
->output
));
2042 buffer_clear(&c
->output
);
2044 buffer_consume(&c
->output
, len
);
2049 channel_handler_init_20(void)
2051 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open
;
2052 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open
;
2053 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
2054 channel_pre
[SSH_CHANNEL_RPORT_LISTENER
] = &channel_pre_listener
;
2055 channel_pre
[SSH_CHANNEL_UNIX_LISTENER
] = &channel_pre_listener
;
2056 channel_pre
[SSH_CHANNEL_RUNIX_LISTENER
] = &channel_pre_listener
;
2057 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
2058 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
2059 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
2060 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
2061 channel_pre
[SSH_CHANNEL_MUX_LISTENER
] = &channel_pre_listener
;
2062 channel_pre
[SSH_CHANNEL_MUX_CLIENT
] = &channel_pre_mux_client
;
2064 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
2065 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
2066 channel_post
[SSH_CHANNEL_RPORT_LISTENER
] = &channel_post_port_listener
;
2067 channel_post
[SSH_CHANNEL_UNIX_LISTENER
] = &channel_post_port_listener
;
2068 channel_post
[SSH_CHANNEL_RUNIX_LISTENER
] = &channel_post_port_listener
;
2069 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
2070 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
2071 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
2072 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
2073 channel_post
[SSH_CHANNEL_MUX_LISTENER
] = &channel_post_mux_listener
;
2074 channel_post
[SSH_CHANNEL_MUX_CLIENT
] = &channel_post_mux_client
;
2078 channel_handler_init_13(void)
2080 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open_13
;
2081 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open_13
;
2082 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
2083 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
2084 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
2085 channel_pre
[SSH_CHANNEL_INPUT_DRAINING
] = &channel_pre_input_draining
;
2086 channel_pre
[SSH_CHANNEL_OUTPUT_DRAINING
] = &channel_pre_output_draining
;
2087 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
2088 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
2090 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
2091 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
2092 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
2093 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
2094 channel_post
[SSH_CHANNEL_OUTPUT_DRAINING
] = &channel_post_output_drain_13
;
2095 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
2096 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
2100 channel_handler_init_15(void)
2102 channel_pre
[SSH_CHANNEL_OPEN
] = &channel_pre_open
;
2103 channel_pre
[SSH_CHANNEL_X11_OPEN
] = &channel_pre_x11_open
;
2104 channel_pre
[SSH_CHANNEL_X11_LISTENER
] = &channel_pre_listener
;
2105 channel_pre
[SSH_CHANNEL_PORT_LISTENER
] = &channel_pre_listener
;
2106 channel_pre
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_pre_listener
;
2107 channel_pre
[SSH_CHANNEL_CONNECTING
] = &channel_pre_connecting
;
2108 channel_pre
[SSH_CHANNEL_DYNAMIC
] = &channel_pre_dynamic
;
2110 channel_post
[SSH_CHANNEL_X11_LISTENER
] = &channel_post_x11_listener
;
2111 channel_post
[SSH_CHANNEL_PORT_LISTENER
] = &channel_post_port_listener
;
2112 channel_post
[SSH_CHANNEL_AUTH_SOCKET
] = &channel_post_auth_listener
;
2113 channel_post
[SSH_CHANNEL_OPEN
] = &channel_post_open
;
2114 channel_post
[SSH_CHANNEL_CONNECTING
] = &channel_post_connecting
;
2115 channel_post
[SSH_CHANNEL_DYNAMIC
] = &channel_post_open
;
2119 channel_handler_init(void)
2123 for (i
= 0; i
< SSH_CHANNEL_MAX_TYPE
; i
++) {
2124 channel_pre
[i
] = NULL
;
2125 channel_post
[i
] = NULL
;
2128 channel_handler_init_20();
2130 channel_handler_init_13();
2132 channel_handler_init_15();
2135 /* gc dead channels */
2137 channel_garbage_collect(Channel
*c
)
2141 if (c
->detach_user
!= NULL
) {
2142 if (!chan_is_dead(c
, c
->detach_close
))
2144 debug2("channel %d: gc: notify user", c
->self
);
2145 c
->detach_user(c
->self
, NULL
);
2146 /* if we still have a callback */
2147 if (c
->detach_user
!= NULL
)
2149 debug2("channel %d: gc: user detached", c
->self
);
2151 if (!chan_is_dead(c
, 1))
2153 debug2("channel %d: garbage collecting", c
->self
);
2158 channel_handler(chan_fn
*ftab
[], fd_set
*readset
, fd_set
*writeset
,
2159 time_t *unpause_secs
)
2161 static int did_init
= 0;
2167 channel_handler_init();
2171 if (unpause_secs
!= NULL
)
2173 for (i
= 0, oalloc
= channels_alloc
; i
< oalloc
; i
++) {
2178 if (ftab
== channel_pre
)
2183 if (ftab
[c
->type
] != NULL
) {
2185 * Run handlers that are not paused.
2187 if (c
->notbefore
<= now
)
2188 (*ftab
[c
->type
])(c
, readset
, writeset
);
2189 else if (unpause_secs
!= NULL
) {
2191 * Collect the time that the earliest
2192 * channel comes off pause.
2194 debug3("%s: chan %d: skip for %d more seconds",
2196 (int)(c
->notbefore
- now
));
2197 if (*unpause_secs
== 0 ||
2198 (c
->notbefore
- now
) < *unpause_secs
)
2199 *unpause_secs
= c
->notbefore
- now
;
2202 channel_garbage_collect(c
);
2204 if (unpause_secs
!= NULL
&& *unpause_secs
!= 0)
2205 debug3("%s: first channel unpauses in %d seconds",
2206 __func__
, (int)*unpause_secs
);
2210 * Allocate/update select bitmasks and add any bits relevant to channels in
2214 channel_prepare_select(fd_set
**readsetp
, fd_set
**writesetp
, int *maxfdp
,
2215 u_int
*nallocp
, time_t *minwait_secs
, int rekeying
)
2217 u_int n
, sz
, nfdset
;
2219 n
= MAX(*maxfdp
, channel_max_fd
);
2221 nfdset
= howmany(n
+1, NFDBITS
);
2222 /* Explicitly test here, because xrealloc isn't always called */
2223 if (nfdset
&& SIZE_T_MAX
/ nfdset
< sizeof(fd_mask
))
2224 fatal("channel_prepare_select: max_fd (%d) is too large", n
);
2225 sz
= nfdset
* sizeof(fd_mask
);
2227 /* perhaps check sz < nalloc/2 and shrink? */
2228 if (*readsetp
== NULL
|| sz
> *nallocp
) {
2229 *readsetp
= xrealloc(*readsetp
, nfdset
, sizeof(fd_mask
));
2230 *writesetp
= xrealloc(*writesetp
, nfdset
, sizeof(fd_mask
));
2234 memset(*readsetp
, 0, sz
);
2235 memset(*writesetp
, 0, sz
);
2238 channel_handler(channel_pre
, *readsetp
, *writesetp
,
2243 * After select, perform any appropriate operations for channels which have
2247 channel_after_select(fd_set
*readset
, fd_set
*writeset
)
2249 channel_handler(channel_post
, readset
, writeset
, NULL
);
2253 /* If there is data to send to the connection, enqueue some of it now. */
2255 channel_output_poll(void)
2259 int packet_length
= 0;
2261 for (i
= 0; i
< channels_alloc
; i
++) {
2267 * We are only interested in channels that can have buffered
2271 if (c
->type
!= SSH_CHANNEL_OPEN
&&
2272 c
->type
!= SSH_CHANNEL_INPUT_DRAINING
)
2275 if (c
->type
!= SSH_CHANNEL_OPEN
)
2279 (c
->flags
& (CHAN_CLOSE_SENT
|CHAN_CLOSE_RCVD
))) {
2280 /* XXX is this true? */
2281 debug3("channel %d: will not send data after close", c
->self
);
2285 /* Get the amount of buffered data for this channel. */
2286 if ((c
->istate
== CHAN_INPUT_OPEN
||
2287 c
->istate
== CHAN_INPUT_WAIT_DRAIN
) &&
2288 (len
= buffer_len(&c
->input
)) > 0) {
2294 data
= buffer_get_string(&c
->input
,
2296 if (dlen
> c
->remote_window
||
2297 dlen
> c
->remote_maxpacket
) {
2298 debug("channel %d: datagram "
2299 "too big for channel",
2304 packet_start(SSH2_MSG_CHANNEL_DATA
);
2305 packet_put_int(c
->remote_id
);
2306 packet_put_string(data
, dlen
);
2307 packet_length
= packet_send();
2308 c
->remote_window
-= dlen
+ 4;
2314 * Send some data for the other side over the secure
2318 if (len
> c
->remote_window
)
2319 len
= c
->remote_window
;
2320 if (len
> c
->remote_maxpacket
)
2321 len
= c
->remote_maxpacket
;
2323 if (packet_is_interactive()) {
2327 /* Keep the packets at reasonable size. */
2328 if (len
> packet_get_maxsize()/2)
2329 len
= packet_get_maxsize()/2;
2333 packet_start(compat20
?
2334 SSH2_MSG_CHANNEL_DATA
: SSH_MSG_CHANNEL_DATA
);
2335 packet_put_int(c
->remote_id
);
2336 packet_put_string(buffer_ptr(&c
->input
), len
);
2337 packet_length
= packet_send();
2338 buffer_consume(&c
->input
, len
);
2339 c
->remote_window
-= len
;
2341 } else if (c
->istate
== CHAN_INPUT_WAIT_DRAIN
) {
2343 fatal("cannot happen: istate == INPUT_WAIT_DRAIN for proto 1.3");
2345 * input-buffer is empty and read-socket shutdown:
2346 * tell peer, that we will not send more data: send IEOF.
2347 * hack for extended data: delay EOF if EFD still in use.
2349 if (CHANNEL_EFD_INPUT_ACTIVE(c
))
2350 debug2("channel %d: ibuf_empty delayed efd %d/(%d)",
2351 c
->self
, c
->efd
, buffer_len(&c
->extended
));
2355 /* Send extended data, i.e. stderr */
2357 !(c
->flags
& CHAN_EOF_SENT
) &&
2358 c
->remote_window
> 0 &&
2359 (len
= buffer_len(&c
->extended
)) > 0 &&
2360 c
->extended_usage
== CHAN_EXTENDED_READ
) {
2361 debug2("channel %d: rwin %u elen %u euse %d",
2362 c
->self
, c
->remote_window
, buffer_len(&c
->extended
),
2364 if (len
> c
->remote_window
)
2365 len
= c
->remote_window
;
2366 if (len
> c
->remote_maxpacket
)
2367 len
= c
->remote_maxpacket
;
2368 packet_start(SSH2_MSG_CHANNEL_EXTENDED_DATA
);
2369 packet_put_int(c
->remote_id
);
2370 packet_put_int(SSH2_EXTENDED_DATA_STDERR
);
2371 packet_put_string(buffer_ptr(&c
->extended
), len
);
2372 packet_length
= packet_send();
2373 buffer_consume(&c
->extended
, len
);
2374 c
->remote_window
-= len
;
2375 debug2("channel %d: sent ext data %d", c
->self
, len
);
2378 return (packet_length
);
2382 /* -- protocol input */
2386 channel_input_data(int type
, u_int32_t seq
, void *ctxt
)
2390 u_int data_len
, win_len
;
2393 /* Get the channel number and verify it. */
2394 id
= packet_get_int();
2395 c
= channel_lookup(id
);
2397 packet_disconnect("Received data for nonexistent channel %d.", id
);
2399 /* Ignore any data for non-open channels (might happen on close) */
2400 if (c
->type
!= SSH_CHANNEL_OPEN
&&
2401 c
->type
!= SSH_CHANNEL_X11_OPEN
)
2405 data
= packet_get_string_ptr(&data_len
);
2408 win_len
+= 4; /* string length header */
2411 * Ignore data for protocol > 1.3 if output end is no longer open.
2412 * For protocol 2 the sending side is reducing its window as it sends
2413 * data, so we must 'fake' consumption of the data in order to ensure
2414 * that window updates are sent back. Otherwise the connection might
2417 if (!compat13
&& c
->ostate
!= CHAN_OUTPUT_OPEN
) {
2419 c
->local_window
-= win_len
;
2420 c
->local_consumed
+= win_len
;
2426 if (win_len
> c
->local_maxpacket
) {
2427 logit("channel %d: rcvd big packet %d, maxpack %d",
2428 c
->self
, win_len
, c
->local_maxpacket
);
2430 if (win_len
> c
->local_window
) {
2431 logit("channel %d: rcvd too much data %d, win %d",
2432 c
->self
, win_len
, c
->local_window
);
2435 c
->local_window
-= win_len
;
2438 buffer_put_string(&c
->output
, data
, data_len
);
2440 buffer_append(&c
->output
, data
, data_len
);
2446 channel_input_extended_data(int type
, u_int32_t seq
, void *ctxt
)
2450 u_int data_len
, tcode
;
2453 /* Get the channel number and verify it. */
2454 id
= packet_get_int();
2455 c
= channel_lookup(id
);
2458 packet_disconnect("Received extended_data for bad channel %d.", id
);
2459 if (c
->type
!= SSH_CHANNEL_OPEN
) {
2460 logit("channel %d: ext data for non open", id
);
2463 if (c
->flags
& CHAN_EOF_RCVD
) {
2464 if (datafellows
& SSH_BUG_EXTEOF
)
2465 debug("channel %d: accepting ext data after eof", id
);
2467 packet_disconnect("Received extended_data after EOF "
2468 "on channel %d.", id
);
2470 tcode
= packet_get_int();
2472 c
->extended_usage
!= CHAN_EXTENDED_WRITE
||
2473 tcode
!= SSH2_EXTENDED_DATA_STDERR
) {
2474 logit("channel %d: bad ext data", c
->self
);
2477 data
= packet_get_string(&data_len
);
2479 if (data_len
> c
->local_window
) {
2480 logit("channel %d: rcvd too much extended_data %d, win %d",
2481 c
->self
, data_len
, c
->local_window
);
2485 debug2("channel %d: rcvd ext data %d", c
->self
, data_len
);
2486 c
->local_window
-= data_len
;
2487 buffer_append(&c
->extended
, data
, data_len
);
2493 channel_input_ieof(int type
, u_int32_t seq
, void *ctxt
)
2498 id
= packet_get_int();
2500 c
= channel_lookup(id
);
2502 packet_disconnect("Received ieof for nonexistent channel %d.", id
);
2505 /* XXX force input close */
2506 if (c
->force_drain
&& c
->istate
== CHAN_INPUT_OPEN
) {
2507 debug("channel %d: FORCE input drain", c
->self
);
2508 c
->istate
= CHAN_INPUT_WAIT_DRAIN
;
2509 if (buffer_len(&c
->input
) == 0)
2517 channel_input_close(int type
, u_int32_t seq
, void *ctxt
)
2522 id
= packet_get_int();
2524 c
= channel_lookup(id
);
2526 packet_disconnect("Received close for nonexistent channel %d.", id
);
2529 * Send a confirmation that we have closed the channel and no more
2530 * data is coming for it.
2532 packet_start(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
);
2533 packet_put_int(c
->remote_id
);
2537 * If the channel is in closed state, we have sent a close request,
2538 * and the other side will eventually respond with a confirmation.
2539 * Thus, we cannot free the channel here, because then there would be
2540 * no-one to receive the confirmation. The channel gets freed when
2541 * the confirmation arrives.
2543 if (c
->type
!= SSH_CHANNEL_CLOSED
) {
2545 * Not a closed channel - mark it as draining, which will
2546 * cause it to be freed later.
2548 buffer_clear(&c
->input
);
2549 c
->type
= SSH_CHANNEL_OUTPUT_DRAINING
;
2553 /* proto version 1.5 overloads CLOSE_CONFIRMATION with OCLOSE */
2556 channel_input_oclose(int type
, u_int32_t seq
, void *ctxt
)
2558 int id
= packet_get_int();
2559 Channel
*c
= channel_lookup(id
);
2563 packet_disconnect("Received oclose for nonexistent channel %d.", id
);
2564 chan_rcvd_oclose(c
);
2569 channel_input_close_confirmation(int type
, u_int32_t seq
, void *ctxt
)
2571 int id
= packet_get_int();
2572 Channel
*c
= channel_lookup(id
);
2576 packet_disconnect("Received close confirmation for "
2577 "out-of-range channel %d.", id
);
2578 if (c
->type
!= SSH_CHANNEL_CLOSED
&& c
->type
!= SSH_CHANNEL_ABANDONED
)
2579 packet_disconnect("Received close confirmation for "
2580 "non-closed channel %d (type %d).", id
, c
->type
);
2586 channel_input_open_confirmation(int type
, u_int32_t seq
, void *ctxt
)
2591 id
= packet_get_int();
2592 c
= channel_lookup(id
);
2594 if (c
==NULL
|| c
->type
!= SSH_CHANNEL_OPENING
)
2595 packet_disconnect("Received open confirmation for "
2596 "non-opening channel %d.", id
);
2597 remote_id
= packet_get_int();
2598 /* Record the remote channel number and mark that the channel is now open. */
2599 c
->remote_id
= remote_id
;
2600 c
->type
= SSH_CHANNEL_OPEN
;
2603 c
->remote_window
= packet_get_int();
2604 c
->remote_maxpacket
= packet_get_int();
2605 if (c
->open_confirm
) {
2606 debug2("callback start");
2607 c
->open_confirm(c
->self
, 1, c
->open_confirm_ctx
);
2608 debug2("callback done");
2610 debug2("channel %d: open confirm rwindow %u rmax %u", c
->self
,
2611 c
->remote_window
, c
->remote_maxpacket
);
2617 reason2txt(int reason
)
2620 case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED
:
2621 return "administratively prohibited";
2622 case SSH2_OPEN_CONNECT_FAILED
:
2623 return "connect failed";
2624 case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE
:
2625 return "unknown channel type";
2626 case SSH2_OPEN_RESOURCE_SHORTAGE
:
2627 return "resource shortage";
2629 return "unknown reason";
2634 channel_input_open_failure(int type
, u_int32_t seq
, void *ctxt
)
2637 char *msg
= NULL
, *lang
= NULL
;
2640 id
= packet_get_int();
2641 c
= channel_lookup(id
);
2643 if (c
==NULL
|| c
->type
!= SSH_CHANNEL_OPENING
)
2644 packet_disconnect("Received open failure for "
2645 "non-opening channel %d.", id
);
2647 reason
= packet_get_int();
2648 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
2649 msg
= packet_get_string(NULL
);
2650 lang
= packet_get_string(NULL
);
2652 logit("channel %d: open failed: %s%s%s", id
,
2653 reason2txt(reason
), msg
? ": ": "", msg
? msg
: "");
2656 if (c
->open_confirm
) {
2657 debug2("callback start");
2658 c
->open_confirm(c
->self
, 0, c
->open_confirm_ctx
);
2659 debug2("callback done");
2663 /* Schedule the channel for cleanup/deletion. */
2669 channel_input_window_adjust(int type
, u_int32_t seq
, void *ctxt
)
2678 /* Get the channel number and verify it. */
2679 id
= packet_get_int();
2680 c
= channel_lookup(id
);
2683 logit("Received window adjust for non-open channel %d.", id
);
2686 adjust
= packet_get_int();
2688 debug2("channel %d: rcvd adjust %u", id
, adjust
);
2689 c
->remote_window
+= adjust
;
2694 channel_input_port_open(int type
, u_int32_t seq
, void *ctxt
)
2698 char *host
, *originator_string
;
2701 remote_id
= packet_get_int();
2702 host
= packet_get_string(NULL
);
2703 host_port
= packet_get_int();
2705 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN
) {
2706 originator_string
= packet_get_string(NULL
);
2708 originator_string
= xstrdup("unknown (remote did not supply name)");
2711 c
= channel_connect_to_port(host
, host_port
,
2712 "connected socket", originator_string
);
2713 free(originator_string
);
2716 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
2717 packet_put_int(remote_id
);
2720 c
->remote_id
= remote_id
;
2725 channel_input_status_confirm(int type
, u_int32_t seq
, void *ctxt
)
2728 struct channel_confirm
*cc
;
2731 /* Reset keepalive timeout */
2732 packet_set_alive_timeouts(0);
2734 id
= packet_get_int();
2737 debug2("channel_input_status_confirm: type %d id %d", type
, id
);
2739 if ((c
= channel_lookup(id
)) == NULL
) {
2740 logit("channel_input_status_confirm: %d: unknown", id
);
2744 if ((cc
= TAILQ_FIRST(&c
->status_confirms
)) == NULL
)
2746 cc
->cb(type
, c
, cc
->ctx
);
2747 TAILQ_REMOVE(&c
->status_confirms
, cc
, entry
);
2748 explicit_bzero(cc
, sizeof(*cc
));
2752 /* -- tcp forwarding */
2755 channel_set_af(int af
)
2762 channel_set_hpn(int external_hpn_disabled
, int external_hpn_buffer_size
)
2764 hpn_disabled
= external_hpn_disabled
;
2765 hpn_buffer_size
= external_hpn_buffer_size
;
2766 debug("HPN Disabled: %d, HPN Buffer Size: %d", hpn_disabled
, hpn_buffer_size
);
2769 * Determine whether or not a port forward listens to loopback, the
2770 * specified address or wildcard. On the client, a specified bind
2771 * address will always override gateway_ports. On the server, a
2772 * gateway_ports of 1 (``yes'') will override the client's specification
2773 * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
2774 * will bind to whatever address the client asked for.
2776 * Special-case listen_addrs are:
2778 * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
2779 * "" (empty string), "*" -> wildcard v4/v6
2780 * "localhost" -> loopback v4/v6
2781 * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
2784 channel_fwd_bind_addr(const char *listen_addr
, int *wildcardp
,
2785 int is_client
, struct ForwardOptions
*fwd_opts
)
2787 const char *addr
= NULL
;
2790 if (listen_addr
== NULL
) {
2791 /* No address specified: default to gateway_ports setting */
2792 if (fwd_opts
->gateway_ports
)
2794 } else if (fwd_opts
->gateway_ports
|| is_client
) {
2795 if (((datafellows
& SSH_OLD_FORWARD_ADDR
) &&
2796 strcmp(listen_addr
, "0.0.0.0") == 0 && is_client
== 0) ||
2797 *listen_addr
== '\0' || strcmp(listen_addr
, "*") == 0 ||
2798 (!is_client
&& fwd_opts
->gateway_ports
== 1)) {
2801 * Notify client if they requested a specific listen
2802 * address and it was overridden.
2804 if (*listen_addr
!= '\0' &&
2805 strcmp(listen_addr
, "0.0.0.0") != 0 &&
2806 strcmp(listen_addr
, "*") != 0) {
2807 packet_send_debug("Forwarding listen address "
2808 "\"%s\" overridden by server "
2809 "GatewayPorts", listen_addr
);
2811 } else if (strcmp(listen_addr
, "localhost") != 0 ||
2812 strcmp(listen_addr
, "127.0.0.1") == 0 ||
2813 strcmp(listen_addr
, "::1") == 0) {
2814 /* Accept localhost address when GatewayPorts=yes */
2817 } else if (strcmp(listen_addr
, "127.0.0.1") == 0 ||
2818 strcmp(listen_addr
, "::1") == 0) {
2820 * If a specific IPv4/IPv6 localhost address has been
2821 * requested then accept it even if gateway_ports is in
2822 * effect. This allows the client to prefer IPv4 or IPv6.
2826 if (wildcardp
!= NULL
)
2827 *wildcardp
= wildcard
;
2832 channel_setup_fwd_listener_tcpip(int type
, struct Forward
*fwd
,
2833 int *allocated_listen_port
, struct ForwardOptions
*fwd_opts
)
2836 int sock
, r
, success
= 0, wildcard
= 0, is_client
;
2837 struct addrinfo hints
, *ai
, *aitop
;
2838 const char *host
, *addr
;
2839 char ntop
[NI_MAXHOST
], strport
[NI_MAXSERV
];
2842 host
= (type
== SSH_CHANNEL_RPORT_LISTENER
) ?
2843 fwd
->listen_host
: fwd
->connect_host
;
2844 is_client
= (type
== SSH_CHANNEL_PORT_LISTENER
);
2847 error("No forward host name.");
2850 if (strlen(host
) >= NI_MAXHOST
) {
2851 error("Forward host name too long.");
2855 /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
2856 addr
= channel_fwd_bind_addr(fwd
->listen_host
, &wildcard
,
2857 is_client
, fwd_opts
);
2858 debug3("%s: type %d wildcard %d addr %s", __func__
,
2859 type
, wildcard
, (addr
== NULL
) ? "NULL" : addr
);
2862 * getaddrinfo returns a loopback address if the hostname is
2863 * set to NULL and hints.ai_flags is not AI_PASSIVE
2865 memset(&hints
, 0, sizeof(hints
));
2866 hints
.ai_family
= IPv4or6
;
2867 hints
.ai_flags
= wildcard
? AI_PASSIVE
: 0;
2868 hints
.ai_socktype
= SOCK_STREAM
;
2869 snprintf(strport
, sizeof strport
, "%d", fwd
->listen_port
);
2870 if ((r
= getaddrinfo(addr
, strport
, &hints
, &aitop
)) != 0) {
2872 /* This really shouldn't happen */
2873 packet_disconnect("getaddrinfo: fatal error: %s",
2874 ssh_gai_strerror(r
));
2876 error("%s: getaddrinfo(%.64s): %s", __func__
, addr
,
2877 ssh_gai_strerror(r
));
2881 if (allocated_listen_port
!= NULL
)
2882 *allocated_listen_port
= 0;
2883 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
2884 switch (ai
->ai_family
) {
2886 lport_p
= &((struct sockaddr_in
*)ai
->ai_addr
)->
2890 lport_p
= &((struct sockaddr_in6
*)ai
->ai_addr
)->
2897 * If allocating a port for -R forwards, then use the
2898 * same port for all address families.
2900 if (type
== SSH_CHANNEL_RPORT_LISTENER
&& fwd
->listen_port
== 0 &&
2901 allocated_listen_port
!= NULL
&& *allocated_listen_port
> 0)
2902 *lport_p
= htons(*allocated_listen_port
);
2904 if (getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
, ntop
, sizeof(ntop
),
2905 strport
, sizeof(strport
), NI_NUMERICHOST
|NI_NUMERICSERV
) != 0) {
2906 error("%s: getnameinfo failed", __func__
);
2909 /* Create a port to listen for the host. */
2910 sock
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
2912 /* this is no error since kernel may not support ipv6 */
2913 verbose("socket: %.100s", strerror(errno
));
2917 channel_set_reuseaddr(sock
);
2918 if (ai
->ai_family
== AF_INET6
)
2919 sock_set_v6only(sock
);
2921 debug("Local forwarding listening on %s port %s.",
2924 /* Bind the socket to the address. */
2925 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
2926 /* address can be in use ipv6 address is already bound */
2928 error("bind: %.100s", strerror(errno
));
2930 verbose("bind: %.100s", strerror(errno
));
2935 /* Start listening for connections on the socket. */
2936 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0) {
2937 error("listen: %.100s", strerror(errno
));
2943 * fwd->listen_port == 0 requests a dynamically allocated port -
2944 * record what we got.
2946 if (type
== SSH_CHANNEL_RPORT_LISTENER
&& fwd
->listen_port
== 0 &&
2947 allocated_listen_port
!= NULL
&&
2948 *allocated_listen_port
== 0) {
2949 *allocated_listen_port
= get_sock_port(sock
, 1);
2950 debug("Allocated listen port %d",
2951 *allocated_listen_port
);
2954 /* Allocate a channel number for the socket. */
2955 /* explicitly test for hpn disabled option. if true use smaller window size */
2957 c
= channel_new("port listener", type
, sock
, sock
, -1,
2958 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
2959 0, "port listener", 1);
2961 c
= channel_new("port listener", type
, sock
, sock
, -1,
2962 hpn_buffer_size
, CHAN_TCP_PACKET_DEFAULT
,
2963 0, "port listener", 1);
2964 c
->path
= xstrdup(host
);
2965 c
->host_port
= fwd
->connect_port
;
2966 c
->listening_addr
= addr
== NULL
? NULL
: xstrdup(addr
);
2967 if (fwd
->listen_port
== 0 && allocated_listen_port
!= NULL
&&
2968 !(datafellows
& SSH_BUG_DYNAMIC_RPORT
))
2969 c
->listening_port
= *allocated_listen_port
;
2971 c
->listening_port
= fwd
->listen_port
;
2975 error("%s: cannot listen to port: %d", __func__
,
2977 freeaddrinfo(aitop
);
2982 channel_setup_fwd_listener_streamlocal(int type
, struct Forward
*fwd
,
2983 struct ForwardOptions
*fwd_opts
)
2985 struct sockaddr_un sunaddr
;
2992 case SSH_CHANNEL_UNIX_LISTENER
:
2993 if (fwd
->connect_path
!= NULL
) {
2994 if (strlen(fwd
->connect_path
) > sizeof(sunaddr
.sun_path
)) {
2995 error("Local connecting path too long: %s",
2999 path
= fwd
->connect_path
;
3000 port
= PORT_STREAMLOCAL
;
3002 if (fwd
->connect_host
== NULL
) {
3003 error("No forward host name.");
3006 if (strlen(fwd
->connect_host
) >= NI_MAXHOST
) {
3007 error("Forward host name too long.");
3010 path
= fwd
->connect_host
;
3011 port
= fwd
->connect_port
;
3014 case SSH_CHANNEL_RUNIX_LISTENER
:
3015 path
= fwd
->listen_path
;
3016 port
= PORT_STREAMLOCAL
;
3019 error("%s: unexpected channel type %d", __func__
, type
);
3023 if (fwd
->listen_path
== NULL
) {
3024 error("No forward path name.");
3027 if (strlen(fwd
->listen_path
) > sizeof(sunaddr
.sun_path
)) {
3028 error("Local listening path too long: %s", fwd
->listen_path
);
3032 debug3("%s: type %d path %s", __func__
, type
, fwd
->listen_path
);
3034 /* Start a Unix domain listener. */
3035 omask
= umask(fwd_opts
->streamlocal_bind_mask
);
3036 sock
= unix_listener(fwd
->listen_path
, SSH_LISTEN_BACKLOG
,
3037 fwd_opts
->streamlocal_bind_unlink
);
3042 debug("Local forwarding listening on path %s.", fwd
->listen_path
);
3044 /* Allocate a channel number for the socket. */
3045 c
= channel_new("unix listener", type
, sock
, sock
, -1,
3046 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
3047 0, "unix listener", 1);
3048 c
->path
= xstrdup(path
);
3049 c
->host_port
= port
;
3050 c
->listening_port
= PORT_STREAMLOCAL
;
3051 c
->listening_addr
= xstrdup(fwd
->listen_path
);
3056 channel_cancel_rport_listener_tcpip(const char *host
, u_short port
)
3061 for (i
= 0; i
< channels_alloc
; i
++) {
3062 Channel
*c
= channels
[i
];
3063 if (c
== NULL
|| c
->type
!= SSH_CHANNEL_RPORT_LISTENER
)
3065 if (strcmp(c
->path
, host
) == 0 && c
->listening_port
== port
) {
3066 debug2("%s: close channel %d", __func__
, i
);
3076 channel_cancel_rport_listener_streamlocal(const char *path
)
3081 for (i
= 0; i
< channels_alloc
; i
++) {
3082 Channel
*c
= channels
[i
];
3083 if (c
== NULL
|| c
->type
!= SSH_CHANNEL_RUNIX_LISTENER
)
3085 if (c
->path
== NULL
)
3087 if (strcmp(c
->path
, path
) == 0) {
3088 debug2("%s: close channel %d", __func__
, i
);
3098 channel_cancel_rport_listener(struct Forward
*fwd
)
3100 if (fwd
->listen_path
!= NULL
)
3101 return channel_cancel_rport_listener_streamlocal(fwd
->listen_path
);
3103 return channel_cancel_rport_listener_tcpip(fwd
->listen_host
, fwd
->listen_port
);
3107 channel_cancel_lport_listener_tcpip(const char *lhost
, u_short lport
,
3108 int cport
, struct ForwardOptions
*fwd_opts
)
3112 const char *addr
= channel_fwd_bind_addr(lhost
, NULL
, 1, fwd_opts
);
3114 for (i
= 0; i
< channels_alloc
; i
++) {
3115 Channel
*c
= channels
[i
];
3116 if (c
== NULL
|| c
->type
!= SSH_CHANNEL_PORT_LISTENER
)
3118 if (c
->listening_port
!= lport
)
3120 if (cport
== CHANNEL_CANCEL_PORT_STATIC
) {
3121 /* skip dynamic forwardings */
3122 if (c
->host_port
== 0)
3125 if (c
->host_port
!= cport
)
3128 if ((c
->listening_addr
== NULL
&& addr
!= NULL
) ||
3129 (c
->listening_addr
!= NULL
&& addr
== NULL
))
3131 if (addr
== NULL
|| strcmp(c
->listening_addr
, addr
) == 0) {
3132 debug2("%s: close channel %d", __func__
, i
);
3142 channel_cancel_lport_listener_streamlocal(const char *path
)
3148 error("%s: no path specified.", __func__
);
3152 for (i
= 0; i
< channels_alloc
; i
++) {
3153 Channel
*c
= channels
[i
];
3154 if (c
== NULL
|| c
->type
!= SSH_CHANNEL_UNIX_LISTENER
)
3156 if (c
->listening_addr
== NULL
)
3158 if (strcmp(c
->listening_addr
, path
) == 0) {
3159 debug2("%s: close channel %d", __func__
, i
);
3169 channel_cancel_lport_listener(struct Forward
*fwd
, int cport
, struct ForwardOptions
*fwd_opts
)
3171 if (fwd
->listen_path
!= NULL
)
3172 return channel_cancel_lport_listener_streamlocal(fwd
->listen_path
);
3174 return channel_cancel_lport_listener_tcpip(fwd
->listen_host
, fwd
->listen_port
, cport
, fwd_opts
);
3177 /* protocol local port fwd, used by ssh (and sshd in v1) */
3179 channel_setup_local_fwd_listener(struct Forward
*fwd
, struct ForwardOptions
*fwd_opts
)
3181 if (fwd
->listen_path
!= NULL
) {
3182 return channel_setup_fwd_listener_streamlocal(
3183 SSH_CHANNEL_UNIX_LISTENER
, fwd
, fwd_opts
);
3185 return channel_setup_fwd_listener_tcpip(SSH_CHANNEL_PORT_LISTENER
,
3186 fwd
, NULL
, fwd_opts
);
3190 /* protocol v2 remote port fwd, used by sshd */
3192 channel_setup_remote_fwd_listener(struct Forward
*fwd
,
3193 int *allocated_listen_port
, struct ForwardOptions
*fwd_opts
)
3195 if (fwd
->listen_path
!= NULL
) {
3196 return channel_setup_fwd_listener_streamlocal(
3197 SSH_CHANNEL_RUNIX_LISTENER
, fwd
, fwd_opts
);
3199 return channel_setup_fwd_listener_tcpip(
3200 SSH_CHANNEL_RPORT_LISTENER
, fwd
, allocated_listen_port
,
3206 * Translate the requested rfwd listen host to something usable for
3210 channel_rfwd_bind_host(const char *listen_host
)
3212 if (listen_host
== NULL
) {
3213 if (datafellows
& SSH_BUG_RFWD_ADDR
)
3217 } else if (*listen_host
== '\0' || strcmp(listen_host
, "*") == 0) {
3218 if (datafellows
& SSH_BUG_RFWD_ADDR
)
3227 * Initiate forwarding of connections to port "port" on remote host through
3228 * the secure channel to host:port from local side.
3229 * Returns handle (index) for updating the dynamic listen port with
3230 * channel_update_permitted_opens().
3233 channel_request_remote_forwarding(struct Forward
*fwd
)
3235 int type
, success
= 0, idx
= -1;
3237 /* Send the forward request to the remote side. */
3239 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
3240 if (fwd
->listen_path
!= NULL
) {
3241 packet_put_cstring("streamlocal-forward@openssh.com");
3242 packet_put_char(1); /* boolean: want reply */
3243 packet_put_cstring(fwd
->listen_path
);
3245 packet_put_cstring("tcpip-forward");
3246 packet_put_char(1); /* boolean: want reply */
3247 packet_put_cstring(channel_rfwd_bind_host(fwd
->listen_host
));
3248 packet_put_int(fwd
->listen_port
);
3251 packet_write_wait();
3252 /* Assume that server accepts the request */
3254 } else if (fwd
->listen_path
== NULL
) {
3255 packet_start(SSH_CMSG_PORT_FORWARD_REQUEST
);
3256 packet_put_int(fwd
->listen_port
);
3257 packet_put_cstring(fwd
->connect_host
);
3258 packet_put_int(fwd
->connect_port
);
3260 packet_write_wait();
3262 /* Wait for response from the remote side. */
3263 type
= packet_read();
3265 case SSH_SMSG_SUCCESS
:
3268 case SSH_SMSG_FAILURE
:
3271 /* Unknown packet */
3272 packet_disconnect("Protocol error for port forward request:"
3273 "received packet type %d.", type
);
3276 logit("Warning: Server does not support remote stream local forwarding.");
3279 /* Record that connection to this host/port is permitted. */
3280 permitted_opens
= xrealloc(permitted_opens
,
3281 num_permitted_opens
+ 1, sizeof(*permitted_opens
));
3282 idx
= num_permitted_opens
++;
3283 if (fwd
->connect_path
!= NULL
) {
3284 permitted_opens
[idx
].host_to_connect
=
3285 xstrdup(fwd
->connect_path
);
3286 permitted_opens
[idx
].port_to_connect
=
3289 permitted_opens
[idx
].host_to_connect
=
3290 xstrdup(fwd
->connect_host
);
3291 permitted_opens
[idx
].port_to_connect
=
3294 if (fwd
->listen_path
!= NULL
) {
3295 permitted_opens
[idx
].listen_host
= NULL
;
3296 permitted_opens
[idx
].listen_path
=
3297 xstrdup(fwd
->listen_path
);
3298 permitted_opens
[idx
].listen_port
= PORT_STREAMLOCAL
;
3300 permitted_opens
[idx
].listen_host
=
3301 fwd
->listen_host
? xstrdup(fwd
->listen_host
) : NULL
;
3302 permitted_opens
[idx
].listen_path
= NULL
;
3303 permitted_opens
[idx
].listen_port
= fwd
->listen_port
;
3310 open_match(ForwardPermission
*allowed_open
, const char *requestedhost
,
3313 if (allowed_open
->host_to_connect
== NULL
)
3315 if (allowed_open
->port_to_connect
!= FWD_PERMIT_ANY_PORT
&&
3316 allowed_open
->port_to_connect
!= requestedport
)
3318 if (strcmp(allowed_open
->host_to_connect
, requestedhost
) != 0)
3324 * Note that in the listen host/port case
3325 * we don't support FWD_PERMIT_ANY_PORT and
3326 * need to translate between the configured-host (listen_host)
3327 * and what we've sent to the remote server (channel_rfwd_bind_host)
3330 open_listen_match_tcpip(ForwardPermission
*allowed_open
,
3331 const char *requestedhost
, u_short requestedport
, int translate
)
3333 const char *allowed_host
;
3335 if (allowed_open
->host_to_connect
== NULL
)
3337 if (allowed_open
->listen_port
!= requestedport
)
3339 if (!translate
&& allowed_open
->listen_host
== NULL
&&
3340 requestedhost
== NULL
)
3342 allowed_host
= translate
?
3343 channel_rfwd_bind_host(allowed_open
->listen_host
) :
3344 allowed_open
->listen_host
;
3345 if (allowed_host
== NULL
||
3346 strcmp(allowed_host
, requestedhost
) != 0)
3352 open_listen_match_streamlocal(ForwardPermission
*allowed_open
,
3353 const char *requestedpath
)
3355 if (allowed_open
->host_to_connect
== NULL
)
3357 if (allowed_open
->listen_port
!= PORT_STREAMLOCAL
)
3359 if (allowed_open
->listen_path
== NULL
||
3360 strcmp(allowed_open
->listen_path
, requestedpath
) != 0)
3366 * Request cancellation of remote forwarding of connection host:port from
3370 channel_request_rforward_cancel_tcpip(const char *host
, u_short port
)
3377 for (i
= 0; i
< num_permitted_opens
; i
++) {
3378 if (open_listen_match_tcpip(&permitted_opens
[i
], host
, port
, 0))
3381 if (i
>= num_permitted_opens
) {
3382 debug("%s: requested forward not found", __func__
);
3385 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
3386 packet_put_cstring("cancel-tcpip-forward");
3388 packet_put_cstring(channel_rfwd_bind_host(host
));
3389 packet_put_int(port
);
3392 permitted_opens
[i
].listen_port
= 0;
3393 permitted_opens
[i
].port_to_connect
= 0;
3394 free(permitted_opens
[i
].host_to_connect
);
3395 permitted_opens
[i
].host_to_connect
= NULL
;
3396 free(permitted_opens
[i
].listen_host
);
3397 permitted_opens
[i
].listen_host
= NULL
;
3398 permitted_opens
[i
].listen_path
= NULL
;
3404 * Request cancellation of remote forwarding of Unix domain socket
3405 * path from local side.
3408 channel_request_rforward_cancel_streamlocal(const char *path
)
3415 for (i
= 0; i
< num_permitted_opens
; i
++) {
3416 if (open_listen_match_streamlocal(&permitted_opens
[i
], path
))
3419 if (i
>= num_permitted_opens
) {
3420 debug("%s: requested forward not found", __func__
);
3423 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
3424 packet_put_cstring("cancel-streamlocal-forward@openssh.com");
3426 packet_put_cstring(path
);
3429 permitted_opens
[i
].listen_port
= 0;
3430 permitted_opens
[i
].port_to_connect
= 0;
3431 free(permitted_opens
[i
].host_to_connect
);
3432 permitted_opens
[i
].host_to_connect
= NULL
;
3433 permitted_opens
[i
].listen_host
= NULL
;
3434 free(permitted_opens
[i
].listen_path
);
3435 permitted_opens
[i
].listen_path
= NULL
;
3441 * Request cancellation of remote forwarding of a connection from local side.
3444 channel_request_rforward_cancel(struct Forward
*fwd
)
3446 if (fwd
->listen_path
!= NULL
) {
3447 return (channel_request_rforward_cancel_streamlocal(
3450 return (channel_request_rforward_cancel_tcpip(fwd
->listen_host
,
3451 fwd
->listen_port
? fwd
->listen_port
: fwd
->allocated_port
));
3456 * This is called after receiving CHANNEL_FORWARDING_REQUEST. This initates
3457 * listening for the port, and sends back a success reply (or disconnect
3458 * message if there was an error).
3461 channel_input_port_forward_request(int is_root
, struct ForwardOptions
*fwd_opts
)
3466 /* Get arguments from the packet. */
3467 memset(&fwd
, 0, sizeof(fwd
));
3468 fwd
.listen_port
= packet_get_int();
3469 fwd
.connect_host
= packet_get_string(NULL
);
3470 fwd
.connect_port
= packet_get_int();
3474 * Check that an unprivileged user is not trying to forward a
3477 if (fwd
.listen_port
< IPPORT_RESERVED
&& !is_root
)
3479 "Requested forwarding of port %d but user is not root.",
3481 if (fwd
.connect_port
== 0)
3482 packet_disconnect("Dynamic forwarding denied.");
3485 /* Initiate forwarding */
3486 success
= channel_setup_local_fwd_listener(&fwd
, fwd_opts
);
3488 /* Free the argument string. */
3489 free(fwd
.connect_host
);
3491 return (success
? 0 : -1);
3495 * Permits opening to any host/port if permitted_opens[] is empty. This is
3496 * usually called by the server, because the user could connect to any port
3497 * anyway, and the server has no way to know but to trust the client anyway.
3500 channel_permit_all_opens(void)
3502 if (num_permitted_opens
== 0)
3503 all_opens_permitted
= 1;
3507 channel_add_permitted_opens(char *host
, int port
)
3509 debug("allow port forwarding to host %s port %d", host
, port
);
3511 permitted_opens
= xrealloc(permitted_opens
,
3512 num_permitted_opens
+ 1, sizeof(*permitted_opens
));
3513 permitted_opens
[num_permitted_opens
].host_to_connect
= xstrdup(host
);
3514 permitted_opens
[num_permitted_opens
].port_to_connect
= port
;
3515 permitted_opens
[num_permitted_opens
].listen_host
= NULL
;
3516 permitted_opens
[num_permitted_opens
].listen_path
= NULL
;
3517 permitted_opens
[num_permitted_opens
].listen_port
= 0;
3518 num_permitted_opens
++;
3520 all_opens_permitted
= 0;
3524 * Update the listen port for a dynamic remote forward, after
3525 * the actual 'newport' has been allocated. If 'newport' < 0 is
3526 * passed then they entry will be invalidated.
3529 channel_update_permitted_opens(int idx
, int newport
)
3531 if (idx
< 0 || idx
>= num_permitted_opens
) {
3532 debug("channel_update_permitted_opens: index out of range:"
3533 " %d num_permitted_opens %d", idx
, num_permitted_opens
);
3536 debug("%s allowed port %d for forwarding to host %s port %d",
3537 newport
> 0 ? "Updating" : "Removing",
3539 permitted_opens
[idx
].host_to_connect
,
3540 permitted_opens
[idx
].port_to_connect
);
3542 permitted_opens
[idx
].listen_port
=
3543 (datafellows
& SSH_BUG_DYNAMIC_RPORT
) ? 0 : newport
;
3545 permitted_opens
[idx
].listen_port
= 0;
3546 permitted_opens
[idx
].port_to_connect
= 0;
3547 free(permitted_opens
[idx
].host_to_connect
);
3548 permitted_opens
[idx
].host_to_connect
= NULL
;
3549 free(permitted_opens
[idx
].listen_host
);
3550 permitted_opens
[idx
].listen_host
= NULL
;
3551 free(permitted_opens
[idx
].listen_path
);
3552 permitted_opens
[idx
].listen_path
= NULL
;
3557 channel_add_adm_permitted_opens(char *host
, int port
)
3559 debug("config allows port forwarding to host %s port %d", host
, port
);
3561 permitted_adm_opens
= xrealloc(permitted_adm_opens
,
3562 num_adm_permitted_opens
+ 1, sizeof(*permitted_adm_opens
));
3563 permitted_adm_opens
[num_adm_permitted_opens
].host_to_connect
3565 permitted_adm_opens
[num_adm_permitted_opens
].port_to_connect
= port
;
3566 permitted_adm_opens
[num_adm_permitted_opens
].listen_host
= NULL
;
3567 permitted_adm_opens
[num_adm_permitted_opens
].listen_path
= NULL
;
3568 permitted_adm_opens
[num_adm_permitted_opens
].listen_port
= 0;
3569 return ++num_adm_permitted_opens
;
3573 channel_disable_adm_local_opens(void)
3575 channel_clear_adm_permitted_opens();
3576 permitted_adm_opens
= xmalloc(sizeof(*permitted_adm_opens
));
3577 permitted_adm_opens
[num_adm_permitted_opens
].host_to_connect
= NULL
;
3578 num_adm_permitted_opens
= 1;
3582 channel_clear_permitted_opens(void)
3586 for (i
= 0; i
< num_permitted_opens
; i
++) {
3587 free(permitted_opens
[i
].host_to_connect
);
3588 free(permitted_opens
[i
].listen_host
);
3589 free(permitted_opens
[i
].listen_path
);
3591 free(permitted_opens
);
3592 permitted_opens
= NULL
;
3593 num_permitted_opens
= 0;
3597 channel_clear_adm_permitted_opens(void)
3601 for (i
= 0; i
< num_adm_permitted_opens
; i
++) {
3602 free(permitted_adm_opens
[i
].host_to_connect
);
3603 free(permitted_adm_opens
[i
].listen_host
);
3604 free(permitted_adm_opens
[i
].listen_path
);
3606 free(permitted_adm_opens
);
3607 permitted_adm_opens
= NULL
;
3608 num_adm_permitted_opens
= 0;
3612 channel_print_adm_permitted_opens(void)
3616 printf("permitopen");
3617 if (num_adm_permitted_opens
== 0) {
3621 for (i
= 0; i
< num_adm_permitted_opens
; i
++)
3622 if (permitted_adm_opens
[i
].host_to_connect
== NULL
)
3625 printf(" %s:%d", permitted_adm_opens
[i
].host_to_connect
,
3626 permitted_adm_opens
[i
].port_to_connect
);
3630 /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
3632 permitopen_port(const char *p
)
3636 if (strcmp(p
, "*") == 0)
3637 return FWD_PERMIT_ANY_PORT
;
3638 if ((port
= a2port(p
)) > 0)
3643 /* Try to start non-blocking connect to next host in cctx list */
3645 connect_next(struct channel_connect
*cctx
)
3647 int sock
, saved_errno
;
3648 struct sockaddr_un
*sunaddr
;
3649 char ntop
[NI_MAXHOST
], strport
[MAX(NI_MAXSERV
,sizeof(sunaddr
->sun_path
))];
3651 for (; cctx
->ai
; cctx
->ai
= cctx
->ai
->ai_next
) {
3652 switch (cctx
->ai
->ai_family
) {
3654 /* unix:pathname instead of host:port */
3655 sunaddr
= (struct sockaddr_un
*)cctx
->ai
->ai_addr
;
3656 strlcpy(ntop
, "unix", sizeof(ntop
));
3657 strlcpy(strport
, sunaddr
->sun_path
, sizeof(strport
));
3661 if (getnameinfo(cctx
->ai
->ai_addr
, cctx
->ai
->ai_addrlen
,
3662 ntop
, sizeof(ntop
), strport
, sizeof(strport
),
3663 NI_NUMERICHOST
|NI_NUMERICSERV
) != 0) {
3664 error("connect_next: getnameinfo failed");
3671 if ((sock
= socket(cctx
->ai
->ai_family
, cctx
->ai
->ai_socktype
,
3672 cctx
->ai
->ai_protocol
)) == -1) {
3673 if (cctx
->ai
->ai_next
== NULL
)
3674 error("socket: %.100s", strerror(errno
));
3676 verbose("socket: %.100s", strerror(errno
));
3679 if (set_nonblock(sock
) == -1)
3680 fatal("%s: set_nonblock(%d)", __func__
, sock
);
3681 if (connect(sock
, cctx
->ai
->ai_addr
,
3682 cctx
->ai
->ai_addrlen
) == -1 && errno
!= EINPROGRESS
) {
3683 debug("connect_next: host %.100s ([%.100s]:%s): "
3684 "%.100s", cctx
->host
, ntop
, strport
,
3686 saved_errno
= errno
;
3688 errno
= saved_errno
;
3689 continue; /* fail -- try next */
3691 if (cctx
->ai
->ai_family
!= AF_UNIX
)
3693 debug("connect_next: host %.100s ([%.100s]:%s) "
3694 "in progress, fd=%d", cctx
->host
, ntop
, strport
, sock
);
3695 cctx
->ai
= cctx
->ai
->ai_next
;
3702 channel_connect_ctx_free(struct channel_connect
*cctx
)
3706 if (cctx
->aitop
->ai_family
== AF_UNIX
)
3709 freeaddrinfo(cctx
->aitop
);
3711 memset(cctx
, 0, sizeof(*cctx
));
3714 /* Return CONNECTING channel to remote host:port or local socket path */
3716 connect_to(const char *name
, int port
, char *ctype
, char *rname
)
3718 struct addrinfo hints
;
3721 char strport
[NI_MAXSERV
];
3722 struct channel_connect cctx
;
3725 memset(&cctx
, 0, sizeof(cctx
));
3727 if (port
== PORT_STREAMLOCAL
) {
3728 struct sockaddr_un
*sunaddr
;
3729 struct addrinfo
*ai
;
3731 if (strlen(name
) > sizeof(sunaddr
->sun_path
)) {
3732 error("%.100s: %.100s", name
, strerror(ENAMETOOLONG
));
3737 * Fake up a struct addrinfo for AF_UNIX connections.
3738 * channel_connect_ctx_free() must check ai_family
3739 * and use free() not freeaddirinfo() for AF_UNIX.
3741 ai
= xmalloc(sizeof(*ai
) + sizeof(*sunaddr
));
3742 memset(ai
, 0, sizeof(*ai
) + sizeof(*sunaddr
));
3743 ai
->ai_addr
= (struct sockaddr
*)(ai
+ 1);
3744 ai
->ai_addrlen
= sizeof(*sunaddr
);
3745 ai
->ai_family
= AF_UNIX
;
3746 ai
->ai_socktype
= SOCK_STREAM
;
3747 ai
->ai_protocol
= PF_UNSPEC
;
3748 sunaddr
= (struct sockaddr_un
*)ai
->ai_addr
;
3749 sunaddr
->sun_family
= AF_UNIX
;
3750 strlcpy(sunaddr
->sun_path
, name
, sizeof(sunaddr
->sun_path
));
3753 memset(&hints
, 0, sizeof(hints
));
3754 hints
.ai_family
= IPv4or6
;
3755 hints
.ai_socktype
= SOCK_STREAM
;
3756 snprintf(strport
, sizeof strport
, "%d", port
);
3757 if ((gaierr
= getaddrinfo(name
, strport
, &hints
, &cctx
.aitop
)) != 0) {
3758 error("connect_to %.100s: unknown host (%s)", name
,
3759 ssh_gai_strerror(gaierr
));
3764 cctx
.host
= xstrdup(name
);
3766 cctx
.ai
= cctx
.aitop
;
3768 if ((sock
= connect_next(&cctx
)) == -1) {
3769 error("connect to %.100s port %d failed: %s",
3770 name
, port
, strerror(errno
));
3771 channel_connect_ctx_free(&cctx
);
3774 c
= channel_new(ctype
, SSH_CHANNEL_CONNECTING
, sock
, sock
, -1,
3775 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
, 0, rname
, 1);
3776 c
->connect_ctx
= cctx
;
3781 channel_connect_by_listen_address(const char *listen_host
,
3782 u_short listen_port
, char *ctype
, char *rname
)
3786 for (i
= 0; i
< num_permitted_opens
; i
++) {
3787 if (open_listen_match_tcpip(&permitted_opens
[i
], listen_host
,
3790 permitted_opens
[i
].host_to_connect
,
3791 permitted_opens
[i
].port_to_connect
, ctype
, rname
);
3794 error("WARNING: Server requests forwarding for unknown listen_port %d",
3800 channel_connect_by_listen_path(const char *path
, char *ctype
, char *rname
)
3804 for (i
= 0; i
< num_permitted_opens
; i
++) {
3805 if (open_listen_match_streamlocal(&permitted_opens
[i
], path
)) {
3807 permitted_opens
[i
].host_to_connect
,
3808 permitted_opens
[i
].port_to_connect
, ctype
, rname
);
3811 error("WARNING: Server requests forwarding for unknown path %.100s",
3816 /* Check if connecting to that port is permitted and connect. */
3818 channel_connect_to_port(const char *host
, u_short port
, char *ctype
, char *rname
)
3820 int i
, permit
, permit_adm
= 1;
3822 permit
= all_opens_permitted
;
3824 for (i
= 0; i
< num_permitted_opens
; i
++)
3825 if (open_match(&permitted_opens
[i
], host
, port
)) {
3831 if (num_adm_permitted_opens
> 0) {
3833 for (i
= 0; i
< num_adm_permitted_opens
; i
++)
3834 if (open_match(&permitted_adm_opens
[i
], host
, port
)) {
3840 if (!permit
|| !permit_adm
) {
3841 logit("Received request to connect to host %.100s port %d, "
3842 "but the request was denied.", host
, port
);
3845 return connect_to(host
, port
, ctype
, rname
);
3848 /* Check if connecting to that path is permitted and connect. */
3850 channel_connect_to_path(const char *path
, char *ctype
, char *rname
)
3852 int i
, permit
, permit_adm
= 1;
3854 permit
= all_opens_permitted
;
3856 for (i
= 0; i
< num_permitted_opens
; i
++)
3857 if (open_match(&permitted_opens
[i
], path
, PORT_STREAMLOCAL
)) {
3863 if (num_adm_permitted_opens
> 0) {
3865 for (i
= 0; i
< num_adm_permitted_opens
; i
++)
3866 if (open_match(&permitted_adm_opens
[i
], path
, PORT_STREAMLOCAL
)) {
3872 if (!permit
|| !permit_adm
) {
3873 logit("Received request to connect to path %.100s, "
3874 "but the request was denied.", path
);
3877 return connect_to(path
, PORT_STREAMLOCAL
, ctype
, rname
);
3881 channel_send_window_changes(void)
3886 for (i
= 0; i
< channels_alloc
; i
++) {
3887 if (channels
[i
] == NULL
|| !channels
[i
]->client_tty
||
3888 channels
[i
]->type
!= SSH_CHANNEL_OPEN
)
3890 if (ioctl(channels
[i
]->rfd
, TIOCGWINSZ
, &ws
) < 0)
3892 channel_request_start(i
, "window-change", 0);
3893 packet_put_int((u_int
)ws
.ws_col
);
3894 packet_put_int((u_int
)ws
.ws_row
);
3895 packet_put_int((u_int
)ws
.ws_xpixel
);
3896 packet_put_int((u_int
)ws
.ws_ypixel
);
3901 /* -- X11 forwarding */
3904 * Creates an internet domain socket for listening for X11 connections.
3905 * Returns 0 and a suitable display number for the DISPLAY variable
3906 * stored in display_numberp , or -1 if an error occurs.
3909 x11_create_display_inet(int x11_display_offset
, int x11_use_localhost
,
3910 int single_connection
, u_int
*display_numberp
, int **chanids
)
3913 int display_number
, sock
;
3915 struct addrinfo hints
, *ai
, *aitop
;
3916 char strport
[NI_MAXSERV
];
3917 int gaierr
, n
, num_socks
= 0, socks
[NUM_SOCKS
];
3919 if (chanids
== NULL
)
3922 for (display_number
= x11_display_offset
;
3923 display_number
< MAX_DISPLAYS
;
3925 port
= 6000 + display_number
;
3926 memset(&hints
, 0, sizeof(hints
));
3927 hints
.ai_family
= IPv4or6
;
3928 hints
.ai_flags
= x11_use_localhost
? 0: AI_PASSIVE
;
3929 hints
.ai_socktype
= SOCK_STREAM
;
3930 snprintf(strport
, sizeof strport
, "%d", port
);
3931 if ((gaierr
= getaddrinfo(NULL
, strport
, &hints
, &aitop
)) != 0) {
3932 error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr
));
3935 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
3936 if (ai
->ai_family
!= AF_INET
&& ai
->ai_family
!= AF_INET6
)
3938 sock
= socket(ai
->ai_family
, ai
->ai_socktype
,
3941 if ((errno
!= EINVAL
) && (errno
!= EAFNOSUPPORT
)
3943 && (errno
!= EPFNOSUPPORT
)
3946 error("socket: %.100s", strerror(errno
));
3947 freeaddrinfo(aitop
);
3950 debug("x11_create_display_inet: Socket family %d not supported",
3955 if (ai
->ai_family
== AF_INET6
)
3956 sock_set_v6only(sock
);
3957 if (x11_use_localhost
)
3958 channel_set_reuseaddr(sock
);
3959 if (bind(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
3960 debug2("bind port %d: %.100s", port
, strerror(errno
));
3963 for (n
= 0; n
< num_socks
; n
++) {
3969 socks
[num_socks
++] = sock
;
3970 if (num_socks
== NUM_SOCKS
)
3973 freeaddrinfo(aitop
);
3977 if (display_number
>= MAX_DISPLAYS
) {
3978 error("Failed to allocate internet-domain X11 display socket.");
3981 /* Start listening for connections on the socket. */
3982 for (n
= 0; n
< num_socks
; n
++) {
3984 if (listen(sock
, SSH_LISTEN_BACKLOG
) < 0) {
3985 error("listen: %.100s", strerror(errno
));
3991 /* Allocate a channel for each socket. */
3992 *chanids
= xcalloc(num_socks
+ 1, sizeof(**chanids
));
3993 for (n
= 0; n
< num_socks
; n
++) {
3995 /* Is this really necassary? */
3997 nc
= channel_new("x11 listener",
3998 SSH_CHANNEL_X11_LISTENER
, sock
, sock
, -1,
3999 CHAN_X11_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
,
4000 0, "X11 inet listener", 1);
4002 nc
= channel_new("x11 listener",
4003 SSH_CHANNEL_X11_LISTENER
, sock
, sock
, -1,
4004 hpn_buffer_size
, CHAN_X11_PACKET_DEFAULT
,
4005 0, "X11 inet listener", 1);
4006 nc
->single_connection
= single_connection
;
4007 (*chanids
)[n
] = nc
->self
;
4011 /* Return the display number for the DISPLAY environment variable. */
4012 *display_numberp
= display_number
;
4017 connect_local_xsocket_path(const char *pathname
)
4020 struct sockaddr_un addr
;
4022 sock
= socket(AF_UNIX
, SOCK_STREAM
, 0);
4024 error("socket: %.100s", strerror(errno
));
4025 memset(&addr
, 0, sizeof(addr
));
4026 addr
.sun_family
= AF_UNIX
;
4027 strlcpy(addr
.sun_path
, pathname
, sizeof addr
.sun_path
);
4028 if (connect(sock
, (struct sockaddr
*)&addr
, sizeof(addr
)) == 0)
4031 error("connect %.100s: %.100s", addr
.sun_path
, strerror(errno
));
4036 connect_local_xsocket(u_int dnr
)
4039 snprintf(buf
, sizeof buf
, _PATH_UNIX_X
, dnr
);
4040 return connect_local_xsocket_path(buf
);
4044 x11_connect_display(void)
4046 u_int display_number
;
4047 const char *display
;
4048 char buf
[1024], *cp
;
4049 struct addrinfo hints
, *ai
, *aitop
;
4050 char strport
[NI_MAXSERV
];
4051 int gaierr
, sock
= 0;
4053 /* Try to open a socket for the local X server. */
4054 display
= getenv("DISPLAY");
4056 error("DISPLAY not set.");
4060 * Now we decode the value of the DISPLAY variable and make a
4061 * connection to the real X server.
4064 /* Check if the display is from launchd. */
4066 if (strncmp(display
, "/tmp/launch", 11) == 0) {
4067 sock
= connect_local_xsocket_path(display
);
4071 /* OK, we now have a connection to the display. */
4076 * Check if it is a unix domain socket. Unix domain displays are in
4077 * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
4079 if (strncmp(display
, "unix:", 5) == 0 ||
4080 display
[0] == ':') {
4081 /* Connect to the unix domain socket. */
4082 if (sscanf(strrchr(display
, ':') + 1, "%u", &display_number
) != 1) {
4083 error("Could not parse display number from DISPLAY: %.100s",
4087 /* Create a socket. */
4088 sock
= connect_local_xsocket(display_number
);
4092 /* OK, we now have a connection to the display. */
4096 * Connect to an inet socket. The DISPLAY value is supposedly
4097 * hostname:d[.s], where hostname may also be numeric IP address.
4099 strlcpy(buf
, display
, sizeof(buf
));
4100 cp
= strchr(buf
, ':');
4102 error("Could not find ':' in DISPLAY: %.100s", display
);
4106 /* buf now contains the host name. But first we parse the display number. */
4107 if (sscanf(cp
+ 1, "%u", &display_number
) != 1) {
4108 error("Could not parse display number from DISPLAY: %.100s",
4113 /* Look up the host address */
4114 memset(&hints
, 0, sizeof(hints
));
4115 hints
.ai_family
= IPv4or6
;
4116 hints
.ai_socktype
= SOCK_STREAM
;
4117 snprintf(strport
, sizeof strport
, "%u", 6000 + display_number
);
4118 if ((gaierr
= getaddrinfo(buf
, strport
, &hints
, &aitop
)) != 0) {
4119 error("%.100s: unknown host. (%s)", buf
,
4120 ssh_gai_strerror(gaierr
));
4123 for (ai
= aitop
; ai
; ai
= ai
->ai_next
) {
4124 /* Create a socket. */
4125 sock
= socket(ai
->ai_family
, ai
->ai_socktype
, ai
->ai_protocol
);
4127 debug2("socket: %.100s", strerror(errno
));
4130 /* Connect it to the display. */
4131 if (connect(sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
4132 debug2("connect %.100s port %u: %.100s", buf
,
4133 6000 + display_number
, strerror(errno
));
4140 freeaddrinfo(aitop
);
4142 error("connect %.100s port %u: %.100s", buf
, 6000 + display_number
,
4151 * This is called when SSH_SMSG_X11_OPEN is received. The packet contains
4152 * the remote channel number. We should do whatever we want, and respond
4153 * with either SSH_MSG_OPEN_CONFIRMATION or SSH_MSG_OPEN_FAILURE.
4158 x11_input_open(int type
, u_int32_t seq
, void *ctxt
)
4161 int remote_id
, sock
= 0;
4164 debug("Received X11 open request.");
4166 remote_id
= packet_get_int();
4168 if (packet_get_protocol_flags() & SSH_PROTOFLAG_HOST_IN_FWD_OPEN
) {
4169 remote_host
= packet_get_string(NULL
);
4171 remote_host
= xstrdup("unknown (remote did not supply name)");
4175 /* Obtain a connection to the real X display. */
4176 sock
= x11_connect_display();
4178 /* Allocate a channel for this connection. */
4179 c
= channel_new("connected x11 socket",
4180 SSH_CHANNEL_X11_OPEN
, sock
, sock
, -1, 0, 0, 0,
4182 c
->remote_id
= remote_id
;
4187 /* Send refusal to the remote host. */
4188 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
4189 packet_put_int(remote_id
);
4191 /* Send a confirmation to the remote host. */
4192 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
4193 packet_put_int(remote_id
);
4194 packet_put_int(c
->self
);
4199 /* dummy protocol handler that denies SSH-1 requests (agent/x11) */
4202 deny_input_open(int type
, u_int32_t seq
, void *ctxt
)
4204 int rchan
= packet_get_int();
4207 case SSH_SMSG_AGENT_OPEN
:
4208 error("Warning: ssh server tried agent forwarding.");
4210 case SSH_SMSG_X11_OPEN
:
4211 error("Warning: ssh server tried X11 forwarding.");
4214 error("deny_input_open: type %d", type
);
4217 error("Warning: this is probably a break-in attempt by a malicious server.");
4218 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
4219 packet_put_int(rchan
);
4224 * Requests forwarding of X11 connections, generates fake authentication
4225 * data, and enables authentication spoofing.
4226 * This should be called in the client only.
4229 x11_request_forwarding_with_spoofing(int client_session_id
, const char *disp
,
4230 const char *proto
, const char *data
, int want_reply
)
4232 u_int data_len
= (u_int
) strlen(data
) / 2;
4239 if (x11_saved_display
== NULL
)
4240 x11_saved_display
= xstrdup(disp
);
4241 else if (strcmp(disp
, x11_saved_display
) != 0) {
4242 error("x11_request_forwarding_with_spoofing: different "
4243 "$DISPLAY already forwarded");
4247 cp
= strchr(disp
, ':');
4249 cp
= strchr(cp
, '.');
4251 screen_number
= (u_int
)strtonum(cp
+ 1, 0, 400, NULL
);
4255 if (x11_saved_proto
== NULL
) {
4256 /* Save protocol name. */
4257 x11_saved_proto
= xstrdup(proto
);
4259 * Extract real authentication data and generate fake data
4260 * of the same length.
4262 x11_saved_data
= xmalloc(data_len
);
4263 x11_fake_data
= xmalloc(data_len
);
4264 for (i
= 0; i
< data_len
; i
++) {
4265 if (sscanf(data
+ 2 * i
, "%2x", &value
) != 1)
4266 fatal("x11_request_forwarding: bad "
4267 "authentication data: %.100s", data
);
4270 x11_saved_data
[i
] = value
;
4271 x11_fake_data
[i
] = rnd
& 0xff;
4274 x11_saved_data_len
= data_len
;
4275 x11_fake_data_len
= data_len
;
4278 /* Convert the fake data into hex. */
4279 new_data
= tohex(x11_fake_data
, data_len
);
4281 /* Send the request packet. */
4283 channel_request_start(client_session_id
, "x11-req", want_reply
);
4284 packet_put_char(0); /* XXX bool single connection */
4286 packet_start(SSH_CMSG_X11_REQUEST_FORWARDING
);
4288 packet_put_cstring(proto
);
4289 packet_put_cstring(new_data
);
4290 packet_put_int(screen_number
);
4292 packet_write_wait();
4297 /* -- agent forwarding */
4299 /* Sends a message to the server to request authentication fd forwarding. */
4302 auth_request_forwarding(void)
4304 packet_start(SSH_CMSG_AGENT_REQUEST_FORWARDING
);
4306 packet_write_wait();