1 /* $OpenBSD: clientloop.c,v 1.236 2011/06/22 22:08:42 djm Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
6 * The main loop for the interactive session (client side).
8 * As far as I am concerned, the code I have written for this software
9 * can be used freely for any purpose. Any derived versions of this
10 * software must be clearly marked as such, and if the derived work is
11 * incompatible with the protocol description in the RFC file, it must be
12 * called by a name other than "ssh" or "Secure Shell".
15 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions
20 * 1. Redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer.
22 * 2. Redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution.
26 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * SSH2 support added by Markus Friedl.
39 * Copyright (c) 1999, 2000, 2001 Markus Friedl. All rights reserved.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
50 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
51 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
52 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
53 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
54 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
55 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
56 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
57 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
58 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
59 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64 #include <sys/types.h>
65 #include <sys/ioctl.h>
66 #include <sys/param.h>
67 #ifdef HAVE_SYS_STAT_H
68 # include <sys/stat.h>
70 #ifdef HAVE_SYS_TIME_H
71 # include <sys/time.h>
73 #include <sys/socket.h>
89 #include "openbsd-compat/sys-queue.h"
103 #include "readconf.h"
104 #include "clientloop.h"
105 #include "sshconnect.h"
107 #include "atomicio.h"
115 extern Options options
;
117 /* Flag indicating that stdin should be redirected from /dev/null. */
118 extern int stdin_null_flag
;
120 /* Flag indicating that no shell has been requested */
121 extern int no_shell_flag
;
124 extern int muxserver_sock
; /* XXX use mux_client_cleanup() instead */
127 * Name of the host we are connecting to. This is the name given on the
128 * command line, or the HostName specified for the user-supplied name in a
129 * configuration file.
134 * Flag to indicate that we have received a window change signal which has
135 * not yet been processed. This will cause a message indicating the new
136 * window size to be sent to the server a little later. This is volatile
137 * because this is updated in a signal handler.
139 static volatile sig_atomic_t received_window_change_signal
= 0;
140 static volatile sig_atomic_t received_signal
= 0;
142 /* Flag indicating whether the user's terminal is in non-blocking mode. */
143 static int in_non_blocking_mode
= 0;
145 /* Time when backgrounded control master using ControlPersist should exit */
146 static time_t control_persist_exit_time
= 0;
148 /* Common data for the client loop code. */
149 volatile sig_atomic_t quit_pending
; /* Set non-zero to quit the loop. */
150 static int escape_char1
; /* Escape character. (proto1 only) */
151 static int escape_pending1
; /* Last character was an escape (proto1 only) */
152 static int last_was_cr
; /* Last character was a newline. */
153 static int exit_status
; /* Used to store the command exit status. */
154 static int stdin_eof
; /* EOF has been encountered on stderr. */
155 static Buffer stdin_buffer
; /* Buffer for stdin data. */
156 static Buffer stdout_buffer
; /* Buffer for stdout data. */
157 static Buffer stderr_buffer
; /* Buffer for stderr data. */
158 static u_int buffer_high
; /* Soft max buffer size. */
159 static int connection_in
; /* Connection to server (input). */
160 static int connection_out
; /* Connection to server (output). */
161 static int need_rekeying
; /* Set to non-zero if rekeying is requested. */
162 static int session_closed
; /* In SSH2: login session closed. */
163 static int x11_refuse_time
; /* If >0, refuse x11 opens after this time. */
165 static void client_init_dispatch(void);
166 int session_ident
= -1;
168 int session_resumed
= 0;
170 /* Track escape per proto2 channel */
171 struct escape_filter_ctx
{
176 /* Context for channel confirmation replies */
177 struct channel_reply_ctx
{
178 const char *request_type
;
180 enum confirm_action action
;
183 /* Global request success/failure callbacks */
184 struct global_confirm
{
185 TAILQ_ENTRY(global_confirm
) entry
;
186 global_confirm_cb
*cb
;
190 TAILQ_HEAD(global_confirms
, global_confirm
);
191 static struct global_confirms global_confirms
=
192 TAILQ_HEAD_INITIALIZER(global_confirms
);
197 void ssh_process_session2_setup(int, int, int, Buffer
*);
199 /* Restores stdin to blocking mode. */
202 leave_non_blocking(void)
204 if (in_non_blocking_mode
) {
205 unset_nonblock(fileno(stdin
));
206 in_non_blocking_mode
= 0;
210 /* Puts stdin terminal in non-blocking mode. */
213 enter_non_blocking(void)
215 in_non_blocking_mode
= 1;
216 set_nonblock(fileno(stdin
));
220 * Signal handler for the window change signal (SIGWINCH). This just sets a
221 * flag indicating that the window has changed.
225 window_change_handler(int sig
)
227 received_window_change_signal
= 1;
228 signal(SIGWINCH
, window_change_handler
);
232 * Signal handler for signals that cause the program to terminate. These
233 * signals must be trapped to restore terminal modes.
237 signal_handler(int sig
)
239 received_signal
= sig
;
244 * Returns current time in seconds from Jan 1, 1970 with the maximum
245 * available resolution.
249 get_current_time(void)
252 gettimeofday(&tv
, NULL
);
253 return (double) tv
.tv_sec
+ (double) tv
.tv_usec
/ 1000000.0;
257 * Sets control_persist_exit_time to the absolute time when the
258 * backgrounded control master should exit due to expiry of the
259 * ControlPersist timeout. Sets it to 0 if we are not a backgrounded
260 * control master process, or if there is no ControlPersist timeout.
263 set_control_persist_exit_time(void)
265 if (muxserver_sock
== -1 || !options
.control_persist
266 || options
.control_persist_timeout
== 0) {
267 /* not using a ControlPersist timeout */
268 control_persist_exit_time
= 0;
269 } else if (channel_still_open()) {
270 /* some client connections are still open */
271 if (control_persist_exit_time
> 0)
272 debug2("%s: cancel scheduled exit", __func__
);
273 control_persist_exit_time
= 0;
274 } else if (control_persist_exit_time
<= 0) {
275 /* a client connection has recently closed */
276 control_persist_exit_time
= time(NULL
) +
277 (time_t)options
.control_persist_timeout
;
278 debug2("%s: schedule exit in %d seconds", __func__
,
279 options
.control_persist_timeout
);
281 /* else we are already counting down to the timeout */
284 #define SSH_X11_PROTO "MIT-MAGIC-COOKIE-1"
286 client_x11_get_proto(const char *display
, const char *xauth_path
,
287 u_int trusted
, u_int timeout
, char **_proto
, char **_data
)
292 static char proto
[512], data
[512];
294 int got_data
= 0, generated
= 0, do_unlink
= 0, i
;
295 char *xauthdir
, *xauthfile
;
299 xauthdir
= xauthfile
= NULL
;
302 proto
[0] = data
[0] = '\0';
304 if (xauth_path
== NULL
||(stat(xauth_path
, &st
) == -1)) {
305 debug("No xauth program.");
307 if (display
== NULL
) {
308 debug("x11_get_proto: DISPLAY not set");
312 * Handle FamilyLocal case where $DISPLAY does
313 * not match an authorization entry. For this we
314 * just try "xauth list unix:displaynum.screennum".
315 * XXX: "localhost" match to determine FamilyLocal
318 if (strncmp(display
, "localhost:", 10) == 0) {
319 snprintf(xdisplay
, sizeof(xdisplay
), "unix:%s",
324 xauthdir
= xmalloc(MAXPATHLEN
);
325 xauthfile
= xmalloc(MAXPATHLEN
);
326 mktemp_proto(xauthdir
, MAXPATHLEN
);
327 if (mkdtemp(xauthdir
) != NULL
) {
329 snprintf(xauthfile
, MAXPATHLEN
, "%s/xauthfile",
331 snprintf(cmd
, sizeof(cmd
),
332 "%s -f %s generate %s " SSH_X11_PROTO
333 " untrusted timeout %u 2>" _PATH_DEVNULL
,
334 xauth_path
, xauthfile
, display
, timeout
);
335 debug2("x11_get_proto: %s", cmd
);
336 if (system(cmd
) == 0)
338 if (x11_refuse_time
== 0) {
339 now
= time(NULL
) + 1;
340 if (UINT_MAX
- timeout
< now
)
341 x11_refuse_time
= UINT_MAX
;
343 x11_refuse_time
= now
+ timeout
;
349 * When in untrusted mode, we read the cookie only if it was
350 * successfully generated as an untrusted one in the step
353 if (trusted
|| generated
) {
354 snprintf(cmd
, sizeof(cmd
),
355 "%s %s%s list %s 2>" _PATH_DEVNULL
,
357 generated
? "-f " : "" ,
358 generated
? xauthfile
: "",
360 debug2("x11_get_proto: %s", cmd
);
362 if (f
&& fgets(line
, sizeof(line
), f
) &&
363 sscanf(line
, "%*s %511s %511s", proto
, data
) == 2)
368 error("Warning: untrusted X11 forwarding setup failed: "
369 "xauth key data not generated");
382 * If we didn't get authentication data, just make up some
383 * data. The forwarding code will check the validity of the
384 * response anyway, and substitute this data. The X11
385 * server, however, will ignore this fake data and use
386 * whatever authentication mechanisms it was using otherwise
387 * for the local connection.
392 logit("Warning: No xauth data; "
393 "using fake authentication data for X11 forwarding.");
394 strlcpy(proto
, SSH_X11_PROTO
, sizeof proto
);
395 for (i
= 0; i
< 16; i
++) {
398 snprintf(data
+ 2 * i
, sizeof data
- 2 * i
, "%02x",
406 * This is called when the interactive is entered. This checks if there is
407 * an EOF coming on stdin. We must check this explicitly, as select() does
408 * not appear to wake up when redirecting from /dev/null.
412 client_check_initial_eof_on_stdin(void)
418 * If standard input is to be "redirected from /dev/null", we simply
419 * mark that we have seen an EOF and send an EOF message to the
420 * server. Otherwise, we try to read a single character; it appears
421 * that for some files, such /dev/null, select() never wakes up for
422 * read for this descriptor, which means that we never get EOF. This
423 * way we will get the EOF if stdin comes from /dev/null or similar.
425 if (stdin_null_flag
) {
426 /* Fake EOF on stdin. */
427 debug("Sending eof.");
429 packet_start(SSH_CMSG_EOF
);
432 enter_non_blocking();
434 /* Check for immediate EOF on stdin. */
435 len
= read(fileno(stdin
), buf
, 1);
438 * EOF. Record that we have seen it and send
441 debug("Sending eof.");
443 packet_start(SSH_CMSG_EOF
);
445 } else if (len
> 0) {
447 * Got data. We must store the data in the buffer,
448 * and also process it as an escape character if
451 if ((u_char
) buf
[0] == escape_char1
)
454 buffer_append(&stdin_buffer
, buf
, 1);
456 leave_non_blocking();
462 * Make packets from buffered stdin data, and buffer them for sending to the
467 client_make_packets_from_stdin_data(void)
471 /* Send buffered stdin data to the server. */
472 while (buffer_len(&stdin_buffer
) > 0 &&
473 packet_not_very_much_data_to_write()) {
474 len
= buffer_len(&stdin_buffer
);
475 /* Keep the packets at reasonable size. */
476 if (len
> packet_get_maxsize())
477 len
= packet_get_maxsize();
478 packet_start(SSH_CMSG_STDIN_DATA
);
479 packet_put_string(buffer_ptr(&stdin_buffer
), len
);
481 buffer_consume(&stdin_buffer
, len
);
482 /* If we have a pending EOF, send it now. */
483 if (stdin_eof
&& buffer_len(&stdin_buffer
) == 0) {
484 packet_start(SSH_CMSG_EOF
);
491 * Checks if the client window has changed, and sends a packet about it to
492 * the server if so. The actual change is detected elsewhere (by a software
493 * interrupt on Unix); this just checks the flag and sends a message if
498 client_check_window_change(void)
502 if (! received_window_change_signal
)
505 received_window_change_signal
= 0;
507 debug2("client_check_window_change: changed");
510 channel_send_window_changes();
512 if (ioctl(fileno(stdin
), TIOCGWINSZ
, &ws
) < 0)
514 packet_start(SSH_CMSG_WINDOW_SIZE
);
515 packet_put_int((u_int
)ws
.ws_row
);
516 packet_put_int((u_int
)ws
.ws_col
);
517 packet_put_int((u_int
)ws
.ws_xpixel
);
518 packet_put_int((u_int
)ws
.ws_ypixel
);
524 client_global_request_reply(int type
, u_int32_t seq
, void *ctxt
)
526 struct global_confirm
*gc
;
528 if ((gc
= TAILQ_FIRST(&global_confirms
)) == NULL
)
531 gc
->cb(type
, seq
, gc
->ctx
);
532 if (--gc
->ref_count
<= 0) {
533 TAILQ_REMOVE(&global_confirms
, gc
, entry
);
534 bzero(gc
, sizeof(*gc
));
538 packet_set_alive_timeouts(0);
542 server_alive_check(void)
544 if (packet_inc_alive_timeouts() > options
.server_alive_count_max
) {
545 logit("Timeout, server %s not responding.", host
);
548 packet_start(SSH2_MSG_GLOBAL_REQUEST
);
549 packet_put_cstring("keepalive@openssh.com");
550 packet_put_char(1); /* boolean: want reply */
552 /* Insert an empty placeholder to maintain ordering */
553 client_register_global_confirm(NULL
, NULL
);
557 * Waits until the client can do something (some data becomes available on
558 * one of the file descriptors).
561 client_wait_until_can_do_something(fd_set
**readsetp
, fd_set
**writesetp
,
562 int *maxfdp
, u_int
*nallocp
, int rekeying
)
564 struct timeval tv
, *tvp
;
568 /* Add any selections by the channel mechanism. */
569 channel_prepare_select(readsetp
, writesetp
, maxfdp
, nallocp
, rekeying
);
572 /* Read from the connection, unless our buffers are full. */
573 if (buffer_len(&stdout_buffer
) < buffer_high
&&
574 buffer_len(&stderr_buffer
) < buffer_high
&&
575 channel_not_very_much_buffered_data())
576 FD_SET(connection_in
, *readsetp
);
578 * Read from stdin, unless we have seen EOF or have very much
579 * buffered data to send to the server.
581 if (!stdin_eof
&& packet_not_very_much_data_to_write())
582 FD_SET(fileno(stdin
), *readsetp
);
584 /* Select stdout/stderr if have data in buffer. */
585 if (buffer_len(&stdout_buffer
) > 0)
586 FD_SET(fileno(stdout
), *writesetp
);
587 if (buffer_len(&stderr_buffer
) > 0)
588 FD_SET(fileno(stderr
), *writesetp
);
590 /* channel_prepare_select could have closed the last channel */
591 if (session_closed
&& !channel_still_open() &&
592 !packet_have_data_to_write()) {
593 /* clear mask since we did not call select() */
594 memset(*readsetp
, 0, *nallocp
);
595 memset(*writesetp
, 0, *nallocp
);
598 FD_SET(connection_in
, *readsetp
);
602 /* Select server connection if have data to write to the server. */
603 if (packet_have_data_to_write())
604 FD_SET(connection_out
, *writesetp
);
607 * Wait for something to happen. This will suspend the process until
608 * some selected descriptor can be read, written, or has some other
609 * event pending, or a timeout expires.
612 timeout_secs
= INT_MAX
; /* we use INT_MAX to mean no timeout */
613 if (options
.server_alive_interval
> 0 && compat20
)
614 timeout_secs
= options
.server_alive_interval
;
615 set_control_persist_exit_time();
616 if (control_persist_exit_time
> 0) {
617 timeout_secs
= MIN(timeout_secs
,
618 control_persist_exit_time
- time(NULL
));
619 if (timeout_secs
< 0)
622 if (timeout_secs
== INT_MAX
)
625 tv
.tv_sec
= timeout_secs
;
630 ret
= select((*maxfdp
)+1, *readsetp
, *writesetp
, NULL
, tvp
);
635 * We have to clear the select masks, because we return.
636 * We have to return, because the mainloop checks for the flags
637 * set by the signal handlers.
639 memset(*readsetp
, 0, *nallocp
);
640 memset(*writesetp
, 0, *nallocp
);
644 /* Note: we might still have data in the buffers. */
645 snprintf(buf
, sizeof buf
, "select: %s\r\n", strerror(errno
));
646 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
649 server_alive_check();
653 client_suspend_self(Buffer
*bin
, Buffer
*bout
, Buffer
*berr
)
655 /* Flush stdout and stderr buffers. */
656 if (buffer_len(bout
) > 0)
657 atomicio(vwrite
, fileno(stdout
), buffer_ptr(bout
),
659 if (buffer_len(berr
) > 0)
660 atomicio(vwrite
, fileno(stderr
), buffer_ptr(berr
),
663 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
666 * Free (and clear) the buffer to reduce the amount of data that gets
673 /* Send the suspend signal to the program itself. */
674 kill(getpid(), SIGTSTP
);
676 /* Reset window sizes in case they have changed */
677 received_window_change_signal
= 1;
679 /* OK, we have been continued by the user. Reinitialize buffers. */
684 enter_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
688 client_process_net_input(fd_set
*readset
)
691 char buf
[SSH_IOBUFSZ
];
694 * Read input from the server, and add any such data to the buffer of
695 * the packet subsystem.
697 if (FD_ISSET(connection_in
, readset
)) {
698 /* Read as much as possible. */
699 len
= roaming_read(connection_in
, buf
, sizeof(buf
), &cont
);
700 if (len
== 0 && cont
== 0) {
702 * Received EOF. The remote host has closed the
705 snprintf(buf
, sizeof buf
,
706 "Connection to %.300s closed by remote host.\r\n",
708 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
713 * There is a kernel bug on Solaris that causes select to
714 * sometimes wake up even though there is no data available.
717 (errno
== EAGAIN
|| errno
== EINTR
|| errno
== EWOULDBLOCK
))
722 * An error has encountered. Perhaps there is a
725 snprintf(buf
, sizeof buf
,
726 "Read from remote host %.300s: %.100s\r\n",
727 host
, strerror(errno
));
728 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
732 packet_process_incoming(buf
, len
);
737 client_status_confirm(int type
, Channel
*c
, void *ctx
)
739 struct channel_reply_ctx
*cr
= (struct channel_reply_ctx
*)ctx
;
744 * If a TTY was explicitly requested, then a failure to allocate
747 if (cr
->action
== CONFIRM_TTY
&&
748 (options
.request_tty
== REQUEST_TTY_FORCE
||
749 options
.request_tty
== REQUEST_TTY_YES
))
750 cr
->action
= CONFIRM_CLOSE
;
752 /* XXX supress on mux _client_ quietmode */
753 tochan
= options
.log_level
>= SYSLOG_LEVEL_ERROR
&&
754 c
->ctl_chan
!= -1 && c
->extended_usage
== CHAN_EXTENDED_WRITE
;
756 if (type
== SSH2_MSG_CHANNEL_SUCCESS
) {
757 debug2("%s request accepted on channel %d",
758 cr
->request_type
, c
->self
);
759 } else if (type
== SSH2_MSG_CHANNEL_FAILURE
) {
761 snprintf(errmsg
, sizeof(errmsg
),
762 "%s request failed\r\n", cr
->request_type
);
764 snprintf(errmsg
, sizeof(errmsg
),
765 "%s request failed on channel %d",
766 cr
->request_type
, c
->self
);
768 /* If error occurred on primary session channel, then exit */
769 if (cr
->action
== CONFIRM_CLOSE
&& c
->self
== session_ident
)
772 * If error occurred on mux client, append to
776 buffer_append(&c
->extended
, errmsg
,
780 if (cr
->action
== CONFIRM_TTY
) {
782 * If a TTY allocation error occurred, then arrange
783 * for the correct TTY to leave raw mode.
785 if (c
->self
== session_ident
)
788 mux_tty_alloc_failed(c
);
789 } else if (cr
->action
== CONFIRM_CLOSE
) {
791 chan_write_failed(c
);
798 client_abandon_status_confirm(Channel
*c
, void *ctx
)
804 client_expect_confirm(int id
, const char *request
,
805 enum confirm_action action
)
807 struct channel_reply_ctx
*cr
= xmalloc(sizeof(*cr
));
809 cr
->request_type
= request
;
812 channel_register_status_confirm(id
, client_status_confirm
,
813 client_abandon_status_confirm
, cr
);
817 client_register_global_confirm(global_confirm_cb
*cb
, void *ctx
)
819 struct global_confirm
*gc
, *last_gc
;
821 /* Coalesce identical callbacks */
822 last_gc
= TAILQ_LAST(&global_confirms
, global_confirms
);
823 if (last_gc
&& last_gc
->cb
== cb
&& last_gc
->ctx
== ctx
) {
824 if (++last_gc
->ref_count
>= INT_MAX
)
825 fatal("%s: last_gc->ref_count = %d",
826 __func__
, last_gc
->ref_count
);
830 gc
= xmalloc(sizeof(*gc
));
834 TAILQ_INSERT_TAIL(&global_confirms
, gc
, entry
);
838 process_cmdline(void)
840 void (*handler
)(int);
841 char *s
, *cmd
, *cancel_host
;
843 int local
= 0, remote
= 0, dynamic
= 0;
847 bzero(&fwd
, sizeof(fwd
));
848 fwd
.listen_host
= fwd
.connect_host
= NULL
;
850 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
851 handler
= signal(SIGINT
, SIG_IGN
);
852 cmd
= s
= read_passphrase("\r\nssh> ", RP_ECHO
);
858 s
++; /* Skip cmdline '-', if any */
862 if (*s
== 'h' || *s
== 'H' || *s
== '?') {
864 logit(" -L[bind_address:]port:host:hostport "
865 "Request local forward");
866 logit(" -R[bind_address:]port:host:hostport "
867 "Request remote forward");
868 logit(" -D[bind_address:]port "
869 "Request dynamic forward");
870 logit(" -KR[bind_address:]port "
871 "Cancel remote forward");
872 if (!options
.permit_local_command
)
875 "Execute local command");
879 if (*s
== '!' && options
.permit_local_command
) {
896 logit("Invalid command.");
900 if ((local
|| dynamic
) && delete) {
901 logit("Not supported.");
904 if (remote
&& delete && !compat20
) {
905 logit("Not supported for SSH protocol version 1.");
909 while (isspace(*++s
))
912 /* XXX update list of forwards in options */
915 cancel_host
= hpdelim(&s
); /* may be NULL */
917 cancel_port
= a2port(s
);
918 cancel_host
= cleanhostname(cancel_host
);
920 cancel_port
= a2port(cancel_host
);
923 if (cancel_port
<= 0) {
924 logit("Bad forwarding close port");
927 channel_request_rforward_cancel(cancel_host
, cancel_port
);
929 if (!parse_forward(&fwd
, s
, dynamic
, remote
)) {
930 logit("Bad forwarding specification.");
933 if (local
|| dynamic
) {
934 if (channel_setup_local_fwd_listener(fwd
.listen_host
,
935 fwd
.listen_port
, fwd
.connect_host
,
936 fwd
.connect_port
, options
.gateway_ports
) < 0) {
937 logit("Port forwarding failed.");
941 if (channel_request_remote_forwarding(fwd
.listen_host
,
942 fwd
.listen_port
, fwd
.connect_host
,
943 fwd
.connect_port
) < 0) {
944 logit("Port forwarding failed.");
949 logit("Forwarding port.");
953 signal(SIGINT
, handler
);
954 enter_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
957 if (fwd
.listen_host
!= NULL
)
958 xfree(fwd
.listen_host
);
959 if (fwd
.connect_host
!= NULL
)
960 xfree(fwd
.connect_host
);
964 * Process the characters one by one, call with c==NULL for proto1 case.
967 process_escapes(Channel
*c
, Buffer
*bin
, Buffer
*bout
, Buffer
*berr
,
976 int *escape_pendingp
, escape_char
;
977 struct escape_filter_ctx
*efc
;
980 escape_pendingp
= &escape_pending1
;
981 escape_char
= escape_char1
;
983 if (c
->filter_ctx
== NULL
)
985 efc
= (struct escape_filter_ctx
*)c
->filter_ctx
;
986 escape_pendingp
= &efc
->escape_pending
;
987 escape_char
= efc
->escape_char
;
993 for (i
= 0; i
< (u_int
)len
; i
++) {
994 /* Get one character at a time. */
997 if (*escape_pendingp
) {
998 /* We have previously seen an escape character. */
999 /* Clear the flag now. */
1000 *escape_pendingp
= 0;
1002 /* Process the escaped character. */
1005 /* Terminate the connection. */
1006 snprintf(string
, sizeof string
, "%c.\r\n",
1008 buffer_append(berr
, string
, strlen(string
));
1010 if (c
&& c
->ctl_chan
!= -1) {
1011 chan_read_failed(c
);
1012 chan_write_failed(c
);
1019 /* XXX support this for mux clients */
1020 if (c
&& c
->ctl_chan
!= -1) {
1022 snprintf(string
, sizeof string
,
1023 "%c%c escape not available to "
1024 "multiplexed sessions\r\n",
1026 buffer_append(berr
, string
,
1030 /* Suspend the program. Inform the user */
1031 snprintf(string
, sizeof string
,
1032 "%c^Z [suspend ssh]\r\n", escape_char
);
1033 buffer_append(berr
, string
, strlen(string
));
1035 /* Restore terminal modes and suspend. */
1036 client_suspend_self(bin
, bout
, berr
);
1038 /* We have been continued. */
1043 snprintf(string
, sizeof string
,
1044 "%cB\r\n", escape_char
);
1045 buffer_append(berr
, string
,
1047 channel_request_start(session_ident
,
1049 packet_put_int(1000);
1056 if (datafellows
& SSH_BUG_NOREKEY
)
1057 logit("Server does not "
1058 "support re-keying");
1065 if (c
&& c
->ctl_chan
!= -1)
1068 * Detach the program (continue to serve
1069 * connections, but put in background and no
1070 * more new connections).
1072 /* Restore tty modes. */
1074 options
.request_tty
== REQUEST_TTY_FORCE
);
1076 /* Stop listening for new connections. */
1077 channel_stop_listening();
1079 snprintf(string
, sizeof string
,
1080 "%c& [backgrounded]\n", escape_char
);
1081 buffer_append(berr
, string
, strlen(string
));
1083 /* Fork into background. */
1086 error("fork: %.100s", strerror(errno
));
1089 if (pid
!= 0) { /* This is the parent. */
1090 /* The parent just exits. */
1093 /* The child continues serving connections. */
1095 buffer_append(bin
, "\004", 1);
1096 /* fake EOF on stdin */
1098 } else if (!stdin_eof
) {
1100 * Sending SSH_CMSG_EOF alone does not
1101 * always appear to be enough. So we
1102 * try to send an EOF character first.
1104 packet_start(SSH_CMSG_STDIN_DATA
);
1105 packet_put_string("\004", 1);
1109 if (buffer_len(bin
) == 0) {
1110 packet_start(SSH_CMSG_EOF
);
1117 if (c
&& c
->ctl_chan
!= -1) {
1118 snprintf(string
, sizeof string
,
1120 Supported escape sequences:\r\n\
1121 %c. - terminate session\r\n\
1122 %cB - send a BREAK to the remote system\r\n\
1123 %cR - Request rekey (SSH protocol 2 only)\r\n\
1124 %c# - list forwarded connections\r\n\
1125 %c? - this message\r\n\
1126 %c%c - send the escape character by typing it twice\r\n\
1127 (Note that escapes are only recognized immediately after newline.)\r\n",
1128 escape_char
, escape_char
,
1129 escape_char
, escape_char
,
1130 escape_char
, escape_char
,
1131 escape_char
, escape_char
);
1133 snprintf(string
, sizeof string
,
1135 Supported escape sequences:\r\n\
1136 %c. - terminate connection (and any multiplexed sessions)\r\n\
1137 %cB - send a BREAK to the remote system\r\n\
1138 %cC - open a command line\r\n\
1139 %cR - Request rekey (SSH protocol 2 only)\r\n\
1140 %c^Z - suspend ssh\r\n\
1141 %c# - list forwarded connections\r\n\
1142 %c& - background ssh (when waiting for connections to terminate)\r\n\
1143 %c? - this message\r\n\
1144 %c%c - send the escape character by typing it twice\r\n\
1145 (Note that escapes are only recognized immediately after newline.)\r\n",
1146 escape_char
, escape_char
,
1147 escape_char
, escape_char
,
1148 escape_char
, escape_char
,
1149 escape_char
, escape_char
,
1150 escape_char
, escape_char
,
1153 buffer_append(berr
, string
, strlen(string
));
1157 snprintf(string
, sizeof string
, "%c#\r\n",
1159 buffer_append(berr
, string
, strlen(string
));
1160 s
= channel_open_message();
1161 buffer_append(berr
, s
, strlen(s
));
1166 if (c
&& c
->ctl_chan
!= -1)
1172 if (ch
!= escape_char
) {
1173 buffer_put_char(bin
, escape_char
);
1176 /* Escaped characters fall through here */
1181 * The previous character was not an escape char.
1182 * Check if this is an escape.
1184 if (last_was_cr
&& ch
== escape_char
) {
1186 * It is. Set the flag and continue to
1189 *escape_pendingp
= 1;
1195 * Normal character. Record whether it was a newline,
1196 * and append it to the buffer.
1198 last_was_cr
= (ch
== '\r' || ch
== '\n');
1199 buffer_put_char(bin
, ch
);
1206 client_process_input(fd_set
*readset
)
1209 char buf
[SSH_IOBUFSZ
];
1211 /* Read input from stdin. */
1212 if (FD_ISSET(fileno(stdin
), readset
)) {
1213 /* Read as much as possible. */
1214 len
= read(fileno(stdin
), buf
, sizeof(buf
));
1216 (errno
== EAGAIN
|| errno
== EINTR
|| errno
== EWOULDBLOCK
))
1217 return; /* we'll try again later */
1220 * Received EOF or error. They are treated
1221 * similarly, except that an error message is printed
1222 * if it was an error condition.
1225 snprintf(buf
, sizeof buf
, "read: %.100s\r\n",
1227 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1229 /* Mark that we have seen EOF. */
1232 * Send an EOF message to the server unless there is
1233 * data in the buffer. If there is data in the
1234 * buffer, no message will be sent now. Code
1235 * elsewhere will send the EOF when the buffer
1236 * becomes empty if stdin_eof is set.
1238 if (buffer_len(&stdin_buffer
) == 0) {
1239 packet_start(SSH_CMSG_EOF
);
1242 } else if (escape_char1
== SSH_ESCAPECHAR_NONE
) {
1244 * Normal successful read, and no escape character.
1245 * Just append the data to buffer.
1247 buffer_append(&stdin_buffer
, buf
, len
);
1250 * Normal, successful read. But we have an escape
1251 * character and have to process the characters one
1254 if (process_escapes(NULL
, &stdin_buffer
,
1255 &stdout_buffer
, &stderr_buffer
, buf
, len
) == -1)
1262 client_process_output(fd_set
*writeset
)
1267 /* Write buffered output to stdout. */
1268 if (FD_ISSET(fileno(stdout
), writeset
)) {
1269 /* Write as much data as possible. */
1270 len
= write(fileno(stdout
), buffer_ptr(&stdout_buffer
),
1271 buffer_len(&stdout_buffer
));
1273 if (errno
== EINTR
|| errno
== EAGAIN
||
1274 errno
== EWOULDBLOCK
)
1278 * An error or EOF was encountered. Put an
1279 * error message to stderr buffer.
1281 snprintf(buf
, sizeof buf
,
1282 "write stdout: %.50s\r\n", strerror(errno
));
1283 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1288 /* Consume printed data from the buffer. */
1289 buffer_consume(&stdout_buffer
, len
);
1291 /* Write buffered output to stderr. */
1292 if (FD_ISSET(fileno(stderr
), writeset
)) {
1293 /* Write as much data as possible. */
1294 len
= write(fileno(stderr
), buffer_ptr(&stderr_buffer
),
1295 buffer_len(&stderr_buffer
));
1297 if (errno
== EINTR
|| errno
== EAGAIN
||
1298 errno
== EWOULDBLOCK
)
1302 * EOF or error, but can't even print
1309 /* Consume printed characters from the buffer. */
1310 buffer_consume(&stderr_buffer
, len
);
1315 * Get packets from the connection input buffer, and process them as long as
1316 * there are packets available.
1318 * Any unknown packets received during the actual
1319 * session cause the session to terminate. This is
1320 * intended to make debugging easier since no
1321 * confirmations are sent. Any compatible protocol
1322 * extensions must be negotiated during the
1323 * preparatory phase.
1327 client_process_buffered_input_packets(void)
1329 dispatch_run(DISPATCH_NONBLOCK
, &quit_pending
,
1330 compat20
? xxx_kex
: NULL
);
1333 /* scan buf[] for '~' before sending data to the peer */
1335 /* Helper: allocate a new escape_filter_ctx and fill in its escape char */
1337 client_new_escape_filter_ctx(int escape_char
)
1339 struct escape_filter_ctx
*ret
;
1341 ret
= xmalloc(sizeof(*ret
));
1342 ret
->escape_pending
= 0;
1343 ret
->escape_char
= escape_char
;
1347 /* Free the escape filter context on channel free */
1349 client_filter_cleanup(int cid
, void *ctx
)
1355 client_simple_escape_filter(Channel
*c
, char *buf
, int len
)
1357 if (c
->extended_usage
!= CHAN_EXTENDED_WRITE
)
1360 return process_escapes(c
, &c
->input
, &c
->output
, &c
->extended
,
1365 client_channel_closed(int id
, void *arg
)
1367 channel_cancel_cleanup(id
);
1369 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
1373 * Implements the interactive session with the server. This is called after
1374 * the user has been authenticated, and a command has been started on the
1375 * remote host. If escape_char != SSH_ESCAPECHAR_NONE, it is the character
1376 * used as an escape character for terminating or suspending the session.
1380 client_loop(int have_pty
, int escape_char_arg
, int ssh2_chan_id
)
1382 fd_set
*readset
= NULL
, *writeset
= NULL
;
1383 double start_time
, total_time
;
1384 int max_fd
= 0, max_fd2
= 0, len
, rekeying
= 0;
1385 u_int64_t ibytes
, obytes
;
1389 debug("Entering interactive session.");
1391 start_time
= get_current_time();
1393 /* Initialize variables. */
1394 escape_pending1
= 0;
1398 buffer_high
= 64 * 1024;
1399 connection_in
= packet_get_connection_in();
1400 connection_out
= packet_get_connection_out();
1401 max_fd
= MAX(connection_in
, connection_out
);
1404 /* enable nonblocking unless tty */
1405 if (!isatty(fileno(stdin
)))
1406 set_nonblock(fileno(stdin
));
1407 if (!isatty(fileno(stdout
)))
1408 set_nonblock(fileno(stdout
));
1409 if (!isatty(fileno(stderr
)))
1410 set_nonblock(fileno(stderr
));
1411 max_fd
= MAX(max_fd
, fileno(stdin
));
1412 max_fd
= MAX(max_fd
, fileno(stdout
));
1413 max_fd
= MAX(max_fd
, fileno(stderr
));
1416 escape_char1
= escape_char_arg
;
1418 /* Initialize buffers. */
1419 buffer_init(&stdin_buffer
);
1420 buffer_init(&stdout_buffer
);
1421 buffer_init(&stderr_buffer
);
1423 client_init_dispatch();
1426 * Set signal handlers, (e.g. to restore non-blocking mode)
1427 * but don't overwrite SIG_IGN, matches behaviour from rsh(1)
1429 if (signal(SIGHUP
, SIG_IGN
) != SIG_IGN
)
1430 signal(SIGHUP
, signal_handler
);
1431 if (signal(SIGINT
, SIG_IGN
) != SIG_IGN
)
1432 signal(SIGINT
, signal_handler
);
1433 if (signal(SIGQUIT
, SIG_IGN
) != SIG_IGN
)
1434 signal(SIGQUIT
, signal_handler
);
1435 if (signal(SIGTERM
, SIG_IGN
) != SIG_IGN
)
1436 signal(SIGTERM
, signal_handler
);
1437 signal(SIGWINCH
, window_change_handler
);
1440 enter_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
1443 session_ident
= ssh2_chan_id
;
1444 if (session_ident
!= -1) {
1445 if (escape_char_arg
!= SSH_ESCAPECHAR_NONE
) {
1446 channel_register_filter(session_ident
,
1447 client_simple_escape_filter
, NULL
,
1448 client_filter_cleanup
,
1449 client_new_escape_filter_ctx(
1452 channel_register_cleanup(session_ident
,
1453 client_channel_closed
, 0);
1456 /* Check if we should immediately send eof on stdin. */
1457 client_check_initial_eof_on_stdin();
1460 /* Main loop of the client for the interactive session mode. */
1461 while (!quit_pending
) {
1463 /* Process buffered packets sent by the server. */
1464 client_process_buffered_input_packets();
1466 if (compat20
&& session_closed
&& !channel_still_open())
1469 rekeying
= (xxx_kex
!= NULL
&& !xxx_kex
->done
);
1472 debug("rekeying in progress");
1475 * Make packets of buffered stdin data, and buffer
1476 * them for sending to the server.
1479 client_make_packets_from_stdin_data();
1482 * Make packets from buffered channel data, and
1483 * enqueue them for sending to the server.
1485 if (packet_not_very_much_data_to_write())
1486 channel_output_poll();
1489 * Check if the window size has changed, and buffer a
1490 * message about it to the server if so.
1492 client_check_window_change();
1498 * Wait until we have something to do (something becomes
1499 * available on one of the descriptors).
1502 client_wait_until_can_do_something(&readset
, &writeset
,
1503 &max_fd2
, &nalloc
, rekeying
);
1508 /* Do channel operations unless rekeying in progress. */
1510 channel_after_select(readset
, writeset
);
1511 if (need_rekeying
|| packet_need_rekeying()) {
1512 debug("need rekeying");
1514 kex_send_kexinit(xxx_kex
);
1519 /* Buffer input from the connection. */
1520 client_process_net_input(readset
);
1526 /* Buffer data from stdin */
1527 client_process_input(readset
);
1529 * Process output to stdout and stderr. Output to
1530 * the connection is processed elsewhere (above).
1532 client_process_output(writeset
);
1535 if (session_resumed
) {
1536 connection_in
= packet_get_connection_in();
1537 connection_out
= packet_get_connection_out();
1538 max_fd
= MAX(max_fd
, connection_out
);
1539 max_fd
= MAX(max_fd
, connection_in
);
1540 session_resumed
= 0;
1544 * Send as much buffered packet data as possible to the
1547 if (FD_ISSET(connection_out
, writeset
))
1548 packet_write_poll();
1551 * If we are a backgrounded control master, and the
1552 * timeout has expired without any active client
1553 * connections, then quit.
1555 if (control_persist_exit_time
> 0) {
1556 if (time(NULL
) >= control_persist_exit_time
) {
1557 debug("ControlPersist timeout expired");
1567 /* Terminate the session. */
1569 /* Stop watching for window change. */
1570 signal(SIGWINCH
, SIG_DFL
);
1573 packet_start(SSH2_MSG_DISCONNECT
);
1574 packet_put_int(SSH2_DISCONNECT_BY_APPLICATION
);
1575 packet_put_cstring("disconnected by user");
1576 packet_put_cstring(""); /* language tag */
1578 packet_write_wait();
1584 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
1586 /* restore blocking io */
1587 if (!isatty(fileno(stdin
)))
1588 unset_nonblock(fileno(stdin
));
1589 if (!isatty(fileno(stdout
)))
1590 unset_nonblock(fileno(stdout
));
1591 if (!isatty(fileno(stderr
)))
1592 unset_nonblock(fileno(stderr
));
1595 * If there was no shell or command requested, there will be no remote
1596 * exit status to be returned. In that case, clear error code if the
1597 * connection was deliberately terminated at this end.
1599 if (no_shell_flag
&& received_signal
== SIGTERM
) {
1600 received_signal
= 0;
1604 if (received_signal
)
1605 fatal("Killed by signal %d.", (int) received_signal
);
1608 * In interactive mode (with pseudo tty) display a message indicating
1609 * that the connection has been closed.
1611 if (have_pty
&& options
.log_level
!= SYSLOG_LEVEL_QUIET
) {
1612 snprintf(buf
, sizeof buf
,
1613 "Connection to %.64s closed.\r\n", host
);
1614 buffer_append(&stderr_buffer
, buf
, strlen(buf
));
1617 /* Output any buffered data for stdout. */
1618 if (buffer_len(&stdout_buffer
) > 0) {
1619 len
= atomicio(vwrite
, fileno(stdout
),
1620 buffer_ptr(&stdout_buffer
), buffer_len(&stdout_buffer
));
1621 if (len
< 0 || (u_int
)len
!= buffer_len(&stdout_buffer
))
1622 error("Write failed flushing stdout buffer.");
1624 buffer_consume(&stdout_buffer
, len
);
1627 /* Output any buffered data for stderr. */
1628 if (buffer_len(&stderr_buffer
) > 0) {
1629 len
= atomicio(vwrite
, fileno(stderr
),
1630 buffer_ptr(&stderr_buffer
), buffer_len(&stderr_buffer
));
1631 if (len
< 0 || (u_int
)len
!= buffer_len(&stderr_buffer
))
1632 error("Write failed flushing stderr buffer.");
1634 buffer_consume(&stderr_buffer
, len
);
1637 /* Clear and free any buffers. */
1638 memset(buf
, 0, sizeof(buf
));
1639 buffer_free(&stdin_buffer
);
1640 buffer_free(&stdout_buffer
);
1641 buffer_free(&stderr_buffer
);
1643 /* Report bytes transferred, and transfer rates. */
1644 total_time
= get_current_time() - start_time
;
1645 packet_get_state(MODE_IN
, NULL
, NULL
, NULL
, &ibytes
);
1646 packet_get_state(MODE_OUT
, NULL
, NULL
, NULL
, &obytes
);
1647 verbose("Transferred: sent %llu, received %llu bytes, in %.1f seconds",
1648 (unsigned long long)obytes
, (unsigned long long)ibytes
, total_time
);
1650 verbose("Bytes per second: sent %.1f, received %.1f",
1651 obytes
/ total_time
, ibytes
/ total_time
);
1652 /* Return the exit status of the program. */
1653 debug("Exit status %d", exit_status
);
1660 client_input_stdout_data(int type
, u_int32_t seq
, void *ctxt
)
1663 char *data
= packet_get_string(&data_len
);
1665 buffer_append(&stdout_buffer
, data
, data_len
);
1666 memset(data
, 0, data_len
);
1670 client_input_stderr_data(int type
, u_int32_t seq
, void *ctxt
)
1673 char *data
= packet_get_string(&data_len
);
1675 buffer_append(&stderr_buffer
, data
, data_len
);
1676 memset(data
, 0, data_len
);
1680 client_input_exit_status(int type
, u_int32_t seq
, void *ctxt
)
1682 exit_status
= packet_get_int();
1684 /* Acknowledge the exit. */
1685 packet_start(SSH_CMSG_EXIT_CONFIRMATION
);
1688 * Must wait for packet to be sent since we are
1691 packet_write_wait();
1692 /* Flag that we want to exit. */
1696 client_input_agent_open(int type
, u_int32_t seq
, void *ctxt
)
1699 int remote_id
, sock
;
1701 /* Read the remote channel number from the message. */
1702 remote_id
= packet_get_int();
1706 * Get a connection to the local authentication agent (this may again
1709 sock
= ssh_get_authentication_socket();
1712 * If we could not connect the agent, send an error message back to
1713 * the server. This should never happen unless the agent dies,
1714 * because authentication forwarding is only enabled if we have an
1718 c
= channel_new("", SSH_CHANNEL_OPEN
, sock
, sock
,
1719 -1, 0, 0, 0, "authentication agent connection", 1);
1720 c
->remote_id
= remote_id
;
1724 packet_start(SSH_MSG_CHANNEL_OPEN_FAILURE
);
1725 packet_put_int(remote_id
);
1727 /* Send a confirmation to the remote host. */
1728 debug("Forwarding authentication connection.");
1729 packet_start(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
);
1730 packet_put_int(remote_id
);
1731 packet_put_int(c
->self
);
1737 client_request_forwarded_tcpip(const char *request_type
, int rchan
)
1740 char *listen_address
, *originator_address
;
1741 u_short listen_port
, originator_port
;
1743 /* Get rest of the packet */
1744 listen_address
= packet_get_string(NULL
);
1745 listen_port
= packet_get_int();
1746 originator_address
= packet_get_string(NULL
);
1747 originator_port
= packet_get_int();
1750 debug("client_request_forwarded_tcpip: listen %s port %d, "
1751 "originator %s port %d", listen_address
, listen_port
,
1752 originator_address
, originator_port
);
1754 c
= channel_connect_by_listen_address(listen_port
,
1755 "forwarded-tcpip", originator_address
);
1757 xfree(originator_address
);
1758 xfree(listen_address
);
1763 client_request_x11(const char *request_type
, int rchan
)
1767 u_short originator_port
;
1770 if (!options
.forward_x11
) {
1771 error("Warning: ssh server tried X11 forwarding.");
1772 error("Warning: this is probably a break-in attempt by a "
1773 "malicious server.");
1776 if (x11_refuse_time
!= 0 && time(NULL
) >= x11_refuse_time
) {
1777 verbose("Rejected X11 connection after ForwardX11Timeout "
1781 originator
= packet_get_string(NULL
);
1782 if (datafellows
& SSH_BUG_X11FWD
) {
1783 debug2("buggy server: x11 request w/o originator_port");
1784 originator_port
= 0;
1786 originator_port
= packet_get_int();
1789 /* XXX check permission */
1790 debug("client_request_x11: request from %s %d", originator
,
1793 sock
= x11_connect_display();
1796 /* again is this really necessary for X11? */
1797 if (options
.hpn_disabled
)
1798 c
= channel_new("x11",
1799 SSH_CHANNEL_X11_OPEN
, sock
, sock
, -1,
1800 CHAN_TCP_WINDOW_DEFAULT
, CHAN_X11_PACKET_DEFAULT
, 0, "x11", 1);
1802 c
= channel_new("x11",
1803 SSH_CHANNEL_X11_OPEN
, sock
, sock
, -1,
1804 options
.hpn_buffer_size
, CHAN_X11_PACKET_DEFAULT
, 0, "x11", 1);
1810 client_request_agent(const char *request_type
, int rchan
)
1815 if (!options
.forward_agent
) {
1816 error("Warning: ssh server tried agent forwarding.");
1817 error("Warning: this is probably a break-in attempt by a "
1818 "malicious server.");
1821 sock
= ssh_get_authentication_socket();
1824 if (options
.hpn_disabled
)
1825 c
= channel_new("authentication agent connection",
1826 SSH_CHANNEL_OPEN
, sock
, sock
, -1,
1827 CHAN_X11_WINDOW_DEFAULT
, CHAN_TCP_WINDOW_DEFAULT
, 0,
1828 "authentication agent connection", 1);
1830 c
= channel_new("authentication agent connection",
1831 SSH_CHANNEL_OPEN
, sock
, sock
, -1,
1832 options
.hpn_buffer_size
, options
.hpn_buffer_size
, 0,
1833 "authentication agent connection", 1);
1839 client_request_tun_fwd(int tun_mode
, int local_tun
, int remote_tun
)
1844 if (tun_mode
== SSH_TUNMODE_NO
)
1848 error("Tunnel forwarding is not supported for protocol 1");
1852 debug("Requesting tun unit %d in mode %d", local_tun
, tun_mode
);
1854 /* Open local tunnel device */
1855 if ((fd
= tun_open(local_tun
, tun_mode
)) == -1) {
1856 error("Tunnel device open failed.");
1860 if(options
.hpn_disabled
)
1861 c
= channel_new("tun", SSH_CHANNEL_OPENING
, fd
, fd
, -1,
1862 CHAN_TCP_WINDOW_DEFAULT
, CHAN_TCP_PACKET_DEFAULT
,
1865 c
= channel_new("tun", SSH_CHANNEL_OPENING
, fd
, fd
, -1,
1866 options
.hpn_buffer_size
, CHAN_TCP_PACKET_DEFAULT
,
1872 #if defined(SSH_TUN_FILTER)
1873 if (options
.tun_open
== SSH_TUNMODE_POINTOPOINT
)
1874 channel_register_filter(c
->self
, sys_tun_infilter
,
1875 sys_tun_outfilter
, NULL
, NULL
);
1878 packet_start(SSH2_MSG_CHANNEL_OPEN
);
1879 packet_put_cstring("tun@openssh.com");
1880 packet_put_int(c
->self
);
1881 packet_put_int(c
->local_window_max
);
1882 packet_put_int(c
->local_maxpacket
);
1883 packet_put_int(tun_mode
);
1884 packet_put_int(remote_tun
);
1890 /* XXXX move to generic input handler */
1892 client_input_channel_open(int type
, u_int32_t seq
, void *ctxt
)
1897 u_int rmaxpack
, rwindow
, len
;
1899 ctype
= packet_get_string(&len
);
1900 rchan
= packet_get_int();
1901 rwindow
= packet_get_int();
1902 rmaxpack
= packet_get_int();
1904 debug("client_input_channel_open: ctype %s rchan %d win %d max %d",
1905 ctype
, rchan
, rwindow
, rmaxpack
);
1907 if (strcmp(ctype
, "forwarded-tcpip") == 0) {
1908 c
= client_request_forwarded_tcpip(ctype
, rchan
);
1909 } else if (strcmp(ctype
, "x11") == 0) {
1910 c
= client_request_x11(ctype
, rchan
);
1911 } else if (strcmp(ctype
, "auth-agent@openssh.com") == 0) {
1912 c
= client_request_agent(ctype
, rchan
);
1914 /* XXX duplicate : */
1916 debug("confirm %s", ctype
);
1917 c
->remote_id
= rchan
;
1918 c
->remote_window
= rwindow
;
1919 c
->remote_maxpacket
= rmaxpack
;
1920 if (c
->type
!= SSH_CHANNEL_CONNECTING
) {
1921 packet_start(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
);
1922 packet_put_int(c
->remote_id
);
1923 packet_put_int(c
->self
);
1924 packet_put_int(c
->local_window
);
1925 packet_put_int(c
->local_maxpacket
);
1929 debug("failure %s", ctype
);
1930 packet_start(SSH2_MSG_CHANNEL_OPEN_FAILURE
);
1931 packet_put_int(rchan
);
1932 packet_put_int(SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED
);
1933 if (!(datafellows
& SSH_BUG_OPENFAILURE
)) {
1934 packet_put_cstring("open failed");
1935 packet_put_cstring("");
1942 client_input_channel_req(int type
, u_int32_t seq
, void *ctxt
)
1945 int exitval
, id
, reply
, success
= 0;
1948 id
= packet_get_int();
1949 rtype
= packet_get_string(NULL
);
1950 reply
= packet_get_char();
1952 debug("client_input_channel_req: channel %d rtype %s reply %d",
1956 error("client_input_channel_req: request for channel -1");
1957 } else if ((c
= channel_lookup(id
)) == NULL
) {
1958 error("client_input_channel_req: channel %d: "
1959 "unknown channel", id
);
1960 } else if (strcmp(rtype
, "eow@openssh.com") == 0) {
1963 } else if (strcmp(rtype
, "exit-status") == 0) {
1964 exitval
= packet_get_int();
1965 if (c
->ctl_chan
!= -1) {
1966 mux_exit_message(c
, exitval
);
1968 } else if (id
== session_ident
) {
1969 /* Record exit value of local session */
1971 exit_status
= exitval
;
1973 /* Probably for a mux channel that has already closed */
1974 debug("%s: no sink for exit-status on channel %d",
1979 if (reply
&& c
!= NULL
) {
1980 packet_start(success
?
1981 SSH2_MSG_CHANNEL_SUCCESS
: SSH2_MSG_CHANNEL_FAILURE
);
1982 packet_put_int(c
->remote_id
);
1988 client_input_global_request(int type
, u_int32_t seq
, void *ctxt
)
1994 rtype
= packet_get_string(NULL
);
1995 want_reply
= packet_get_char();
1996 debug("client_input_global_request: rtype %s want_reply %d",
1999 packet_start(success
?
2000 SSH2_MSG_REQUEST_SUCCESS
: SSH2_MSG_REQUEST_FAILURE
);
2002 packet_write_wait();
2008 client_session2_setup(int id
, int want_tty
, int want_subsystem
,
2009 const char *term
, struct termios
*tiop
, int in_fd
, Buffer
*cmd
, char **env
)
2014 debug2("%s: id %d", __func__
, id
);
2016 if ((c
= channel_lookup(id
)) == NULL
)
2017 fatal("client_session2_setup: channel %d: unknown channel", id
);
2019 packet_set_interactive(want_tty
,
2020 options
.ip_qos_interactive
, options
.ip_qos_bulk
);
2025 /* Store window size in the packet. */
2026 if (ioctl(in_fd
, TIOCGWINSZ
, &ws
) < 0)
2027 memset(&ws
, 0, sizeof(ws
));
2029 channel_request_start(id
, "pty-req", 1);
2030 client_expect_confirm(id
, "PTY allocation", CONFIRM_TTY
);
2031 packet_put_cstring(term
!= NULL
? term
: "");
2032 packet_put_int((u_int
)ws
.ws_col
);
2033 packet_put_int((u_int
)ws
.ws_row
);
2034 packet_put_int((u_int
)ws
.ws_xpixel
);
2035 packet_put_int((u_int
)ws
.ws_ypixel
);
2037 tiop
= get_saved_tio();
2038 tty_make_modes(-1, tiop
);
2040 /* XXX wait for reply */
2044 /* Transfer any environment variables from client to server */
2045 if (options
.num_send_env
!= 0 && env
!= NULL
) {
2049 debug("Sending environment.");
2050 for (i
= 0; env
[i
] != NULL
; i
++) {
2052 name
= xstrdup(env
[i
]);
2053 if ((val
= strchr(name
, '=')) == NULL
) {
2060 for (j
= 0; j
< options
.num_send_env
; j
++) {
2061 if (match_pattern(name
, options
.send_env
[j
])) {
2067 debug3("Ignored env %s", name
);
2072 debug("Sending env %s = %s", name
, val
);
2073 channel_request_start(id
, "env", 0);
2074 packet_put_cstring(name
);
2075 packet_put_cstring(val
);
2081 len
= buffer_len(cmd
);
2085 if (want_subsystem
) {
2086 debug("Sending subsystem: %.*s",
2087 len
, (u_char
*)buffer_ptr(cmd
));
2088 channel_request_start(id
, "subsystem", 1);
2089 client_expect_confirm(id
, "subsystem", CONFIRM_CLOSE
);
2091 debug("Sending command: %.*s",
2092 len
, (u_char
*)buffer_ptr(cmd
));
2093 channel_request_start(id
, "exec", 1);
2094 client_expect_confirm(id
, "exec", CONFIRM_CLOSE
);
2096 packet_put_string(buffer_ptr(cmd
), buffer_len(cmd
));
2099 channel_request_start(id
, "shell", 1);
2100 client_expect_confirm(id
, "shell", CONFIRM_CLOSE
);
2106 client_init_dispatch_20(void)
2108 dispatch_init(&dispatch_protocol_error
);
2110 dispatch_set(SSH2_MSG_CHANNEL_CLOSE
, &channel_input_oclose
);
2111 dispatch_set(SSH2_MSG_CHANNEL_DATA
, &channel_input_data
);
2112 dispatch_set(SSH2_MSG_CHANNEL_EOF
, &channel_input_ieof
);
2113 dispatch_set(SSH2_MSG_CHANNEL_EXTENDED_DATA
, &channel_input_extended_data
);
2114 dispatch_set(SSH2_MSG_CHANNEL_OPEN
, &client_input_channel_open
);
2115 dispatch_set(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION
, &channel_input_open_confirmation
);
2116 dispatch_set(SSH2_MSG_CHANNEL_OPEN_FAILURE
, &channel_input_open_failure
);
2117 dispatch_set(SSH2_MSG_CHANNEL_REQUEST
, &client_input_channel_req
);
2118 dispatch_set(SSH2_MSG_CHANNEL_WINDOW_ADJUST
, &channel_input_window_adjust
);
2119 dispatch_set(SSH2_MSG_CHANNEL_SUCCESS
, &channel_input_status_confirm
);
2120 dispatch_set(SSH2_MSG_CHANNEL_FAILURE
, &channel_input_status_confirm
);
2121 dispatch_set(SSH2_MSG_GLOBAL_REQUEST
, &client_input_global_request
);
2124 dispatch_set(SSH2_MSG_KEXINIT
, &kex_input_kexinit
);
2126 /* global request reply messages */
2127 dispatch_set(SSH2_MSG_REQUEST_FAILURE
, &client_global_request_reply
);
2128 dispatch_set(SSH2_MSG_REQUEST_SUCCESS
, &client_global_request_reply
);
2132 client_init_dispatch_13(void)
2134 dispatch_init(NULL
);
2135 dispatch_set(SSH_MSG_CHANNEL_CLOSE
, &channel_input_close
);
2136 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
, &channel_input_close_confirmation
);
2137 dispatch_set(SSH_MSG_CHANNEL_DATA
, &channel_input_data
);
2138 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION
, &channel_input_open_confirmation
);
2139 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE
, &channel_input_open_failure
);
2140 dispatch_set(SSH_MSG_PORT_OPEN
, &channel_input_port_open
);
2141 dispatch_set(SSH_SMSG_EXITSTATUS
, &client_input_exit_status
);
2142 dispatch_set(SSH_SMSG_STDERR_DATA
, &client_input_stderr_data
);
2143 dispatch_set(SSH_SMSG_STDOUT_DATA
, &client_input_stdout_data
);
2145 dispatch_set(SSH_SMSG_AGENT_OPEN
, options
.forward_agent
?
2146 &client_input_agent_open
: &deny_input_open
);
2147 dispatch_set(SSH_SMSG_X11_OPEN
, options
.forward_x11
?
2148 &x11_input_open
: &deny_input_open
);
2152 client_init_dispatch_15(void)
2154 client_init_dispatch_13();
2155 dispatch_set(SSH_MSG_CHANNEL_CLOSE
, &channel_input_ieof
);
2156 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION
, & channel_input_oclose
);
2160 client_init_dispatch(void)
2163 client_init_dispatch_20();
2165 client_init_dispatch_13();
2167 client_init_dispatch_15();
2171 client_stop_mux(void)
2173 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
2174 unlink(options
.control_path
);
2176 * If we are in persist mode, signal that we should close when all
2177 * active channels are closed.
2179 if (options
.control_persist
) {
2181 setproctitle("[stopped mux]");
2185 /* client specific fatal cleanup */
2189 leave_raw_mode(options
.request_tty
== REQUEST_TTY_FORCE
);
2190 leave_non_blocking();
2191 if (options
.control_path
!= NULL
&& muxserver_sock
!= -1)
2192 unlink(options
.control_path
);
2193 ssh_kill_proxy_command();